@edlsh/browse-core 0.4.1 → 0.5.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/dist/session.js CHANGED
@@ -4,16 +4,15 @@ import { createServer } from "node:net";
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { setTimeout as delay } from "node:timers/promises";
7
- import { Browserbase } from "@browserbasehq/sdk";
8
- import { browserbase, getExtensionArchive, localBrowser, Stagehand } from "@browserbasehq/stagehand";
9
7
  import { z } from "zod";
10
8
  import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
11
9
  import { guardEndpoint } from "./cdp-guard.js";
12
10
  import { HarRecorder } from "./har.js";
13
11
  import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
14
12
  import { BrokerConnection } from "./broker-client.js";
13
+ import { extensionCacheKey, extensionCachePath, provisionExtension } from "./extension-cache.js";
15
14
  import { randomUUID } from "node:crypto";
16
- import { pageOperation, tabsOperation } from "./page-operations.js";
15
+ import { cancelPageBatch, pageOperation, readOperation, tabsOperation, viewOperation } from "./page-operations.js";
17
16
  import { CookieSourceError, localCookieProvider, normalizeCookieDomains } from "./browser-cookies.js";
18
17
  import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, pickTarget, treeCandidates } from "./jev.js";
19
18
  import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
@@ -65,6 +64,11 @@ function stagehandPolicy(lists) {
65
64
  ...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
66
65
  };
67
66
  }
67
+ /**
68
+ * Stagehand and the Browserbase SDK load on first browser use. Loading them with this package cost every host about
69
+ * 85 ms at startup, whether or not the conversation ever opened a browser.
70
+ */
71
+ const stagehandSdk = () => import("@browserbasehq/stagehand");
68
72
  const REGIONS = ["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"];
69
73
  /** JEV's classifier unless jevModel names another: Jev on Vercel AI Gateway. */
70
74
  const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
@@ -72,6 +76,10 @@ const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
72
76
  const ASK_DEFAULT = { service: "workers-ai", model: CLEF };
73
77
  /** Actions that open a browser when none is open. */
74
78
  const OPENS_BROWSER = new Set(["start", "open", "tab_new", "cookie_import", "har_start"]);
79
+ /** Whether a call opens a browser when none is open: one of those actions, or a batch whose first step is open. */
80
+ function opensBrowser(p) {
81
+ return OPENS_BROWSER.has(p.action) || (p.action === "batch" && p.steps?.[0]?.action === "open");
82
+ }
75
83
  /** 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. */
76
84
  const SESSION_LIFETIME_SECONDS = 3600;
77
85
  /** Stagehand's errors once the transport to the remote browser is gone. */
@@ -80,14 +88,10 @@ const CONNECTION_LOST = /RPC client is closed|RPC client closed|CDP connection c
80
88
  const NOT_SENT = /RPC client is closed/i;
81
89
  /** Actions that are safe to repeat after a reconnect whatever happened to the first attempt. */
82
90
  const REPEATABLE = new Set(["open", "snapshot", "ask", "screenshot", "tabs", "wait", "live_view", "observe", "extract"]);
83
- /** Actions that keep snapshot refs: they change values, not which DOM nodes exist; target() still re-verifies each ref. */
84
- const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll"]);
85
- const DIRECT_ACTIONS = new Set(["snapshot", "click", "fill", "select", "press", "scroll", "evaluate", "tab_select"]);
86
- /**
87
- * A tab's first history entry, before any page: about:blank for the session's first tab, Stagehand's own start page
88
- * for tabs it opens. open only accepts http(s), so neither is a page the model navigated to.
89
- */
90
- const START_PAGE = /^(?:about:blank|chrome-extension:\/\/[a-p]{32}\/blank\.html)$/;
91
+ /** Actions that keep snapshot refs: they read, or change values, not which DOM nodes exist; each ref is still re-verified before use. */
92
+ const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll", "snapshot", "screenshot", "tab_select"]);
93
+ /** Actions that validate, act, and read their result beside the browser in one request. */
94
+ const DIRECT_ACTIONS = new Set(["start", "open", "back", "forward", "reload", "wait", "snapshot", "click", "fill", "select", "press", "scroll", "evaluate", "screenshot", "tab_select"]);
91
95
  /**
92
96
  * Stagehand launch defaults a persistent profile must drop: the mock Keychain encrypts its saved cookies with a fixed,
93
97
  * publicly known key, disabled background networking stops installed extensions from updating, and disabled default
@@ -171,8 +175,20 @@ const DIALOG_GUARD = `(() => {
171
175
  window.prompt = function prompt(message) { note("prompt", message, "cancel"); return null; };
172
176
  window.addEventListener("beforeunload", event => event.stopImmediatePropagation(), true);
173
177
  })()`;
174
- /** Takes the top frame's answered dialogs since the last read. */
175
- const TAKE_DIALOGS = "globalThis.__browserbaseDialogs?.splice(0) ?? []";
178
+ /** Whether an action can replace DOM nodes, which ends the use of earlier snapshot refs. */
179
+ function changesPage(p) {
180
+ return !KEEPS_REFS.has(p.action) || Boolean(p.url);
181
+ }
182
+ /** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
183
+ function scriptError(message) {
184
+ if (!/^Uncaught\b/.test(message))
185
+ return undefined;
186
+ const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
187
+ return new BrowseToolError("script_error", (detail
188
+ ? `The script threw: ${detail}.`
189
+ : "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
190
+ + " Side effects before the throw may have happened.");
191
+ }
176
192
  function messageOf(error) {
177
193
  return error instanceof Error ? error.message : String(error);
178
194
  }
@@ -183,7 +199,7 @@ function messageOf(error) {
183
199
  async function createStagehand(browser, model, signal) {
184
200
  for (let attempt = 0;; attempt++) {
185
201
  try {
186
- return await Stagehand.create({ browser, logging: { level: "off" }, ...model });
202
+ return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
187
203
  }
188
204
  catch (error) {
189
205
  if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
@@ -342,9 +358,12 @@ export function environmentConfig() {
342
358
  }
343
359
  export class BrowseToolError extends Error {
344
360
  code;
345
- constructor(code, message) {
361
+ batch;
362
+ /** `batch` is set on a failed batch call. */
363
+ constructor(code, message, batch) {
346
364
  super(message);
347
365
  this.code = code;
366
+ this.batch = batch;
348
367
  }
349
368
  }
350
369
  /** Shared browsers by key (`launch:<userDataDir>` or `attach:<cdpUrl>`), for every BrowseSession in this process. */
