@edlsh/browse-core 0.6.4 → 0.8.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.
Files changed (49) hide show
  1. package/README.md +23 -2
  2. package/dist/broker-client.d.ts +4 -2
  3. package/dist/broker-client.js +12 -6
  4. package/dist/broker-protocol.d.ts +3 -2
  5. package/dist/broker-protocol.js +11 -7
  6. package/dist/broker.js +12 -12
  7. package/dist/cdp-connection.d.ts +18 -0
  8. package/dist/cdp-connection.js +59 -0
  9. package/dist/config.d.ts +101 -0
  10. package/dist/config.js +78 -0
  11. package/dist/contexts.d.ts +10 -0
  12. package/dist/contexts.js +27 -0
  13. package/dist/errors.d.ts +29 -0
  14. package/dist/errors.js +83 -0
  15. package/dist/har.d.ts +1 -6
  16. package/dist/har.js +16 -56
  17. package/dist/host-model.d.ts +24 -0
  18. package/dist/host-model.js +35 -0
  19. package/dist/http-auth.d.ts +14 -0
  20. package/dist/http-auth.js +114 -0
  21. package/dist/index.d.ts +10 -13
  22. package/dist/index.js +11 -15
  23. package/dist/jev.js +9 -3
  24. package/dist/page-operations.d.ts +11 -1
  25. package/dist/page-operations.js +62 -11
  26. package/dist/real-browser-ai.d.ts +1 -1
  27. package/dist/real-browser-ai.js +1 -1
  28. package/dist/real-browser-client.js +1 -1
  29. package/dist/real-browser-session.d.ts +1 -1
  30. package/dist/real-browser-session.js +24 -5
  31. package/dist/schema.d.ts +34 -0
  32. package/dist/schema.js +29 -6
  33. package/dist/session-runtime.d.ts +42 -0
  34. package/dist/session-runtime.js +144 -0
  35. package/dist/session.d.ts +29 -108
  36. package/dist/session.js +189 -364
  37. package/dist/settings.js +47 -6
  38. package/dist/tool-results.d.ts +28 -0
  39. package/dist/tool-results.js +40 -0
  40. package/extensions/http-auth/README.md +27 -0
  41. package/extensions/http-auth/background.js +85 -0
  42. package/extensions/http-auth/manifest.json +27 -0
  43. package/extensions/http-auth/native/README.md +31 -0
  44. package/extensions/http-auth/native/host.py +97 -0
  45. package/extensions/http-auth/native/install.py +62 -0
  46. package/extensions/http-auth/options.html +25 -0
  47. package/extensions/http-auth/options.js +36 -0
  48. package/extensions/http-auth/origin.js +16 -0
  49. package/package.json +14 -2
package/dist/session.js CHANGED
@@ -1,12 +1,15 @@
1
- import { once } from "node:events";
2
- import { appendFile, mkdir } from "node:fs/promises";
3
- import { createServer } from "node:net";
1
+ import { abortable, abortError, BrowseToolError, deadline, messageOf, scriptError, translate } from "./errors.js";
2
+ import { domainLists, environmentConfig, fenced, stagehandPolicy } from "./config.js";
3
+ import { freePort, connectRetrying, createStagehand, ensurePageTarget, release, withRawCdp, quitChrome, stagehandSdk } from "./session-runtime.js";
4
+ import { contextRegistry, rememberContext, knownContext } from "./contexts.js";
4
5
  import { tmpdir } from "node:os";
5
- import { dirname, join } from "node:path";
6
+ import { join } from "node:path";
6
7
  import { setTimeout as delay } from "node:timers/promises";
7
8
  import { z } from "zod";
8
9
  import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
9
10
  import { guardEndpoint } from "./cdp-guard.js";
11
+ import { answerHttpAuth, resolveHttpAuth } from "./http-auth.js";
12
+ import { encodeFailure, ToolResults } from "./tool-results.js";
10
13
  import { HarRecorder, writeCaptureHar } from "./har.js";
11
14
  import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
12
15
  import { BrokerConnection } from "./broker-client.js";
@@ -15,62 +18,9 @@ import { extractPage, observePage } from "./real-browser-ai.js";
15
18
  import { extensionCacheKey, extensionCachePath, provisionExtension } from "./extension-cache.js";
16
19
  import { createHash, randomUUID } from "node:crypto";
17
20
  import { cancelPageBatch, pageOperation, readOperation, tabsOperation, viewOperation } from "./page-operations.js";
18
- import { CookieSourceError, localCookieProvider, normalizeCookieDomains } from "./browser-cookies.js";
21
+ import { CookieSourceError, localCookieProvider } from "./browser-cookies.js";
19
22
  import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, outlineCandidates, pickTarget, treeCandidates } from "./jev.js";
20
23
  import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
21
- /** Whether `domain` is `parent` or one of its subdomains. */
22
- function within(domain, parent) {
23
- return domain === parent || domain.endsWith(`.${parent}`);
24
- }
25
- /** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
26
- export function domainLists(config, start) {
27
- const normalize = (domains, setting) => {
28
- if (!domains?.length)
29
- return undefined;
30
- try {
31
- return normalizeCookieDomains(domains);
32
- }
33
- catch (error) {
34
- throw new BrowseToolError("configuration", `${setting}: ${messageOf(error)}`);
35
- }
36
- };
37
- const profileAllowed = normalize(config.allowedDomains, "the profile's allowedDomains");
38
- const startAllowed = normalize(start.allowedDomains, "allowedDomains");
39
- if (profileAllowed && startAllowed) {
40
- const outside = startAllowed.filter(domain => !profileAllowed.some(parent => within(domain, parent)));
41
- if (outside.length)
42
- throw new BrowseToolError("domain_policy_widened", `allowedDomains can only narrow this profile's allowed domains (${profileAllowed.join(", ")}); ${outside.join(", ")} is outside them.`);
43
- }
44
- const allowedDomains = startAllowed ?? profileAllowed;
45
- const blockedDomains = [...new Set([...normalize(config.blockedDomains, "the profile's blockedDomains") ?? [], ...normalize(start.blockedDomains, "blockedDomains") ?? []])];
46
- if (!allowedDomains && !blockedDomains.length)
47
- return undefined;
48
- return { ...(allowedDomains ? { allowedDomains } : {}), ...(blockedDomains.length ? { blockedDomains } : {}) };
49
- }
50
- /** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
51
- function fenced(url, lists) {
52
- if (!lists || !URL.canParse(url))
53
- return undefined;
54
- const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
55
- if (lists.blockedDomains?.some(domain => within(host, domain)))
56
- return `${host} is in this browser's blocked domains (${lists.blockedDomains.join(", ")})`;
57
- if (lists.allowedDomains && !lists.allowedDomains.some(domain => within(host, domain)))
58
- return `${host} is outside this browser's allowed domains (${lists.allowedDomains.join(", ")})`;
59
- return undefined;
60
- }
61
- /** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
62
- function stagehandPolicy(lists) {
63
- const patterns = (domains) => domains.flatMap(domain => [domain, `*.${domain}`]);
64
- return {
65
- ...(lists.allowedDomains ? { allowedDomains: patterns(lists.allowedDomains) } : {}),
66
- ...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
67
- };
68
- }
69
- /**
70
- * Stagehand and the Browserbase SDK load on first browser use. Loading them with this package cost every host about
71
- * 85 ms at startup, whether or not the conversation ever opened a browser.
72
- */
73
- const stagehandSdk = () => import("@browserbasehq/stagehand");
74
24
  const REGIONS = ["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"];
75
25
  /** JEV's classifier unless jevModel names another: Jev on Vercel AI Gateway. */
76
26
  const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
@@ -93,66 +43,13 @@ const REPEATABLE = new Set(["open", "snapshot", "ask", "screenshot", "tabs", "wa
93
43
  /** Actions that keep snapshot refs: they read, or change values, not which DOM nodes exist; each ref is still re-verified before use. */
94
44
  const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll", "snapshot", "screenshot", "tab_select"]);
95
45
  /** Actions that validate, act, and read their result beside the browser in one request. */
96
- const DIRECT_ACTIONS = new Set(["start", "open", "back", "forward", "reload", "wait", "snapshot", "click", "fill", "select", "press", "scroll", "evaluate", "screenshot", "tab_select"]);
46
+ const DIRECT_ACTIONS = new Set(["start", "open", "back", "forward", "reload", "wait", "snapshot", "click", "fill", "select", "press", "scroll", "evaluate", "screenshot", "tab_select", "hover", "upload", "viewport"]);
97
47
  /**
98
48
  * Stagehand launch defaults a persistent profile must drop: the mock Keychain encrypts its saved cookies with a fixed,
99
49
  * publicly known key, disabled background networking stops installed extensions from updating, and disabled default
100
50
  * apps makes Chrome skip the profile's `External Extensions` directory, which preinstalls Web Store extensions.
101
51
  */
102
52
  const PERSISTENT_PROFILE_IGNORED_ARGS = ["--use-mock-keychain", "--password-store=basic", "--disable-background-networking", "--disable-default-apps"];
103
- async function freePort() {
104
- const server = createServer().listen(0, "127.0.0.1");
105
- await once(server, "listening");
106
- const { port } = server.address();
107
- await new Promise(resolve => server.close(resolve));
108
- return port;
109
- }
110
- /**
111
- * Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
112
- * writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
113
- * close then has nothing left to signal, so a persistent profile keeps its logins.
114
- */
115
- async function quitChrome(port) {
116
- const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
117
- const socket = new WebSocket((await version.json()).webSocketDebuggerUrl);
118
- let pid;
119
- socket.addEventListener("message", event => {
120
- const reply = JSON.parse(String(event.data));
121
- if (reply.id === 1)
122
- pid = reply.result?.processInfo?.find(entry => entry.type === "browser")?.id;
123
- });
124
- const closed = once(socket, "close");
125
- socket.addEventListener("open", () => {
126
- socket.send(JSON.stringify({ id: 1, method: "SystemInfo.getProcessInfo" }));
127
- socket.send(JSON.stringify({ id: 2, method: "Browser.close" }));
128
- }, { once: true });
129
- await closed;
130
- // The endpoint closes before Chrome finishes writing the profile.
131
- for (let i = 0; pid && i < 200 && running(pid); i++)
132
- await delay(20);
133
- }
134
- /** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
135
- async function connectRetrying(connect, signal) {
136
- for (let attempt = 0;; attempt++) {
137
- try {
138
- return await connect();
139
- }
140
- catch (error) {
141
- if (attempt >= 3 || !/No target with given id found/.test(messageOf(error)))
142
- throw error;
143
- await delay(100, undefined, { signal });
144
- }
145
- }
146
- }
147
- function running(pid) {
148
- try {
149
- process.kill(pid, 0);
150
- return true;
151
- }
152
- catch (error) {
153
- return error.code === "EPERM";
154
- }
155
- }
156
53
  /** How long a tab may take to answer a trivial evaluate before it counts as unresponsive. */
157
54
  const TAB_PROBE_MS = 2_000;
158
55
  /** How long the reads after a completed action may take before the result reports the tab unresponsive instead of failing. */
@@ -178,140 +75,10 @@ const DIALOG_GUARD = `(() => {
178
75
  window.addEventListener("beforeunload", event => event.stopImmediatePropagation(), true);
179
76
  })()`;
180
77
  /** Whether an action can replace DOM nodes, which ends the use of earlier snapshot refs. */
78
+ function shifted(key) { return /^shift\+(?:.|space|spacebar)$/iu.test(key ?? ""); }
181
79
  function changesPage(p) {
182
80
  return !KEEPS_REFS.has(p.action) || Boolean(p.url);
183
81
  }
184
- /** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
185
- function scriptError(message) {
186
- if (!/^Uncaught\b/.test(message))
187
- return undefined;
188
- const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
189
- return new BrowseToolError("script_error", (detail
190
- ? `The script threw: ${detail}.`
191
- : "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
192
- + " Side effects before the throw may have happened.");
193
- }
194
- function messageOf(error) {
195
- return error instanceof Error ? error.message : String(error);
196
- }
197
- /**
198
- * Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
199
- * instance asynchronously, so a create that arrives first sees it still initialized and is retried.
200
- */
201
- async function createStagehand(browser, model, signal) {
202
- for (let attempt = 0;; attempt++) {
203
- try {
204
- return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
205
- }
206
- catch (error) {
207
- if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
208
- throw error;
209
- await delay(250, undefined, { signal });
210
- }
211
- }
212
- }
213
- /** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
214
- async function withRawCdp(connectUrl, signal, use) {
215
- const socket = new WebSocket(connectUrl);
216
- const pending = new Map();
217
- let nextId = 0;
218
- const closed = new Promise((_, reject) => {
219
- const fail = () => reject(new Error("CDP connection closed"));
220
- socket.addEventListener("close", fail);
221
- socket.addEventListener("error", fail);
222
- });
223
- closed.catch(() => undefined);
224
- socket.addEventListener("message", event => {
225
- const message = JSON.parse(String(event.data));
226
- const entry = pending.get(message.id);
227
- if (!entry)
228
- return;
229
- pending.delete(message.id);
230
- if (message.error)
231
- entry.reject(new Error(message.error.message));
232
- else
233
- entry.resolve(message.result);
234
- });
235
- const send = (method, params = {}, sessionId) => {
236
- const id = ++nextId;
237
- const reply = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
238
- socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
239
- return abortable(Promise.race([reply, closed]), signal);
240
- };
241
- try {
242
- await abortable(Promise.race([new Promise(resolve => socket.addEventListener("open", resolve, { once: true })), closed]), signal);
243
- return await use(send);
244
- }
245
- finally {
246
- socket.close();
247
- }
248
- }
249
- /**
250
- * Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
251
- * Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
252
- * attach. The tab belongs to whoever attaches, whose close removes it again.
253
- */
254
- async function ensurePageTarget(connectUrl, signal) {
255
- return withRawCdp(connectUrl, signal, async (send) => {
256
- const { targetInfos } = await send("Target.getTargets");
257
- if (targetInfos.some(target => target.type === "page"))
258
- return undefined;
259
- const { targetId } = await send("Target.createTarget", { url: "about:blank", newWindow: true });
260
- return z.string().parse(targetId);
261
- });
262
- }
263
- /**
264
- * Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
265
- * the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
266
- */
267
- async function release(shared) {
268
- if (shared.guard) {
269
- try {
270
- await deadline(shared.browser.disconnect(), 5000);
271
- }
272
- finally {
273
- await shared.guard.close();
274
- }
275
- return;
276
- }
277
- await deadline(shared.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
278
- if (shared.quitPort)
279
- await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
280
- await deadline(shared.browser.close(), 5000);
281
- }
282
- /** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
283
- function translate(error) {
284
- if (error instanceof BrowseToolError)
285
- return error;
286
- const message = messageOf(error);
287
- if (/ERR_BLOCKED_BY_CLIENT/.test(message))
288
- return new BrowseToolError("domain_blocked", "The browser's domain policy blocked this request. status lists the allowed and blocked domains; close and start again to change them, or ask the user to change the profile's.");
289
- if (/^No Page found|^Stagehand callback batch page was not found:|^Stagehand has no active page\.|^Stagehand page ".+" was not found;/.test(message))
290
- return new BrowseToolError("tab_missing", "The tab closed or navigated away during the action. List tabs, select one, and take a snapshot.");
291
- if (/^Connection error\.?$/.test(message))
292
- return new BrowseToolError("network_error", "Could not reach Browserbase. Retry once; if it persists, check this machine's network.");
293
- // Stagehand admits one client per browser and refuses a second while the first is connected.
294
- if (/A Stagehand client is already connected/.test(message))
295
- return new BrowseToolError("browser_in_use", "Another Stagehand client is connected to this browser, and a browser takes one at a time: a conversation on another machine, or another tool. Close the browser there, then start again.");
296
- if (/does not support the client watchdog|requires Chrome 137 or later/.test(message))
297
- return new BrowseToolError("attach_failed", "This browser cannot take this version of Stagehand: it needs Chrome 137 or newer and the Stagehand extension this tool ships. Update the browser and reinstall the extension in it, then start again.");
298
- // Stagehand's own per-request limit: the tab stopped answering, typically a busy script.
299
- const rpc = /^RPC response timed out: (\S+)/.exec(message);
300
- if (rpc)
301
- return new BrowseToolError("timeout", `Stagehand got no reply for ${rpc[1]} in time; the action may have completed. The tab may be busy: check status, and if it reports tab_unresponsive, call tab_new and tab_close that tab.`);
302
- // Page-level waits and navigations that ran out of time, in Stagehand's wording, sometimes wrapped as a page exception.
303
- const pageTimeout = /^(?:Uncaught (?:\(in promise\) )?(?:Error: )?)?(.*(?:timed out after \d+ ?ms|Timeout \d+ ?ms exceeded).*)$/s.exec(message);
304
- if (pageTimeout)
305
- return new BrowseToolError("timeout", `${pageTimeout[1].slice(0, 300)}. The browser was kept; take a snapshot to check the page, or raise timeoutMs.`);
306
- // Strict structured output (OpenAI models on Model Gateway) rejects schemas with optional properties.
307
- if (/^Invalid schema for response_format/.test(message)) {
308
- return new BrowseToolError("invalid_arguments", `The model rejected the extract schema: ${message.slice(0, 300)} List every property in required, and allow null for values that may be missing.`);
309
- }
310
- if (/extension world not ready for frame/i.test(message)) {
311
- return new BrowseToolError("frame_unavailable", "Stagehand cannot reach that document: legacy <frame> pages, browser error pages, and frames still loading are unsupported. Take a snapshot and use its refs, or wait for the page and retry.");
312
- }
313
- return error;
314
- }
315
82
  /** `(expr)[n]` with balanced outer parentheses. Stagehand's shadow-DOM XPath resolver ignores a grouped position. */
316
83
  function groupedPosition(selector) {
317
84
  const text = selector.trim().replace(/^xpath=/, "");
@@ -336,45 +103,10 @@ function groupedPosition(selector) {
336
103
  }
337
104
  return { base: `xpath=${match[1]}`, index: Number(match[2]) - 1 };
338
105
  }
339
- /** A comma- or space-separated domain list from the environment; empty counts as unset. */
340
- function domainList(value) {
341
- const domains = value?.split(/[\s,]+/).filter(Boolean);
342
- return domains?.length ? domains : undefined;
343
- }
344
- export function environmentConfig() {
345
- return {
346
- apiKey: process.env.BROWSERBASE_API_KEY ?? "",
347
- projectId: process.env.BROWSERBASE_PROJECT_ID ?? "",
348
- model: process.env.STAGEHAND_MODEL,
349
- modelApiKey: process.env.STAGEHAND_MODEL_API_KEY,
350
- jevApiKey: process.env.AI_GATEWAY_API_KEY,
351
- cloudflareAccountId: process.env.CLOUDFLARE_ACCOUNT_ID,
352
- cloudflareApiKey: process.env.CLOUDFLARE_API_KEY,
353
- region: process.env.BROWSERBASE_REGION,
354
- allowedDomains: domainList(process.env.BROWSE_ALLOWED_DOMAINS),
355
- blockedDomains: domainList(process.env.BROWSE_BLOCKED_DOMAINS),
356
- navigationPolicyId: process.env.BROWSERBASE_NAVIGATION_POLICY_ID,
357
- jevModel: process.env.BROWSE_JEV_MODEL,
358
- askModel: process.env.BROWSE_ASK_MODEL,
359
- };
360
- }
361
- export class BrowseToolError extends Error {
362
- code;
363
- batch;
364
- /** `batch` is set on a failed batch call. */
365
- constructor(code, message, batch) {
366
- super(message);
367
- this.code = code;
368
- this.batch = batch;
369
- }
370
- }
371
106
  /** Shared browsers by key (`launch:<userDataDir>` or `attach:<cdpUrl>`), for every BrowseSession in this process. */
372
107
  const sharedBrowsers = new Map();
373
108
  /** A shared browser still quitting; a new launch of the same profile waits for Chrome to release it. */
374
109
  const retiringBrowsers = new Map();
375
- function abortError(message = "Operation cancelled.") {
376
- return new BrowseToolError("cancelled", message);
377
- }
378
110
  /** A fixed wait needs headroom past its own duration, or the default deadline would reject waits the schema allows. */
379
111
  function operationTimeout(params, ai) {
380
112
  if (params.timeoutMs)
@@ -387,26 +119,6 @@ function operationTimeout(params, ai) {
387
119
  const wait = "durationMs" in params ? params.durationMs : undefined;
388
120
  return wait ? Math.max(30_000, wait + 5_000) : 30_000;
389
121
  }
390
- /** Stops waiting immediately; the caller is responsible for closing the remote browser. */
391
- function abortable(promise, signal) {
392
- return new Promise((resolve, reject) => {
393
- const abort = () => reject(signal.reason ?? abortError());
394
- signal.addEventListener("abort", abort, { once: true });
395
- promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
396
- if (signal.aborted)
397
- abort();
398
- });
399
- }
400
- async function deadline(promise, ms) {
401
- const controller = new AbortController();
402
- const timer = setTimeout(() => controller.abort(new BrowseToolError("timeout", "Browser cleanup timed out.")), ms);
403
- try {
404
- return await abortable(promise, controller.signal);
405
- }
406
- finally {
407
- clearTimeout(timer);
408
- }
409
- }
410
122
  export class BrowseSession {
411
123
  resolveConfig;
412
124
  hostClassify;
@@ -421,6 +133,7 @@ export class BrowseSession {
421
133
  snapshotNumber = 0;
422
134
  generation = 0;
423
135
  contextReadyAt = new Map();
136
+ results = new ToolResults();
424
137
  secrets = new Set();
425
138
  /** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
426
139
  keepAliveAllowed = true;
@@ -434,7 +147,9 @@ export class BrowseSession {
434
147
  extensions = new Map();
435
148
  /** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
436
149
  stagehandModel;
150
+ aiOwner = { inference: {}, aiTurn: Promise.resolve() };
437
151
  describeInference;
152
+ defaultGenerate;
438
153
  /** 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. */
439
154
  defaultBackend = "local";
440
155
  constructor(resolveConfig = environmentConfig, inference, hostClassify, identity = { name: "Host", integration: "browse-core" }, options = {}) {
@@ -443,9 +158,19 @@ export class BrowseSession {
443
158
  this.identity = identity;
444
159
  this.profileBroker = options.profileBroker ?? true;
445
160
  this.cookies = options.cookies ?? localCookieProvider;
446
- this.stagehandModel = inference ? { model: { generate: inference.generate } } : {};
447
- this.describeInference = inference?.describe ?? (async () => "gateway-auto");
448
- }
161
+ this.stagehandModel = inference ? { model: { generate: params => {
162
+ if (!this.aiOwner.inference.generate)
163
+ throw abortError("No active browser model call.");
164
+ return this.aiOwner.inference.generate(params);
165
+ } } } : {};
166
+ this.describeInference = inference?.describe.bind(inference) ?? (async () => "gateway-auto");
167
+ this.defaultGenerate = inference?.generate?.bind(inference);
168
+ }
169
+ /** Host-facing output. Keep raw run() available for SDK consumers and the broker. */
170
+ encodeResult(output, scope) {
171
+ return this.results.encode(output, this.owner(scope), text => this.redact(text));
172
+ }
173
+ encodeError(cause) { return encodeFailure(cause, text => this.redact(text)); }
449
174
  redact(text) {
450
175
  // Longest first: a shorter secret nested in a longer one must not leave the longer one's remainder visible.
451
176
  for (const secret of [...this.secrets].sort((a, b) => b.length - a.length))
@@ -468,8 +193,6 @@ export class BrowseSession {
468
193
  signal?.throwIfAborted();
469
194
  if (generation !== this.generation)
470
195
  throw abortError("The conversation changed before this browser operation started.");
471
- if (typeof ai === "function")
472
- ai();
473
196
  const controller = new AbortController();
474
197
  const cancel = () => controller.abort(abortError());
475
198
  signal?.addEventListener("abort", cancel, { once: true });
@@ -485,7 +208,14 @@ export class BrowseSession {
485
208
  await this.closeReal();
486
209
  controller.signal.throwIfAborted();
487
210
  this.batchSent = false;
488
- return await abortable(this.dispatch(params, scope, isAi), controller.signal);
211
+ const scoped = typeof ai === "function" ? ai(controller.signal) : undefined;
212
+ const defaultGenerate = this.defaultGenerate;
213
+ const provider = scoped || (defaultGenerate && (p => defaultGenerate(p, controller.signal)));
214
+ const generate = isAi && provider ? p => {
215
+ controller.signal.throwIfAborted();
216
+ return abortable(Promise.resolve(provider(p)), controller.signal);
217
+ } : undefined;
218
+ return await abortable(this.dispatch(params, scope, isAi, generate), controller.signal);
489
219
  }
490
220
  catch (error) {
491
221
  // Shutdown releases the browser itself. A fired deadline or cancellation leaves only the last action's
@@ -507,6 +237,8 @@ export class BrowseSession {
507
237
  }
508
238
  finally {
509
239
  clearTimeout(timer);
240
+ if (isAi)
241
+ controller.abort(abortError("The browser model call has ended."));
510
242
  signal?.removeEventListener("abort", cancel);
511
243
  if (this.active === controller)
512
244
  this.active = undefined;
@@ -529,6 +261,7 @@ export class BrowseSession {
529
261
  });
530
262
  }
531
263
  async shutdown() {
264
+ this.results.clear();
532
265
  this.generation++;
533
266
  this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
534
267
  // Begin releasing immediately, in case the host cuts shutdown handlers short.
@@ -560,7 +293,8 @@ export class BrowseSession {
560
293
  const jevClassifier = describe("jev", jev), askClassifier = describe("ask", ask);
561
294
  return {
562
295
  credentials: Boolean(browser?.apiKey?.trim() && browser?.projectId?.trim()),
563
- region: browser?.region || "Browserbase default",
296
+ region: browser?.region && !REGIONS.some(r => r === browser.region) ? `invalid (${browser.region}; expected ${REGIONS.join(", ")})` : browser?.region || "Browserbase default",
297
+ regionValid: !browser?.region || REGIONS.some(r => r === browser.region),
564
298
  aiModel: browser?.model?.trim() || undefined,
565
299
  jevModel: jevClassifier.model,
566
300
  jevKey: jevClassifier.key,
@@ -571,16 +305,20 @@ export class BrowseSession {
571
305
  };
572
306
  }
573
307
  owner(context) {
574
- return `${context.profile}:${context.sessionId}`;
308
+ return JSON.stringify([context.profile, context.sessionId]);
575
309
  }
576
310
  /** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
577
- async dispatch(params, context, ai) {
311
+ async dispatch(params, context, ai, generate) {
312
+ if (!ai && params.action === "result_read")
313
+ return { action: params.action, sessionId: null, data: this.results.read(this.owner(context), params.resultId, params.offset ?? 0) };
314
+ if (params.action === "close")
315
+ this.results.clear();
578
316
  // SAFETY: only browse actions open a browser, and browse_ai calls were excluded.
579
317
  if (!this.real && !this.delegate && !this.session && !ai && opensBrowser(params))
580
318
  this.real = await this.realBrowser(params, context);
581
319
  if (this.real) {
582
320
  try {
583
- return await this.inRealBrowser(this.real, params, context, ai);
321
+ return await this.inRealBrowser(this.real, params, context, ai, generate);
584
322
  }
585
323
  catch (error) {
586
324
  // OpenCode Browse is gone, and this conversation's tabs with it: the next start may choose another browser.
@@ -606,9 +344,11 @@ export class BrowseSession {
606
344
  if (this.delegate && !ai && params.action === "cookie_import" && this.cookies !== localCookieProvider) {
607
345
  throw new BrowseToolError("unsupported_backend", "This host's cookie source imports into Browserbase sessions only. Close, start with backend \"browserbase\", then cookie_import.");
608
346
  }
347
+ if (this.delegate && !ai && params.action === "start" && params.httpAuth)
348
+ throw new BrowseToolError("browser_change", "Close the shared browser before starting an isolated HTTP-auth session.");
609
349
  if (this.delegate)
610
- return this.forward(params, context, ai);
611
- const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
350
+ return this.forward(params, context, ai, generate);
351
+ const attempt = () => ai ? this.ai(params, context, generate) : this.browse(params, context);
612
352
  try {
613
353
  return await attempt();
614
354
  }
@@ -624,7 +364,7 @@ export class BrowseSession {
624
364
  }
625
365
  /** The shared browser a call would open, as the broker keys it: an attached browser or a persistent profile; else none. */
626
366
  async sharedKey(p, context) {
627
- if ((p.backend ?? this.defaultBackend) !== "local")
367
+ if (p.httpAuth || (p.backend ?? this.defaultBackend) !== "local")
628
368
  return undefined;
629
369
  if (p.cdpUrl)
630
370
  return `attach:${p.cdpUrl}`;
@@ -637,7 +377,7 @@ export class BrowseSession {
637
377
  }
638
378
  /** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
639
379
  async realBrowser(p, context) {
640
- if ((p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
380
+ if (p.httpAuth || (p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
641
381
  return undefined;
642
382
  // The real browser has the person's logins already; an import is for a browser this tool launches.
643
383
  if (p.action === "cookie_import")
@@ -653,12 +393,12 @@ export class BrowseSession {
653
393
  const groupId = createHash("sha256").update(JSON.stringify([this.identity.integration, context.profile, context.sessionId])).digest("hex").slice(0, 24);
654
394
  return RealBrowserSession.open(config.realBrowser.command, { name: this.identity.integration, version: "1" }, this.owner(context), `${this.identity.name} ${groupId}`, policy?.allowedDomains?.flatMap(domain => [domain, `*.${domain}`]));
655
395
  }
656
- async inRealBrowser(real, params, context, ai) {
396
+ async inRealBrowser(real, params, context, ai, generate) {
657
397
  // SAFETY: `ai` marks a browse_ai call, whose arguments are AIParams; every other call's are BrowserParams.
658
398
  if (ai)
659
- return this.aiInRealBrowser(real, params, context);
399
+ return this.aiInRealBrowser(real, params, context, generate);
660
400
  const p = params;
661
- if (p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
401
+ if (p.httpAuth || p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
662
402
  throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
663
403
  }
664
404
  // Listing the cookie sources needs no browser.
@@ -726,8 +466,7 @@ export class BrowseSession {
726
466
  * browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
727
467
  * inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
728
468
  */
729
- async aiInRealBrowser(real, p, context) {
730
- const generate = this.stagehandModel.model?.generate;
469
+ async aiInRealBrowser(real, p, context, generate) {
731
470
  if (!generate) {
732
471
  throw new BrowseToolError("configuration", `browse_ai in the user's real browser runs on the ${this.identity.name} model, which this host does not lend. Use browse with a snapshot and refs, or close and start with backend "browserbase".`);
733
472
  }
@@ -778,13 +517,13 @@ export class BrowseSession {
778
517
  await real?.close(AbortSignal.timeout(5000)).catch(() => undefined);
779
518
  }
780
519
  /** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
781
- async forward(params, context, ai) {
520
+ async forward(params, context, ai, generate) {
782
521
  const { conv, connection } = this.delegate;
783
522
  const { signal, purpose: _purpose, ...rest } = context;
784
523
  // The broker reports a batch's progress itself; a broker that goes away mid-call leaves it unknown.
785
524
  this.batchSent = true;
786
525
  try {
787
- const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal);
526
+ const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal, generate);
788
527
  if (params.action === "close")
789
528
  await this.dropDelegate();
790
529
  return output;
@@ -1001,6 +740,8 @@ export class BrowseSession {
1001
740
  if (!this.session || this.session.closing || this.session.browser.closed || !this.session.stagehand) {
1002
741
  throw new BrowseToolError("no_session", "No usable browser session. Call close, then start or open to begin a fresh session.");
1003
742
  }
743
+ if (this.session.httpAuth?.closed)
744
+ throw new BrowseToolError("http_auth_disconnected", "The browser's HTTP authentication connection ended. Close it and start a new isolated browser.");
1004
745
  return this.session;
1005
746
  }
1006
747
  async start(context, p) {
@@ -1010,6 +751,8 @@ export class BrowseSession {
1010
751
  throw new BrowseToolError("unsupported_backend", "contextId and proxyCountry are Browserbase-only options. Close the local browser before starting a hosted one.");
1011
752
  }
1012
753
  if (this.session) {
754
+ if (p.httpAuth && !this.session.httpAuth)
755
+ throw new BrowseToolError("browser_change", "Close the current browser before starting an isolated HTTP-auth session.");
1013
756
  if (backend !== this.session.backend || (cdpUrl !== undefined && cdpUrl !== this.session.cdpUrl)
1014
757
  || (p.endpoint !== undefined && p.endpoint !== this.session.endpoint)
1015
758
  || (headless !== undefined && (this.session.cdpUrl !== undefined || headless !== this.session.headless))) {
@@ -1026,7 +769,20 @@ export class BrowseSession {
1026
769
  }
1027
770
  return this.current();
1028
771
  }
1029
- const config = await this.config(context, backend);
772
+ const config = await this.config(p.httpAuth ? { ...context, httpAuth: true } : context, backend);
773
+ if (p.httpAuth) {
774
+ try {
775
+ config.httpAuth = await resolveHttpAuth(config.httpAuth, config.httpAuthStore, p.url, backend === "browserbase", context.signal);
776
+ }
777
+ catch (error) {
778
+ throw new BrowseToolError("configuration", messageOf(error));
779
+ }
780
+ const { username, password } = config.httpAuth;
781
+ this.secrets.add(Buffer.from(username + ":" + password).toString("base64"));
782
+ this.secrets.add(password).add(JSON.stringify(password).slice(1, -1));
783
+ }
784
+ else
785
+ delete config.httpAuth;
1030
786
  const domainPolicy = domainLists(config, p);
1031
787
  if (backend === "local") {
1032
788
  const attach = p.endpoint ? config.remoteBrowsers?.[p.endpoint]
@@ -1038,7 +794,7 @@ export class BrowseSession {
1038
794
  for (const secret of [attach.cdpUrl, attach.extensionCdpUrl, ...Object.values(attach.headers ?? {}).filter(value => value.length >= 8)])
1039
795
  if (secret)
1040
796
  this.secrets.add(secret);
1041
- const userDataDir = attach ? undefined : config.localUserDataDir || undefined;
797
+ const userDataDir = attach || p.httpAuth ? undefined : config.localUserDataDir || undefined;
1042
798
  if (attach || userDataDir)
1043
799
  return this.joinShared(context, config, p, domainPolicy, attach, userDataDir);
1044
800
  // A temporary profile belongs to this conversation alone.
@@ -1058,8 +814,8 @@ export class BrowseSession {
1058
814
  });
1059
815
  if (saved.projectId !== config.projectId)
1060
816
  throw new BrowseToolError("context_project", "The saved context belongs to a different Browserbase project.");
1061
- // context_create prefixes names with the creating profile, so one host profile cannot load another's logins.
1062
- if (!saved.name?.startsWith(`${context.profile}:`)) {
817
+ // A remote name is not proof of origin. Check the locally recorded ID as well as the remote project and prefix.
818
+ if (!saved.name?.startsWith(`${context.profile}:`) || !await knownContext(contextRegistry(config.contextHistoryPath, this.identity.integration), { contextId, projectId: config.projectId, profile: context.profile, integration: this.identity.integration })) {
1063
819
  throw new BrowseToolError("context_profile", `The saved context was not created by this extension under the "${context.profile}" profile.`);
1064
820
  }
1065
821
  const remaining = (this.contextReadyAt.get(contextId) ?? 0) - Date.now();
@@ -1072,6 +828,7 @@ export class BrowseSession {
1072
828
  const create = (keepAlive) => browserbase.launch({
1073
829
  apiKey: config.apiKey, projectId: config.projectId, region: config.region, extensionId: extension.id, api_timeout: SESSION_LIFETIME_SECONDS, keepAlive,
1074
830
  browserSettings: {
831
+ ...(p.httpAuth ? { logSession: false, recordSession: false } : {}),
1075
832
  viewport: { width: 1280, height: 800 }, ...(contextId ? { context: { id: contextId, persist: true } } : {}),
1076
833
  ...(config.navigationPolicyId ? { riskPolicyId: config.navigationPolicyId } : {}),
1077
834
  },
@@ -1094,7 +851,7 @@ export class BrowseSession {
1094
851
  return create(keepAlive);
1095
852
  }
1096
853
  };
1097
- let keepAlive = this.keepAliveAllowed;
854
+ let keepAlive = !p.httpAuth && this.keepAliveAllowed;
1098
855
  let browser;
1099
856
  try {
1100
857
  browser = await launch(keepAlive);
@@ -1126,6 +883,16 @@ export class BrowseSession {
1126
883
  const [, active] = await Promise.all([browser.context.addInitScript(DIALOG_GUARD), browser.context.activePage(),
1127
884
  session.domainPolicy ? browser.context.setDomainPolicy(stagehandPolicy(session.domainPolicy)) : undefined]);
1128
885
  session.tabId = active?.pageId;
886
+ if (session.config.httpAuth) {
887
+ const signal = AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]);
888
+ const url = await this.devToolsUrl(session, signal);
889
+ const handler = await answerHttpAuth(url, session.config.httpAuth, signal);
890
+ if (this.session !== session || session.closing || signal.aborted) {
891
+ await handler.close();
892
+ throw abortError();
893
+ }
894
+ session.httpAuth = handler;
895
+ }
1129
896
  return session;
1130
897
  }
1131
898
  catch (error) {
@@ -1288,10 +1055,10 @@ export class BrowseSession {
1288
1055
  return shared.closing;
1289
1056
  }
1290
1057
  /** Runs a browse_ai call on a shared Stagehand in turn, lending it this conversation's default inference meanwhile. */
1291
- takeAiTurn(shared, signal, run) {
1058
+ takeAiTurn(shared, signal, generate, run) {
1292
1059
  const turn = shared.aiTurn.then(async () => {
1293
1060
  signal.throwIfAborted();
1294
- shared.inference.generate = this.stagehandModel.model?.generate;
1061
+ shared.inference.generate = generate;
1295
1062
  try {
1296
1063
  return await run();
1297
1064
  }
@@ -1325,24 +1092,27 @@ export class BrowseSession {
1325
1092
  const pages = await session.browser.context.pages();
1326
1093
  return session.shared ? pages.filter(page => !this.ownedByOther(session, page.pageId)) : pages;
1327
1094
  }
1095
+ /** Browser-level DevTools endpoint of a browser we launched or the provider hosts. */
1096
+ async devToolsUrl(session, signal) {
1097
+ if (session.backend === "local") {
1098
+ if (!session.debugPort)
1099
+ throw new BrowseToolError("unsupported_backend", "This local browser has no DevTools port.");
1100
+ const version = await fetch(`http://127.0.0.1:${session.debugPort}/json/version`, { signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) });
1101
+ return (await version.json()).webSocketDebuggerUrl;
1102
+ }
1103
+ const remote = await session.client.sessions.retrieve(session.browser.sessionId, { signal, timeout: 5000, maxRetries: 0 });
1104
+ if (!remote.connectUrl)
1105
+ throw new BrowseToolError("connection_failed", "Browserbase returned no DevTools URL for this session.");
1106
+ this.secrets.add(remote.connectUrl);
1107
+ return remote.connectUrl;
1108
+ }
1328
1109
  /** Starts recording every tab's network traffic over a DevTools connection of its own. */
1329
1110
  async harStart(session, context) {
1330
1111
  if (session.har)
1331
1112
  throw new BrowseToolError("har_active", "A recording is already running. Call har_stop to write it first.");
1332
- let browserUrl;
1333
- if (session.backend === "local") {
1334
- if (!session.debugPort)
1335
- throw new BrowseToolError("unsupported_backend", "This local browser has no DevTools port to record through. Close it and start again.");
1336
- const version = await fetch(`http://127.0.0.1:${session.debugPort}/json/version`, { signal: AbortSignal.any([context.signal, AbortSignal.timeout(5000)]) });
1337
- browserUrl = (await version.json()).webSocketDebuggerUrl;
1338
- }
1339
- else {
1340
- const remote = await session.client.sessions.retrieve(session.browser.sessionId, { timeout: 5000, maxRetries: 0 });
1341
- if (!remote.connectUrl)
1342
- throw new BrowseToolError("har_failed", "Browserbase returned no DevTools URL for this session to record through.");
1343
- browserUrl = remote.connectUrl;
1344
- this.secrets.add(browserUrl);
1345
- }
1113
+ if (session.config.httpAuth)
1114
+ throw new BrowseToolError("unsupported_backend", "HAR recording is unavailable in a browser started with HTTP authentication.");
1115
+ const browserUrl = await this.devToolsUrl(session, context.signal);
1346
1116
  context.signal.throwIfAborted();
1347
1117
  // A shared browser holds other conversations' tabs: record only this one's, and the popups they open.
1348
1118
  const include = session.shared ? (targetId) => session.ownedTabs.has(targetId) : undefined;
@@ -1363,6 +1133,7 @@ export class BrowseSession {
1363
1133
  session.har?.close();
1364
1134
  session.har = undefined;
1365
1135
  session.closing = (async () => {
1136
+ await session.httpAuth?.close();
1366
1137
  const shared = session.shared;
1367
1138
  if (shared) {
1368
1139
  if (this.session === session)
@@ -1472,7 +1243,7 @@ export class BrowseSession {
1472
1243
  }
1473
1244
  /** 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. */
1474
1245
  prepare(session, p, budget) {
1475
- const control = p.action === "click" || p.action === "fill" || p.action === "select";
1246
+ const control = ["click", "fill", "select", "hover", "upload"].includes(p.action);
1476
1247
  // Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
1477
1248
  const input = {
1478
1249
  ...p, action: p.action, readTimeoutMs: RESULT_READ_MS,
@@ -1480,7 +1251,7 @@ export class BrowseSession {
1480
1251
  };
1481
1252
  // The worker writes the version into the refs it returns, so it is taken before the call; a failed call skips a number.
1482
1253
  if (p.action === "snapshot")
1483
- input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000 };
1254
+ input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000, offset: p.offset, interactive: p.interactive };
1484
1255
  const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
1485
1256
  if (refused)
1486
1257
  throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
@@ -1506,7 +1277,7 @@ export class BrowseSession {
1506
1277
  if (snapshot) {
1507
1278
  const { version } = input.snapshot;
1508
1279
  session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.refs });
1509
- data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated };
1280
+ data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated, ...(snapshot.nextOffset === undefined ? {} : { nextOffset: snapshot.nextOffset }) };
1510
1281
  }
1511
1282
  else if (p.action === "select") {
1512
1283
  data = { selected: value };
@@ -1521,11 +1292,43 @@ export class BrowseSession {
1521
1292
  }
1522
1293
  return { ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}), ...(image ? { image: new Uint8Array(Buffer.from(image, "base64")) } : {}) };
1523
1294
  }
1295
+ /** Stagehand 4.4 keyPress loses printable Shift key metadata. Send this chord through the selected tab's DevTools target. */
1296
+ async shiftedKey(session, page, key, signal) {
1297
+ const base = key.slice(6).replace(/^(space|spacebar)$/i, " ");
1298
+ const low = "1234567890-=[];'/.,\\`", high = '!@#$%^&*()_+{}:"?><|~';
1299
+ const codes = ["Digit1", "Digit2", "Digit3", "Digit4", "Digit5", "Digit6", "Digit7", "Digit8", "Digit9", "Digit0", "Minus", "Equal", "BracketLeft", "BracketRight", "Semicolon", "Quote", "Slash", "Period", "Comma", "Backslash", "Backquote"];
1300
+ const vks = [49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187, 219, 221, 186, 222, 191, 190, 188, 220, 192];
1301
+ const pos = Math.max(low.indexOf(base), high.indexOf(base));
1302
+ const char = pos >= 0 ? high[pos] : base.toUpperCase();
1303
+ const stroke = { key: char, code: pos >= 0 ? codes[pos] : base === " " ? "Space" : /^[a-z]$/i.test(base) ? "Key" + char : undefined,
1304
+ windowsVirtualKeyCode: pos >= 0 ? vks[pos] : /^[a-z ]$/i.test(base) ? char.charCodeAt(0) : undefined, modifiers: 8 };
1305
+ const shift = { key: "Shift", code: "ShiftLeft", windowsVirtualKeyCode: 16, location: 1 };
1306
+ await withRawCdp(session.shared?.guard?.url ?? await this.devToolsUrl(session, signal), signal, async (send) => {
1307
+ const { sessionId } = await send("Target.attachToTarget", { targetId: page.pageId, flatten: true });
1308
+ const event = (type, params) => send("Input.dispatchKeyEvent", { type, ...params }, sessionId);
1309
+ await event("rawKeyDown", { ...shift, modifiers: 8 });
1310
+ try {
1311
+ await event("keyDown", { ...stroke, text: char, unmodifiedText: base });
1312
+ }
1313
+ finally {
1314
+ try {
1315
+ await event("keyUp", stroke);
1316
+ }
1317
+ finally {
1318
+ await event("keyUp", { ...shift, modifiers: 0 });
1319
+ }
1320
+ }
1321
+ });
1322
+ const { origin: _origin, ...view } = await this.view(session, page);
1323
+ return view;
1324
+ }
1524
1325
  async direct(session, p, context) {
1525
1326
  let input, result;
1526
1327
  try {
1527
1328
  input = this.prepare(session, p, operationTimeout(p, false));
1528
- result = await this.batch(session, p, context, pageOperation, input, await this.tab(session, p.tabId));
1329
+ const page = await this.tab(session, p.tabId);
1330
+ result = p.action === "press" && shifted(p.key) ? await this.shiftedKey(session, page, p.key, context.signal)
1331
+ : await this.batch(session, p, context, pageOperation, input, page);
1529
1332
  if (result.error) {
1530
1333
  if (result.error.code === "stale_ref")
1531
1334
  session.snapshots.delete(result.tabId);
@@ -1569,7 +1372,35 @@ export class BrowseSession {
1569
1372
  let result;
1570
1373
  try {
1571
1374
  this.batchSent = true;
1572
- result = await this.batch(session, p, context, pageOperation, { id, steps: prepared, timeoutMs: budget }, page);
1375
+ if (prepared.some(step => step.action === "press" && shifted(step.key))) {
1376
+ // A shifted printable needs host-side CDP. Keep step ordering, the same tab, deadline and partial results.
1377
+ result = { results: [] };
1378
+ let refsValid = true;
1379
+ for (const [index, step] of prepared.entries()) {
1380
+ context.signal.throwIfAborted();
1381
+ if (step.reference && !refsValid) {
1382
+ result.failure = { index, code: "stale_ref", message: "An earlier step invalidated this ref.", outcomeUnknown: false };
1383
+ break;
1384
+ }
1385
+ try {
1386
+ const value = step.action === "press" && shifted(step.key) ? await this.shiftedKey(session, page, step.key, context.signal)
1387
+ : await this.batch(session, p, context, pageOperation, step, page);
1388
+ if (value.error) {
1389
+ result.failure = { index, ...value.error, outcomeUnknown: false };
1390
+ break;
1391
+ }
1392
+ result.results.push(value);
1393
+ if (step.action === "snapshot" || changesPage(steps[index]))
1394
+ refsValid = false;
1395
+ }
1396
+ catch (error) {
1397
+ result.failure = { index, code: "browser_error", message: messageOf(error), outcomeUnknown: true };
1398
+ break;
1399
+ }
1400
+ }
1401
+ }
1402
+ else
1403
+ result = await this.batch(session, p, context, pageOperation, { id, steps: prepared, timeoutMs: budget }, page);
1573
1404
  }
1574
1405
  catch (cause) {
1575
1406
  // Sent or not is all that is known here: run() reports the outcome as unknown unless the request never left.
@@ -1682,7 +1513,7 @@ export class BrowseSession {
1682
1513
  let model = session?.config.model;
1683
1514
  if (!session) {
1684
1515
  try {
1685
- model = (await this.resolveConfig(context)).model;
1516
+ model = (await this.resolveConfig({ ...context, backend: this.defaultBackend })).model;
1686
1517
  }
1687
1518
  catch { /* Status stays available before configuration exists. */ }
1688
1519
  }
@@ -1704,16 +1535,8 @@ export class BrowseSession {
1704
1535
  throw new BrowseToolError("unsupported_backend", "Saved contexts are Browserbase-only. Close the local browser first.");
1705
1536
  const config = await this.config(context);
1706
1537
  const created = await (await this.client(config)).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
1707
- const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile };
1708
- let historySaved = false;
1709
- if (config.contextHistoryPath) {
1710
- try {
1711
- await mkdir(dirname(config.contextHistoryPath), { recursive: true });
1712
- await appendFile(config.contextHistoryPath, `${JSON.stringify(saved)}\n`, { mode: 0o600 });
1713
- historySaved = true;
1714
- }
1715
- catch { /* The remote context exists; return its identifier even if local history is unavailable. */ }
1716
- }
1538
+ const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile, integration: this.identity.integration };
1539
+ const historySaved = await rememberContext(contextRegistry(config.contextHistoryPath, this.identity.integration), saved).then(() => true, () => false);
1717
1540
  return { action: p.action, sessionId: null, contextId: created.id, projectId: config.projectId, data: { ...saved, historySaved } };
1718
1541
  }
1719
1542
  // The profile is settled before cookie_import starts a browser, so an import that cannot proceed launches nothing.
@@ -1826,9 +1649,9 @@ export class BrowseSession {
1826
1649
  }
1827
1650
  // Every other action ran above; what is left names its element by target.
1828
1651
  const jev = await this.locate(session, page, p, p.target, context);
1829
- if (!jev.xpath)
1652
+ if (!jev.selector)
1830
1653
  return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.none ? "jev_none" : "jev_uncertain", isError: true };
1831
- const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
1654
+ const output = await this.direct(session, { ...p, target: undefined, selector: jev.selector }, context);
1832
1655
  return { ...output, data: { ...output.data, jev: jev.result } };
1833
1656
  }
1834
1657
  /**
@@ -1863,8 +1686,7 @@ export class BrowseSession {
1863
1686
  }
1864
1687
  }
1865
1688
  /**
1866
- * JEV mode: a classifier (Jev unless jevModel names another) picks the element for a plain-language target from a
1867
- * fresh snapshot; no xpath means it declined to act.
1689
+ * JEV mode: a classifier (Jev unless jevModel names another) picks a versioned snapshot ref. The worker must still verify it after inference.
1868
1690
  */
1869
1691
  async locate(session, page, p, target, context) {
1870
1692
  const action = p.action, visual = p.visual;
@@ -1884,8 +1706,8 @@ export class BrowseSession {
1884
1706
  const version = `s${++this.snapshotNumber}`;
1885
1707
  session.snapshots.set(page.pageId, { version, url, refs });
1886
1708
  if (pick.chosen)
1887
- return { xpath: refs[pick.chosen.ref], none: false, result: { model, label: pick.chosen.label, confidence: pick.confidence } };
1888
- return { xpath: undefined, none: pick.none, result: this.declined(model, pick, ref => `@${version}:${ref}`) };
1709
+ return { selector: `@${version}:${pick.chosen.ref}`, none: false, result: { model, label: pick.chosen.label, confidence: pick.confidence } };
1710
+ return { selector: undefined, none: pick.none, result: this.declined(model, pick, ref => `@${version}:${ref}`) };
1889
1711
  }
1890
1712
  /** Jev's pick among the candidates; a failed request says whether retrying can help. */
1891
1713
  async pick(candidates, state, classify, image, signal) {
@@ -1924,7 +1746,7 @@ export class BrowseSession {
1924
1746
  ...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
1925
1747
  };
1926
1748
  }
1927
- async ai(p, context) {
1749
+ async ai(p, context, generate) {
1928
1750
  const session = this.current();
1929
1751
  const config = await this.config(context, session.backend);
1930
1752
  // No model: Model Gateway picks one per call. A model without a key: Gateway pinned to it. A model with a key: that provider directly.
@@ -1964,7 +1786,10 @@ export class BrowseSession {
1964
1786
  session.snapshots.clear();
1965
1787
  }
1966
1788
  };
1967
- const { result, isError } = session.shared ? await this.takeAiTurn(session.shared, context.signal, run) : await run();
1789
+ // Stagehand registers one callback per runtime, not per request. Hold its turn until the actual SDK
1790
+ // promise settles, even if the caller has already received a timeout.
1791
+ const { result, isError } = await this.takeAiTurn(session.shared ?? this.aiOwner, context.signal, generate, run);
1792
+ context.signal.throwIfAborted();
1968
1793
  return { ...await this.output(p.action, session, page, result), isError, ...(isError ? { code: "act_failed" } : {}) };
1969
1794
  }
1970
1795
  }