@@ -363,21 +382,6 @@ function operationTimeout(params, ai) {
363
382
  const wait = "durationMs" in params ? params.durationMs : undefined;
364
383
  return wait ? Math.max(30_000, wait + 5_000) : 30_000;
365
384
  }
366
- /**
367
- * Stagehand's goto resolves without a response when the browser cancels the navigation, leaving the tab on its start page;
368
- * Helium does this to a navigation made in about its first second after launch. One retry covers that; a second is an error.
369
- */
370
- async function navigate(page, url, timeout, signal) {
371
- const started = Date.now();
372
- for (let attempt = 1;; attempt++) {
373
- signal.throwIfAborted();
374
- const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: Math.max(1, timeout - (Date.now() - started)) });
375
- if (response || !START_PAGE.test(await page.url()))
376
- return response?.status();
377
- if (attempt === 2)
378
- throw new BrowseToolError("navigation_cancelled", "The browser cancelled the navigation twice and the tab is still blank. An extension or policy in this browser may block the URL; check it in the browser, or retry open.");
379
- }
380
- }
381
385
  /** Stops waiting immediately; the caller is responsible for closing the remote browser. */
382
386
  function abortable(promise, signal) {
383
387
  return new Promise((resolve, reject) => {
@@ -405,6 +409,10 @@ export class BrowseSession {
405
409
  session;
406
410
  queue = Promise.resolve();
407
411
  active;
412
+ /** Asks the running batch to stop before its next step. */
413
+ stopBatch;
414
+ /** Whether the running batch may have reached the browser, so its steps may have run. */
415
+ batchSent = false;
408
416
  snapshotNumber = 0;
409
417
  generation = 0;
410
418
  contextReadyAt = new Map();
@@ -415,8 +423,8 @@ export class BrowseSession {
415
423
  cookies;
416
424
  /** This conversation's calls run in the broker that owns its shared browser, until close. */
417
425
  delegate;
418
- /** Stagehand's runtime extension, uploaded once per tool instance instead of on every launch. */
419
- extension;
426
+ /** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
427
+ extensions = new Map();
420
428
  /** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
421
429
  stagehandModel;
422
430
  describeInference;
@@ -467,6 +475,7 @@ export class BrowseSession {
467
475
  if (this.delegate && this.delegate.owner !== this.owner(scope))
468
476
  await this.dropDelegate();
469
477
  controller.signal.throwIfAborted();
478
+ this.batchSent = false;
470
479
  return await abortable(this.dispatch(params, scope, isAi), controller.signal);
471
480
  }
472
481
  catch (error) {
@@ -478,6 +487,7 @@ export class BrowseSession {
478
487
  // The broker keeps or releases a shared browser by its own deadline; only the outcome here is unknown.
479
488
  if (this.delegate)
480
489
  throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. Take a snapshot before retrying.`);
490
+ await this.stopBatch?.();
481
491
  const kept = await this.keepIfResponsive(params.tabId);
482
492
  throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. ${{
483
493
  kept: "The browser still responds and was kept: take a snapshot before retrying.",
@@ -493,21 +503,26 @@ export class BrowseSession {
493
503
  }
494
504
  });
495
505
  this.queue = work.catch(() => undefined);
496
- return signal ? abortable(work, signal) : work;
506
+ const reply = signal ? abortable(work, signal) : work;
507
+ if (isAi || params.action !== "batch")
508
+ return reply;
509
+ // Every batch failure says how far the batch got, or that it cannot tell.
510
+ return reply.catch(cause => {
511
+ if (cause instanceof BrowseToolError && cause.batch)
512
+ throw cause;
513
+ const known = translate(cause);
514
+ const code = known instanceof BrowseToolError ? known.code : signal?.aborted ? "cancelled" : "browser_error";
515
+ const total = params.steps?.length ?? 0;
516
+ if (!this.batchSent)
517
+ throw new BrowseToolError(code, `${messageOf(known)} No batch steps were run.`, { total, completed: 0, outcomeUnknown: false });
518
+ throw new BrowseToolError(code, `${messageOf(known)} The batch may have partly run; inspect the page before repeating anything.`, { total, outcomeUnknown: true });
519
+ });
497
520
  }
498
521
  async shutdown() {
499
522
  this.generation++;
500
523
  this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
501
524
  // Begin releasing immediately, in case the host cuts shutdown handlers short.
502
525
  await Promise.all([this.closeOwned(), this.dropDelegate()]);
503
- // Only after release: a live session may still be using the extension. Best-effort within the host's shutdown time.
504
- // Content-Type is cleared on the bodyless DELETE as Stagehand's own cleanup does.
505
- const extension = this.extension;
506
- this.extension = undefined;
507
- if (extension) {
508
- await deadline(extension.id.then(id => extension.client.extensions.delete(id, { headers: { "Content-Type": null }, timeout: 500, maxRetries: 0 })), 500)
509
- .catch(() => undefined);
510
- }
511
526
  }
512
527
  /** Which credentials resolve for this profile. Starts no browser and leaves the session alone. */
513
528
  async readiness(context, signal) {
@@ -550,7 +565,7 @@ export class BrowseSession {
550
565
  }
551
566
  /** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
552
567
  async dispatch(params, context, ai) {
553
- if (!this.delegate && !this.session && this.profileBroker && !ai && OPENS_BROWSER.has(params.action)) {
568
+ if (!this.delegate && !this.session && this.profileBroker && !ai && opensBrowser(params)) {
554
569
  // SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
555
570
  const key = await this.sharedKey(params, context);
556
571
  // The broker reads cookies with its own machine's browsers, not a host's provider.
@@ -600,6 +615,8 @@ export class BrowseSession {
600
615
  async forward(params, context, ai) {
601
616
  const { conv, connection } = this.delegate;
602
617
  const { signal, purpose: _purpose, ...rest } = context;
618
+ // The broker reports a batch's progress itself; a broker that goes away mid-call leaves it unknown.
619
+ this.batchSent = true;
603
620
  try {
604
621
  const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal);
605
622
  if (params.action === "close")
@@ -636,7 +653,7 @@ export class BrowseSession {
636
653
  // Old and unused handles are dropped, never closed: closing any Browserbase handle releases the remote session.
637
654
  let browser, stagehand;
638
655
  try {
639
- browser = await connectRetrying(() => browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
656
+ browser = await connectRetrying(async () => (await stagehandSdk()).browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
640
657
  stagehand = await createStagehand(browser, this.stagehandModel, context.signal);
641
658
  }
642
659
  catch (error) {
@@ -785,27 +802,34 @@ export class BrowseSession {
785
802
  return;
786
803
  throw new BrowseToolError("visual_unsupported", `${classifierName(spec)} reads text only. Pick an image-capable classifier with /browse ${setting === "jevModel" ? "jev" : "ask"}-model (workers-ai, or one of the host's), or retry without visual.`);
787
804
  }
788
- /** The viewport as JPEG for a classifier: smaller than PNG, and every image-capable classifier takes it. */
789
- async viewport(page) {
790
- const image = await page.screenshot({ type: "jpeg", quality: 70, fullPage: false, timeout: 10_000 });
791
- return { mimeType: "image/jpeg", data: Buffer.from(image).toString("base64") };
792
- }
793
- client(config) {
805
+ async client(config) {
806
+ const { Browserbase } = await import("@browserbasehq/sdk");
794
807
  return new Browserbase({ apiKey: config.apiKey, timeout: 15_000, maxRetries: 0 });
795
808
  }
796
- extensionId(client) {
797
- if (!this.extension) {
798
- // No signal: a cancelled start leaves the upload cached for the next launch and for deletion at shutdown.
799
- const extension = { client, id: (async () => {
800
- const archive = await getExtensionArchive();
801
- const file = new File([archive.slice().buffer], "stagehand-extension.zip", { type: "application/zip" });
802
- return (await client.extensions.create({ file })).id;
803
- })() };
804
- this.extension = extension;
805
- extension.id.catch(() => { if (this.extension === extension)
806
- this.extension = undefined; });
807
- }
808
- return this.extension.id;
809
+ /**
810
+ * The project's uploaded Stagehand extension: the one the cache file remembers, else a new upload. `fresh` uploads
811
+ * again after the project turned out to have lost the remembered one.
812
+ */
813
+ extensionId(client, config, fresh = false) {
814
+ const key = extensionCacheKey(config.apiKey ?? "", config.projectId ?? "");
815
+ let extension = fresh ? undefined : this.extensions.get(key);
816
+ if (!extension) {
817
+ // No signal: a cancelled start leaves the upload remembered for the next launch.
818
+ extension = (async () => provisionExtension({
819
+ path: extensionCachePath(), key, archive: await (await stagehandSdk()).getExtensionArchive(), fresh,
820
+ upload: async () => {
821
+ const archive = await (await stagehandSdk()).getExtensionArchive();
822
+ return (await client.extensions.create({ file: new File([archive.slice().buffer], "stagehand-extension.zip", { type: "application/zip" }) })).id;
823
+ },
824
+ // Content-Type is cleared on the bodyless DELETE as Stagehand's own cleanup does.
825
+ remove: id => client.extensions.delete(id, { headers: { "Content-Type": null }, timeout: 5000, maxRetries: 0 }),
826
+ }))();
827
+ const pending = extension;
828
+ this.extensions.set(key, pending);
829
+ pending.catch(() => { if (this.extensions.get(key) === pending)
830
+ this.extensions.delete(key); });
831
+ }
832
+ return extension;
809
833
  }
810
834
  current() {
811
835
  if (!this.session || this.session.closing || this.session.browser.closed || !this.session.stagehand) {
@@ -853,13 +877,13 @@ export class BrowseSession {
853
877
  return this.joinShared(context, config, p, domainPolicy, attach, userDataDir);
854
878
  // A temporary profile belongs to this conversation alone.
855
879
  const port = await freePort();
856
- const browser = await localBrowser.launch({
880
+ const browser = await (await stagehandSdk()).localBrowser.launch({
857
881
  headless: headless ?? false, viewport: { width: 1280, height: 800 },
858
882
  ...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}), port,
859
883
  });
860
884
  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);
861
885
  }
862
- const client = this.client(config);
886
+ const client = await this.client(config);
863
887
  if (contextId) {
864
888
  const saved = await client.contexts.retrieve(contextId, { signal: context.signal }).catch(error => {
865
889
  throw error.status === 404
@@ -876,10 +900,11 @@ export class BrowseSession {
876
900
  if (remaining > 0)
877
901
  await delay(remaining, undefined, { signal: context.signal });
878
902
  }
879
- const extensionId = await this.extensionId(client);
903
+ let extension = await this.extensionId(client, config);
880
904
  context.signal.throwIfAborted();
881
- const launch = (keepAlive) => browserbase.launch({
882
- apiKey: config.apiKey, projectId: config.projectId, region: config.region, extensionId, api_timeout: SESSION_LIFETIME_SECONDS, keepAlive,
905
+ const { browserbase } = await stagehandSdk();
906
+ const create = (keepAlive) => browserbase.launch({
907
+ apiKey: config.apiKey, projectId: config.projectId, region: config.region, extensionId: extension.id, api_timeout: SESSION_LIFETIME_SECONDS, keepAlive,
883
908
  browserSettings: {
884
909
  viewport: { width: 1280, height: 800 }, ...(contextId ? { context: { id: contextId, persist: true } } : {}),
885
910
  ...(config.navigationPolicyId ? { riskPolicyId: config.navigationPolicyId } : {}),
@@ -887,6 +912,22 @@ export class BrowseSession {
887
912
  ...(proxyCountry ? { proxies: [{ type: "browserbase", geolocation: { country: proxyCountry } }] } : {}),
888
913
  userMetadata: { integration: this.identity.integration, profile: context.profile, conversation: context.sessionId },
889
914
  });
915
+ // Browserbase refuses a session that names an extension the project no longer has, and Stagehand hides why a
916
+ // session failed: after a failure with a remembered extension, ask whether it still exists, and upload again if not.
917
+ const launch = async (keepAlive) => {
918
+ try {
919
+ return await create(keepAlive);
920
+ }
921
+ catch (error) {
922
+ const gone = extension.cached && await client.extensions.retrieve(extension.id, { timeout: 5000, maxRetries: 0 })
923
+ .then(() => false, (cause) => cause.status === 404);
924
+ if (!gone)
925
+ throw error;
926
+ context.signal.throwIfAborted();
927
+ extension = await this.extensionId(client, config, true);
928
+ return create(keepAlive);
929
+ }
930
+ };
890
931
  let keepAlive = this.keepAliveAllowed;
891
932
  let browser;
892
933
  try {
@@ -911,7 +952,7 @@ export class BrowseSession {
911
952
  }
912
953
  this.session = session;
913
954
  try {
914
- session.stagehand = await Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
955
+ session.stagehand = await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
915
956
  context.signal.throwIfAborted();
916
957
  if (this.session !== session)
917
958
  throw abortError();
@@ -1008,7 +1049,7 @@ export class BrowseSession {
1008
1049
  // guard, and one that ends with this process would take the extension's connection down with the client's.
1009
1050
  const extensionCdpUrl = attach.extensionCdpUrl ?? opened.browserUrl;
1010
1051
  try {
1011
- browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url, extensionCdpUrl }), context.signal).catch(error => {
1052
+ browser = await connectRetrying(async () => (await stagehandSdk()).localBrowser.connect({ cdpUrl: opened.url, extensionCdpUrl }), context.signal).catch(error => {
1012
1053
  const known = translate(error);
1013
1054
  if (known instanceof BrowseToolError)
1014
1055
  throw known;
@@ -1023,9 +1064,9 @@ export class BrowseSession {
1023
1064
  else {
1024
1065
  // The avatar and profile menu then say which harness owns the window; a profile Chrome cannot rename still launches.
1025
1066
  await nameChromeProfile(userDataDir, `${this.identity.name} browse`).catch(() => undefined);
1026
- await refreshExtensionWorkers(userDataDir, await getExtensionArchive());
1067
+ await refreshExtensionWorkers(userDataDir, await (await stagehandSdk()).getExtensionArchive());
1027
1068
  quitPort = await freePort();
1028
- browser = await localBrowser.launch({
1069
+ browser = await (await stagehandSdk()).localBrowser.launch({
1029
1070
  headless: p.headless ?? false, viewport: { width: 1280, height: 800 },
1030
1071
  ...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}),
1031
1072
  port: quitPort, userDataDir, ignoreDefaultArgs: PERSISTENT_PROFILE_IGNORED_ARGS,
@@ -1216,17 +1257,34 @@ export class BrowseSession {
1216
1257
  const id = tabId ?? session.tabId;
1217
1258
  // In a shared browser only a tab chosen by id is taken over; no conversation drifts into the user's or a closed one.
1218
1259
  const page = id ? pages.find(page => page.pageId === id) : pages.find(page => session.ownedTabs.has(page.pageId)) ?? (session.shared ? undefined : pages[0]);
1219
- if (!page) {
1220
- throw new BrowseToolError("tab_missing", session.shared
1221
- ? "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."
1222
- : "The target tab is closed or missing. List tabs, select an existing tab, or create a new one.");
1223
- }
1260
+ if (!page)
1261
+ throw this.tabMissing(session);
1224
1262
  if (!session.tabId)
1225
1263
  session.tabId = page.pageId;
1226
1264
  // In a shared browser, acting on a tab claims it, so no other conversation can use it meanwhile.
1227
1265
  session.ownedTabs.add(page.pageId);
1228
1266
  return page;
1229
1267
  }
1268
+ /**
1269
+ * The tab a call acts on, named by its ID without asking the browser for its tabs: the batch executor finds the live tab
1270
+ * itself and reports a closed one. Only a call with no selected tab lists them. In a shared browser, acting on a tab
1271
+ * claims it before the request, so no other conversation can take it meanwhile.
1272
+ */
1273
+ async tab(session, tabId) {
1274
+ const id = tabId ?? session.tabId;
1275
+ if (!id)
1276
+ return this.page(session);
1277
+ if (this.ownedByOther(session, id))
1278
+ throw this.tabMissing(session);
1279
+ session.ownedTabs.add(id);
1280
+ const { Page } = await stagehandSdk();
1281
+ return new Page(session.stagehand.rpcClient, { pageId: id });
1282
+ }
1283
+ tabMissing(session) {
1284
+ return new BrowseToolError("tab_missing", session.shared
1285
+ ? "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."
1286
+ : "The target tab is closed or missing. List tabs, select an existing tab, or create a new one.");
1287
+ }
1230
1288
  /**
1231
1289
  * Runs one operation beside the browser in a single round trip. Stagehand cannot cancel a running batch: on a deadline
1232
1290
  * or cancellation the browser-side batch stops at its own timeout, and run() checks whether the browser still answers.
@@ -1235,77 +1293,159 @@ export class BrowseSession {
1235
1293
  context.signal.throwIfAborted();
1236
1294
  const result = await session.stagehand.experimentalBatch(operation, JSON.parse(JSON.stringify(input)), {
1237
1295
  ...(page ? { page } : {}), timeout: operationTimeout(p, false),
1296
+ }).catch(error => {
1297
+ if (!page || !/^Stagehand callback batch page was not found:/.test(messageOf(error)))
1298
+ throw error;
1299
+ // The tab closed since it was last seen: give up the claim tab() made on it.
1300
+ session.ownedTabs.delete(page.pageId);
1301
+ throw this.tabMissing(session);
1238
1302
  });
1239
1303
  // A cancelled reply must not install a late snapshot or alter the next call's selected tab.
1240
1304
  context.signal.throwIfAborted();
1241
1305
  return result;
1242
1306
  }
1243
- async direct(session, p, context) {
1244
- const changesPage = ["click", "press", "evaluate"].includes(p.action);
1307
+ /** One direct action as the worker runs it: the domain fence and snapshot refs are settled here, and the worker checks each ref again live. */
1308
+ prepare(session, p, budget) {
1245
1309
  const control = p.action === "click" || p.action === "fill" || p.action === "select";
1246
- const input = { ...p, action: p.action, readTimeoutMs: RESULT_READ_MS };
1247
- if (control) {
1248
- let target;
1249
- try {
1250
- target = this.reference(session, p.tabId ?? session.tabId, p.selector);
1251
- }
1252
- catch (error) {
1253
- if (changesPage)
1254
- session.snapshots.clear();
1255
- throw error;
1256
- }
1257
- const position = groupedPosition(target.selector);
1310
+ // Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
1311
+ const input = {
1312
+ ...p, action: p.action, readTimeoutMs: RESULT_READ_MS,
1313
+ pageTimeoutMs: Math.ceil(Math.max(budget - 2_000, budget / 2)), fenced: Boolean(session.domainPolicy),
1314
+ };
1315
+ // The worker writes the version into the refs it returns, so it is taken before the call; a failed call skips a number.
1316
+ if (p.action === "snapshot")
1317
+ input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000 };
1318
+ const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
1319
+ if (refused)
1320
+ throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
1321
+ if (control || (p.action === "wait" && p.selector)) {
1322
+ const target = this.reference(session, p.tabId ?? session.tabId, p.selector);
1323
+ const position = control ? groupedPosition(target.selector) : undefined;
1258
1324
  input.selector = position?.base ?? target.selector;
1259
1325
  input.nth = position?.index;
1260
1326
  if (target.cached)
1261
1327
  input.reference = { url: target.cached.url, id: target.refId, xpath: target.selector };
1262
1328
  }
1263
- let result;
1264
- try {
1265
- result = await this.batch(session, p, context, pageOperation, input, await this.page(session, p.tabId));
1266
- if (result.error) {
1267
- if (result.error.code === "stale_ref")
1268
- session.snapshots.delete(result.tabId);
1269
- throw new BrowseToolError(result.error.code, result.error.message);
1270
- }
1271
- }
1272
- catch (error) {
1273
- if (changesPage && !context.signal.aborted && !NOT_SENT.test(messageOf(error)))
1274
- session.snapshots.clear();
1275
- if (p.action !== "evaluate" || !/^Uncaught\b/.test(messageOf(error)))
1276
- throw error;
1277
- const detail = messageOf(error).replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
1278
- throw new BrowseToolError("script_error", (detail
1279
- ? `The script threw: ${detail}.`
1280
- : "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
1281
- + " Side effects before the throw may have happened.");
1282
- }
1283
- if (changesPage)
1329
+ return input;
1330
+ }
1331
+ /** Applies a completed action to the conversation's state (selected tab, snapshot refs) and returns what its result reports. */
1332
+ finish(session, p, input, result) {
1333
+ if (changesPage(p))
1284
1334
  session.snapshots.clear();
1285
1335
  if (!session.tabId || p.action === "tab_select")
1286
1336
  session.tabId = result.tabId;
1287
- const { value, snapshot, snapshotUrl, error: _error, ...view } = result;
1337
+ const { value, snapshot, snapshotUrl, navigation, image, error: _error, ...view } = result;
1288
1338
  let data;
1289
1339
  let note;
1290
1340
  if (snapshot) {
1291
- const version = `s${++this.snapshotNumber}`;
1292
- session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.xpathMap });
1293
- const tree = snapshot.formattedTree.replace(/\[(\d+-\d+)\]/g, `[${version}:$1]`);
1294
- const limit = p.maxChars ?? 20_000;
1295
- data = { snapshotId: version, tree: tree.slice(0, limit), truncated: tree.length > limit };
1341
+ const { version } = input.snapshot;
1342
+ session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.refs });
1343
+ data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated };
1296
1344
  }
1297
1345
  else if (p.action === "select") {
1298
- const selected = value;
1299
- if (!selected.length)
1300
- throw new BrowseToolError("not_select", "select works only on a native <select> element. For a custom dropdown, click it and then click the option.");
1301
- data = { selected };
1346
+ data = { selected: value };
1302
1347
  }
1303
1348
  else if (p.action === "evaluate") {
1304
1349
  data = value;
1305
1350
  if (value === null || value === undefined)
1306
1351
  note = "null can also mean undefined or a value JSON cannot carry (NaN, Infinity, -0, BigInt, a function); return String(value) to tell them apart.";
1307
1352
  }
1308
- return { ...await this.output(p.action, session), ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}) };
1353
+ else if (navigation) {
1354
+ data = navigation;
1355
+ }
1356
+ return { ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}), ...(image ? { image: new Uint8Array(Buffer.from(image, "base64")) } : {}) };
1357
+ }
1358
+ async direct(session, p, context) {
1359
+ let input, result;
1360
+ try {
1361
+ input = this.prepare(session, p, operationTimeout(p, false));
1362
+ result = await this.batch(session, p, context, pageOperation, input, await this.tab(session, p.tabId));
1363
+ if (result.error) {
1364
+ if (result.error.code === "stale_ref")
1365
+ session.snapshots.delete(result.tabId);
1366
+ throw new BrowseToolError(result.error.code, result.error.message);
1367
+ }
1368
+ }
1369
+ catch (error) {
1370
+ if (changesPage(p) && !NOT_SENT.test(messageOf(error)))
1371
+ session.snapshots.clear();
1372
+ throw (p.action === "evaluate" ? scriptError(messageOf(error)) : undefined) ?? error;
1373
+ }
1374
+ return { ...await this.output(p.action, session), ...this.finish(session, p, input, result) };
1375
+ }
1376
+ /**
1377
+ * batch: the steps run in order beside the browser in one request, under one deadline. The first failure stops the
1378
+ * rest and nothing is rolled back; the result says how many steps completed.
1379
+ */
1380
+ async sequence(session, p, context, budget) {
1381
+ // SAFETY: a step is a direct control's arguments, and every direct control is a BrowserParams.
1382
+ const steps = p.steps.map(step => ({ ...step, tabId: p.tabId }));
1383
+ const total = steps.length;
1384
+ const prepared = [];
1385
+ for (const step of steps) {
1386
+ try {
1387
+ prepared.push(this.prepare(session, step, budget));
1388
+ }
1389
+ catch (cause) {
1390
+ throw new BrowseToolError(cause instanceof BrowseToolError ? cause.code : "browser_error", `${messageOf(cause)} No batch steps were run.`, { total, completed: 0, failedIndex: prepared.length, outcomeUnknown: false });
1391
+ }
1392
+ }
1393
+ const page = await this.tab(session, p.tabId);
1394
+ const stagehand = session.stagehand;
1395
+ const id = randomUUID();
1396
+ let stopping;
1397
+ // A request of its own: the worker runs it while the batch waits on a step, and the batch stops before its next one.
1398
+ const stop = () => stopping ??= deadline(stagehand.experimentalBatch(cancelPageBatch, { id, ttlMs: budget + 15_000 }, { page, timeout: 2_000 }), 2_000)
1399
+ .then(() => undefined, () => undefined);
1400
+ const abort = () => { void stop(); };
1401
+ this.stopBatch = stop;
1402
+ context.signal.addEventListener("abort", abort, { once: true });
1403
+ let result;
1404
+ try {
1405
+ this.batchSent = true;
1406
+ result = await this.batch(session, p, context, pageOperation, { id, steps: prepared, timeoutMs: budget }, page);
1407
+ }
1408
+ catch (cause) {
1409
+ // Sent or not is all that is known here: run() reports the outcome as unknown unless the request never left.
1410
+ if (NOT_SENT.test(messageOf(cause)))
1411
+ this.batchSent = false;
1412
+ else
1413
+ session.snapshots.clear();
1414
+ throw cause;
1415
+ }
1416
+ finally {
1417
+ context.signal.removeEventListener("abort", abort);
1418
+ if (this.stopBatch === stop)
1419
+ this.stopBatch = undefined;
1420
+ }
1421
+ const results = result.results.map((step, index) => {
1422
+ const { tabId: _tab, ...reported } = this.finish(session, steps[index], prepared[index], step);
1423
+ return { action: steps[index].action, ...reported };
1424
+ });
1425
+ const progress = { total, completed: results.length, outcomeUnknown: false };
1426
+ const last = results.at(-1);
1427
+ const output = {
1428
+ ...await this.output(p.action, session), tabId: page.pageId, ...(last ? { url: last.url, title: last.title } : {}),
1429
+ // Progress comes before the results, so it survives a host that truncates a long result.
1430
+ batch: progress, data: { results },
1431
+ };
1432
+ if (result.failure) {
1433
+ const failed = steps[result.failure.index];
1434
+ const cause = result.failure.code === "browser_error"
1435
+ ? (failed.action === "evaluate" ? scriptError(result.failure.message) : undefined) ?? translate(new Error(result.failure.message))
1436
+ : new BrowseToolError(result.failure.code, result.failure.message);
1437
+ if (result.failure.outcomeUnknown || changesPage(failed))
1438
+ session.snapshots.clear();
1439
+ else if (result.failure.code === "stale_ref")
1440
+ session.snapshots.delete(page.pageId);
1441
+ progress.failedIndex = result.failure.index;
1442
+ progress.outcomeUnknown = result.failure.outcomeUnknown;
1443
+ progress.error = { code: cause instanceof BrowseToolError ? cause.code : "browser_error", message: this.redact(messageOf(cause)).slice(0, 4000) };
1444
+ output.isError = true;
1445
+ output.code = progress.error.code;
1446
+ output.note = "The batch stopped at the failed step: later steps did not run, and earlier ones were not rolled back. Inspect the page before repeating anything.";
1447
+ }
1448
+ return output;
1309
1449
  }
1310
1450
  reference(session, tabId, selector) {
1311
1451
  const reference = selector.replace(/^@/, "").replace(/^\[|\]$/g, "");
@@ -1326,34 +1466,16 @@ export class BrowseSession {
1326
1466
  }
1327
1467
  return { selector: xpath, cached, refId: match[2] };
1328
1468
  }
1329
- async target(session, page, selector) {
1330
- const target = this.reference(session, page.pageId, selector);
1331
- if (!target.cached)
1332
- return target.selector;
1333
- const [url, fresh] = await Promise.all([page.url(), page.snapshot({ includeIframes: true })]);
1334
- if (url !== target.cached.url || fresh.xpathMap[target.refId] !== target.selector) {
1335
- session.snapshots.delete(page.pageId);
1336
- throw new BrowseToolError("stale_ref", url !== target.cached.url
1337
- ? "The tab navigated since that snapshot. Take a new snapshot."
1338
- : "The referenced element changed or disappeared. Take a new snapshot.");
1339
- }
1340
- return target.selector;
1341
- }
1342
- async output(action, session, page, data) {
1343
- // Read in parallel, and bounded: the action already ran, so a tab that blocks now yields a result marked unresponsive
1344
- // rather than a failure. A page without the guard (or mid-navigation) reports no dialogs.
1345
- const view = page && await Promise.all([
1346
- page.url(),
1347
- deadline(page.title(), RESULT_READ_MS).catch(error => { if (expired(error))
1348
- return undefined; throw error; }),
1349
- deadline(page.evaluate(TAKE_DIALOGS), RESULT_READ_MS).catch(() => []),
1350
- ]);
1351
- const dialogs = view && Array.isArray(view[2]) && view[2].length ? { dialogs: view[2] } : {};
1469
+ /** A tab's URL, title, answered dialogs, and document identity, in one bounded request: the action already ran, so a tab that blocks now is reported unresponsive rather than failing. */
1470
+ view(session, page) {
1471
+ return session.stagehand.experimentalBatch(viewOperation, { readTimeoutMs: RESULT_READ_MS }, { page, timeout: RESULT_READ_MS + 5_000 });
1472
+ }
1473
+ async output(action, session, page, data, seen) {
1474
+ const { origin: _origin, ...view } = seen ?? (page ? await this.view(session, page) : { origin: null });
1352
1475
  return {
1353
1476
  action, sessionId: session.browser.sessionId ?? null, backend: session.backend, origin: session.browser.origin,
1354
1477
  ...(session.backend === "browserbase" ? { projectId: session.config.projectId, contextId: session.contextId } : {}),
1355
- ...(page && view ? { tabId: page.pageId, url: view[0], title: view[1] ?? null, ...(view[1] === undefined ? { responsive: false } : {}), ...dialogs } : {}),
1356
- ...(data === undefined ? {} : { data }),
1478
+ ...view, ...(data === undefined ? {} : { data }),
1357
1479
  };
1358
1480
  }
1359
1481
  /** A cookie provider call, with its refusals as tool errors. */
@@ -1382,9 +1504,6 @@ export class BrowseSession {
1382
1504
  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.`);
1383
1505
  }
1384
1506
  async browse(p, context) {
1385
- // Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
1386
- const budget = operationTimeout(p, false);
1387
- const pageTimeout = Math.ceil(Math.max(budget - 2_000, budget / 2));
1388
1507
  if (p.action === "cookie_profiles") {
1389
1508
  const browsers = await this.fromCookies(() => this.cookies.list(p.browser, context.signal));
1390
1509
  return { action: p.action, sessionId: null, data: { browsers } };
@@ -1415,7 +1534,7 @@ export class BrowseSession {
1415
1534
  if (this.session?.backend === "local")
1416
1535
  throw new BrowseToolError("unsupported_backend", "Saved contexts are Browserbase-only. Close the local browser first.");
1417
1536
  const config = await this.config(context);
1418
- const created = await this.client(config).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
1537
+ const created = await (await this.client(config)).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
1419
1538
  const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile };
1420
1539
  let historySaved = false;
1421
1540
  if (config.contextHistoryPath) {
@@ -1437,7 +1556,8 @@ export class BrowseSession {
1437
1556
  if (p.action === "har_start" && this.session?.browser.origin === "connected") {
1438
1557
  throw new BrowseToolError("unsupported_backend", "har_start records a browser this tool launched or hosts; an attached browser's tabs are the user's own.");
1439
1558
  }
1440
- const session = ["start", "open", "tab_new", "cookie_import", "har_start"].includes(p.action) ? await this.start(context, p) : this.current();
1559
+ const began = Date.now();
1560
+ const session = opensBrowser(p) ? await this.start(context, p) : this.current();
1441
1561
  context.signal.throwIfAborted();
1442
1562
  if (p.action === "har_start")
1443
1563
  return this.harStart(session, context);
@@ -1479,7 +1599,10 @@ export class BrowseSession {
1479
1599
  matched: imported.matched, imported: imported.cookies.length, skipped: imported.skipped,
1480
1600
  reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort || session.shared?.quitPort) });
1481
1601
  }
1482
- if (!p.target && DIRECT_ACTIONS.has(p.action) && !(p.action === "tab_select" && session.backend === "local"))
1602
+ // A batch that started a browser spent part of its deadline doing so.
1603
+ if (p.action === "batch")
1604
+ return this.sequence(session, p, context, Math.max(1_000, operationTimeout(p, false) - (Date.now() - began)));
1605
+ if (!p.target && DIRECT_ACTIONS.has(p.action))
1483
1606
  return this.direct(session, p, context);
1484
1607
  if (p.action === "tabs") {
1485
1608
  const input = { selectedTabId: session.tabId ?? null, readTimeoutMs: TAB_PROBE_MS };
@@ -1506,21 +1629,8 @@ export class BrowseSession {
1506
1629
  await session.har?.follow(page.pageId);
1507
1630
  return this.output(p.action, session, page);
1508
1631
  }
1509
- const page = await this.page(session, p.tabId);
1510
- if (p.action === "tab_select") {
1511
- context.signal.throwIfAborted();
1512
- await session.browser.context.setActivePage(page);
1513
- session.tabId = page.pageId;
1514
- return this.output(p.action, session, page);
1515
- }
1516
- if (p.action === "live_view") {
1517
- const live = await session.client.sessions.debug(session.browser.sessionId, { signal: context.signal, timeout: 10_000, maxRetries: 0 });
1518
- // A person may change anything in the page, so no earlier ref stays trustworthy.
1519
- session.snapshots.clear();
1520
- const liveViewUrl = live.pages.find(entry => entry.id === page.pageId)?.debuggerFullscreenUrl ?? live.debuggerFullscreenUrl;
1521
- return { ...await this.output(p.action, session, page), liveViewUrl };
1522
- }
1523
1632
  if (p.action === "tab_close") {
1633
+ const page = await this.page(session, p.tabId);
1524
1634
  context.signal.throwIfAborted();
1525
1635
  session.shared?.closedTabs.add(page.pageId);
1526
1636
  await page.close();
@@ -1533,68 +1643,24 @@ export class BrowseSession {
1533
1643
  }
1534
1644
  return this.output(p.action, session, undefined, { closedTabId: page.pageId, selectedTabId: session.tabId ?? null });
1535
1645
  }
1536
- if (p.action === "screenshot") {
1537
- const image = await page.screenshot({ type: "png", fullPage: p.fullPage ?? false, timeout: pageTimeout });
1538
- return { ...await this.output(p.action, session, page), image };
1539
- }
1540
- if (p.action === "ask")
1541
- return this.output(p.action, session, page, await this.ask(session, page, p.fields, context, p.visual));
1542
- const jev = p.target ? await this.locate(session, page, p.action, p.target, context, p.visual) : undefined;
1543
- if (jev && !jev.xpath)
1544
- return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.result.match === "none" ? "jev_none" : "jev_uncertain", isError: true };
1545
- if (jev) {
1546
- const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
1547
- return { ...output, data: { ...output.data, jev: jev.result } };
1548
- }
1549
- let data;
1550
- const changesPage = !KEEPS_REFS.has(p.action) || Boolean(p.url);
1551
- try {
1552
- switch (p.action) {
1553
- case "start":
1554
- case "open":
1555
- if (p.url) {
1556
- const refused = fenced(p.url, session.domainPolicy);
1557
- if (refused)
1558
- throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
1559
- data = { httpStatus: await navigate(page, p.url, pageTimeout, context.signal) };
1560
- // A redirect the fence refuses ends on Chrome's error page instead of throwing.
1561
- if (session.domainPolicy && (await page.url()).startsWith("chrome-error://")) {
1562
- throw new BrowseToolError("domain_blocked", "The navigation ended on Chrome's error page; this browser's domain policy likely refused a redirect. Check status for the allowed and blocked domains.");
1563
- }
1564
- }
1565
- break;
1566
- case "back":
1567
- case "forward":
1568
- case "reload": {
1569
- context.signal.throwIfAborted();
1570
- const options = { waitUntil: "domcontentloaded", timeout: pageTimeout };
1571
- const response = await (p.action === "back" ? page.goBack(options) : p.action === "forward" ? page.goForward(options) : page.reload(options));
1572
- // Going back to the start page would hand the model a blank tab, or an extension URL.
1573
- if (p.action === "back" && START_PAGE.test(await page.url())) {
1574
- await page.goForward(options);
1575
- throw new BrowseToolError("no_history", "This tab has no earlier page to go back to; it stays on the current page.");
1576
- }
1577
- data = { httpStatus: response?.status() };
1578
- break;
1579
- }
1580
- case "wait":
1581
- if (p.selector) {
1582
- const target = await this.target(session, page, p.selector);
1583
- context.signal.throwIfAborted();
1584
- await page.waitForSelector(target, { state: p.state ?? "visible", timeout: pageTimeout });
1585
- }
1586
- else if (p.loadState)
1587
- await page.waitForLoadState(p.loadState, pageTimeout);
1588
- else
1589
- await page.waitForTimeout(p.durationMs);
1590
- break;
1591
- }
1646
+ const page = await this.tab(session, p.tabId);
1647
+ if (p.action === "live_view") {
1648
+ const live = await session.client.sessions.debug(session.browser.sessionId, { signal: context.signal, timeout: 10_000, maxRetries: 0 });
1649
+ // A person may change anything in the page, so no earlier ref stays trustworthy.
1650
+ session.snapshots.clear();
1651
+ const liveViewUrl = live.pages.find(entry => entry.id === page.pageId)?.debuggerFullscreenUrl ?? live.debuggerFullscreenUrl;
1652
+ return { ...await this.output(p.action, session, page), liveViewUrl };
1592
1653
  }
1593
- finally {
1594
- if (changesPage)
1595
- session.snapshots.clear();
1654
+ if (p.action === "ask") {
1655
+ const { result, view } = await this.ask(session, page, p, context);
1656
+ return this.output(p.action, session, page, result, view);
1596
1657
  }
1597
- return this.output(p.action, session, page, data);
1658
+ // Every other action ran above; what is left names its element by target.
1659
+ const jev = await this.locate(session, page, p, p.target, context);
1660
+ if (!jev.xpath)
1661
+ return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.result.match === "none" ? "jev_none" : "jev_uncertain", isError: true };
1662
+ const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
1663
+ return { ...output, data: { ...output.data, jev: jev.result } };
1598
1664
  }
1599
1665
  /**
1600
1666
  * ask: Clairic reads values and a decision classifier (Clef unless askModel names another) answers bool and choice
@@ -1602,7 +1668,8 @@ export class BrowseSession {
1602
1668
  * leave answers about a page that is gone, under the new page's URL and title, so a changed document (its timeOrigin)
1603
1669
  * redoes the read once.
1604
1670
  */
1605
- async ask(session, page, fields, context, visual) {
1671
+ async ask(session, page, p, context) {
1672
+ const fields = p.fields, visual = p.visual;
1606
1673
  const needs = askNeeds(fields);
1607
1674
  const config = await this.purposeConfig(session, context, "ask");
1608
1675
  const decider = needs.decide ? this.classifier("ask", config) : undefined;
@@ -1615,22 +1682,24 @@ export class BrowseSession {
1615
1682
  ...(accountId && apiKey ? { cloudflare: { accountId, apiKey } } : {}),
1616
1683
  ...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
1617
1684
  };
1618
- // A context destroyed mid-navigation reads as NaN, which never matches, so the read is redone.
1619
- const document = () => page.evaluate("performance.timeOrigin").catch(() => NaN);
1620
1685
  for (let attempt = 1;; attempt++) {
1621
- const before = await document();
1622
- const [snapshot, url, title, image] = await Promise.all([page.snapshot({ includeIframes: true }), page.url(), page.title(), visual ? this.viewport(page) : undefined]);
1686
+ // One request reads the document's identity, the tree, and the viewport; ask needs no XPaths.
1687
+ const read = await this.batch(session, p, context, readOperation, { refs: false, image: Boolean(visual) }, page);
1688
+ // A context destroyed mid-navigation has no origin to report, which never matches, so the read is redone.
1689
+ const before = read.origin;
1623
1690
  let result;
1624
1691
  try {
1625
- result = await askPage({ ...models, ...(image ? { images: [image] } : {}) }, { url, title, tree: snapshot.formattedTree }, fields, context.signal);
1692
+ result = await askPage({ ...models, ...(read.image ? { images: [{ mimeType: "image/jpeg", data: read.image }] } : {}) }, { url: read.url, title: read.title, tree: read.tree }, fields, context.signal);
1626
1693
  }
1627
1694
  catch (error) {
1628
1695
  if (context.signal.aborted)
1629
1696
  throw error;
1630
1697
  throw new BrowseToolError("ask_error", `${messageOf(error)} Take a snapshot and read the page instead.`);
1631
1698
  }
1632
- if (await document() === before)
1633
- return result;
1699
+ // The closing read doubles as the result's view of the tab.
1700
+ const view = await this.view(session, page);
1701
+ if (before !== null && view.origin === before)
1702
+ return { result, view };
1634
1703
  if (attempt === 2)
1635
1704
  throw new BrowseToolError("page_changed", "The page navigated while ask read it, twice. Wait for it to settle (wait with a selector on the expected page, or loadState networkidle), then ask again.");
1636
1705
  }
@@ -1639,16 +1708,19 @@ export class BrowseSession {
1639
1708
  * JEV mode: a classifier (Jev unless jevModel names another) picks the element for a plain-language target from a
1640
1709
  * fresh snapshot; no xpath means it declined to act.
1641
1710
  */
1642
- async locate(session, page, action, target, context, visual) {
1711
+ async locate(session, page, p, target, context) {
1712
+ const action = p.action, visual = p.visual;
1643
1713
  const { spec, classify } = this.classifier("jev", await this.purposeConfig(session, context, "jev"));
1644
1714
  const model = classifierName(spec);
1645
1715
  if (visual)
1646
1716
  this.visualAllowed(spec, "jevModel");
1647
- const snapshot = await page.snapshot({ includeIframes: true });
1648
- const candidates = treeCandidates(snapshot.formattedTree).filter(c => snapshot.xpathMap[c.ref] && fitsAction(action, c, snapshot.xpathMap[c.ref]));
1717
+ // One request reads the tree, the XPaths a target can name, and the viewport.
1718
+ const read = await this.batch(session, p, context, readOperation, { refs: true, image: Boolean(visual) }, page);
1719
+ const refs = read.refs ?? {}, { url, title } = read;
1720
+ const image = read.image ? { mimeType: "image/jpeg", data: read.image } : undefined;
1721
+ const candidates = treeCandidates(read.tree).filter(c => refs[c.ref] && fitsAction(action, c, refs[c.ref]));
1649
1722
  if (!candidates.length)
1650
1723
  throw new BrowseToolError("jev_no_candidates", "The page has no elements this action can target. Take a snapshot to inspect it.");
1651
- const [url, title, image] = await Promise.all([page.url(), page.title(), visual ? this.viewport(page) : undefined]);
1652
1724
  let pick;
1653
1725
  try {
1654
1726
  pick = await pickTarget(candidates, { url, title, action, request: target }, jevChooser(classify, image && [image]), context.signal);
@@ -1662,9 +1734,9 @@ export class BrowseSession {
1662
1734
  }
1663
1735
  // Keep this snapshot so returned candidate selectors work without another snapshot.
1664
1736
  const version = `s${++this.snapshotNumber}`;
1665
- session.snapshots.set(page.pageId, { version, url, refs: snapshot.xpathMap });
1737
+ session.snapshots.set(page.pageId, { version, url, refs });
1666
1738
  if (pick.chosen)
1667
- return { xpath: snapshot.xpathMap[pick.chosen.ref], result: { model, label: pick.chosen.label, confidence: pick.confidence } };
1739
+ return { xpath: refs[pick.chosen.ref], result: { model, label: pick.chosen.label, confidence: pick.confidence } };
1668
1740
  return { xpath: undefined, result: {
1669
1741
  model, acted: false, match: pick.none ? "none" : "uncertain", confidence: pick.confidence, threshold: JEV_MIN_CONFIDENCE,
1670
1742
  candidates: pick.ranked.map(c => ({ selector: `@${version}:${c.ref}`, label: c.label, probability: c.probability })),