@edlsh/browse-core 0.7.0 → 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.
- package/README.md +8 -2
- package/dist/broker-client.d.ts +4 -2
- package/dist/broker-client.js +10 -5
- package/dist/broker-protocol.d.ts +3 -2
- package/dist/broker-protocol.js +11 -7
- package/dist/broker.js +12 -12
- package/dist/config.d.ts +101 -0
- package/dist/config.js +78 -0
- package/dist/contexts.d.ts +10 -0
- package/dist/contexts.js +27 -0
- package/dist/errors.d.ts +29 -0
- package/dist/errors.js +83 -0
- package/dist/host-model.d.ts +24 -0
- package/dist/host-model.js +35 -0
- package/dist/index.d.ts +10 -13
- package/dist/index.js +11 -15
- package/dist/jev.js +9 -3
- package/dist/page-operations.d.ts +11 -1
- package/dist/page-operations.js +62 -11
- package/dist/real-browser-ai.d.ts +1 -1
- package/dist/real-browser-ai.js +1 -1
- package/dist/real-browser-client.js +1 -1
- package/dist/real-browser-session.d.ts +1 -1
- package/dist/real-browser-session.js +24 -5
- package/dist/schema.d.ts +32 -0
- package/dist/schema.js +22 -6
- package/dist/session-runtime.d.ts +42 -0
- package/dist/session-runtime.js +144 -0
- package/dist/session.d.ts +27 -118
- package/dist/session.js +134 -350
- package/dist/settings.js +47 -6
- package/dist/tool-results.d.ts +28 -0
- package/dist/tool-results.js +40 -0
- package/extensions/http-auth/README.md +27 -0
- package/extensions/http-auth/background.js +85 -0
- package/extensions/http-auth/manifest.json +27 -0
- package/extensions/http-auth/native/README.md +31 -0
- package/extensions/http-auth/native/host.py +97 -0
- package/extensions/http-auth/native/install.py +62 -0
- package/extensions/http-auth/options.html +25 -0
- package/extensions/http-auth/options.js +36 -0
- package/extensions/http-auth/origin.js +16 -0
- package/package.json +13 -2
package/dist/session.js
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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 {
|
|
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";
|
|
10
11
|
import { answerHttpAuth, resolveHttpAuth } from "./http-auth.js";
|
|
12
|
+
import { encodeFailure, ToolResults } from "./tool-results.js";
|
|
11
13
|
import { HarRecorder, writeCaptureHar } from "./har.js";
|
|
12
14
|
import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
|
|
13
15
|
import { BrokerConnection } from "./broker-client.js";
|
|
@@ -16,62 +18,9 @@ import { extractPage, observePage } from "./real-browser-ai.js";
|
|
|
16
18
|
import { extensionCacheKey, extensionCachePath, provisionExtension } from "./extension-cache.js";
|
|
17
19
|
import { createHash, randomUUID } from "node:crypto";
|
|
18
20
|
import { cancelPageBatch, pageOperation, readOperation, tabsOperation, viewOperation } from "./page-operations.js";
|
|
19
|
-
import { CookieSourceError, localCookieProvider
|
|
21
|
+
import { CookieSourceError, localCookieProvider } from "./browser-cookies.js";
|
|
20
22
|
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, outlineCandidates, pickTarget, treeCandidates } from "./jev.js";
|
|
21
23
|
import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
|
|
22
|
-
/** Whether `domain` is `parent` or one of its subdomains. */
|
|
23
|
-
function within(domain, parent) {
|
|
24
|
-
return domain === parent || domain.endsWith(`.${parent}`);
|
|
25
|
-
}
|
|
26
|
-
/** The profile's domain lists, narrowed by start: start's allowed domains must fall inside the profile's, and blocked ones add up. */
|
|
27
|
-
export function domainLists(config, start) {
|
|
28
|
-
const normalize = (domains, setting) => {
|
|
29
|
-
if (!domains?.length)
|
|
30
|
-
return undefined;
|
|
31
|
-
try {
|
|
32
|
-
return normalizeCookieDomains(domains);
|
|
33
|
-
}
|
|
34
|
-
catch (error) {
|
|
35
|
-
throw new BrowseToolError("configuration", `${setting}: ${messageOf(error)}`);
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
const profileAllowed = normalize(config.allowedDomains, "the profile's allowedDomains");
|
|
39
|
-
const startAllowed = normalize(start.allowedDomains, "allowedDomains");
|
|
40
|
-
if (profileAllowed && startAllowed) {
|
|
41
|
-
const outside = startAllowed.filter(domain => !profileAllowed.some(parent => within(domain, parent)));
|
|
42
|
-
if (outside.length)
|
|
43
|
-
throw new BrowseToolError("domain_policy_widened", `allowedDomains can only narrow this profile's allowed domains (${profileAllowed.join(", ")}); ${outside.join(", ")} is outside them.`);
|
|
44
|
-
}
|
|
45
|
-
const allowedDomains = startAllowed ?? profileAllowed;
|
|
46
|
-
const blockedDomains = [...new Set([...normalize(config.blockedDomains, "the profile's blockedDomains") ?? [], ...normalize(start.blockedDomains, "blockedDomains") ?? []])];
|
|
47
|
-
if (!allowedDomains && !blockedDomains.length)
|
|
48
|
-
return undefined;
|
|
49
|
-
return { ...(allowedDomains ? { allowedDomains } : {}), ...(blockedDomains.length ? { blockedDomains } : {}) };
|
|
50
|
-
}
|
|
51
|
-
/** Why the fence refuses a URL's host, or undefined when it lets the URL through. */
|
|
52
|
-
function fenced(url, lists) {
|
|
53
|
-
if (!lists || !URL.canParse(url))
|
|
54
|
-
return undefined;
|
|
55
|
-
const host = new URL(url).hostname.toLowerCase().replace(/\.$/, "");
|
|
56
|
-
if (lists.blockedDomains?.some(domain => within(host, domain)))
|
|
57
|
-
return `${host} is in this browser's blocked domains (${lists.blockedDomains.join(", ")})`;
|
|
58
|
-
if (lists.allowedDomains && !lists.allowedDomains.some(domain => within(host, domain)))
|
|
59
|
-
return `${host} is outside this browser's allowed domains (${lists.allowedDomains.join(", ")})`;
|
|
60
|
-
return undefined;
|
|
61
|
-
}
|
|
62
|
-
/** Stagehand matches exact hosts and `*.` subdomains, so each bare domain becomes both. */
|
|
63
|
-
function stagehandPolicy(lists) {
|
|
64
|
-
const patterns = (domains) => domains.flatMap(domain => [domain, `*.${domain}`]);
|
|
65
|
-
return {
|
|
66
|
-
...(lists.allowedDomains ? { allowedDomains: patterns(lists.allowedDomains) } : {}),
|
|
67
|
-
...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
/**
|
|
71
|
-
* Stagehand and the Browserbase SDK load on first browser use. Loading them with this package cost every host about
|
|
72
|
-
* 85 ms at startup, whether or not the conversation ever opened a browser.
|
|
73
|
-
*/
|
|
74
|
-
const stagehandSdk = () => import("@browserbasehq/stagehand");
|
|
75
24
|
const REGIONS = ["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"];
|
|
76
25
|
/** JEV's classifier unless jevModel names another: Jev on Vercel AI Gateway. */
|
|
77
26
|
const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
|
|
@@ -94,66 +43,13 @@ const REPEATABLE = new Set(["open", "snapshot", "ask", "screenshot", "tabs", "wa
|
|
|
94
43
|
/** Actions that keep snapshot refs: they read, or change values, not which DOM nodes exist; each ref is still re-verified before use. */
|
|
95
44
|
const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll", "snapshot", "screenshot", "tab_select"]);
|
|
96
45
|
/** Actions that validate, act, and read their result beside the browser in one request. */
|
|
97
|
-
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"]);
|
|
98
47
|
/**
|
|
99
48
|
* Stagehand launch defaults a persistent profile must drop: the mock Keychain encrypts its saved cookies with a fixed,
|
|
100
49
|
* publicly known key, disabled background networking stops installed extensions from updating, and disabled default
|
|
101
50
|
* apps makes Chrome skip the profile's `External Extensions` directory, which preinstalls Web Store extensions.
|
|
102
51
|
*/
|
|
103
52
|
const PERSISTENT_PROFILE_IGNORED_ARGS = ["--use-mock-keychain", "--password-store=basic", "--disable-background-networking", "--disable-default-apps"];
|
|
104
|
-
async function freePort() {
|
|
105
|
-
const server = createServer().listen(0, "127.0.0.1");
|
|
106
|
-
await once(server, "listening");
|
|
107
|
-
const { port } = server.address();
|
|
108
|
-
await new Promise(resolve => server.close(resolve));
|
|
109
|
-
return port;
|
|
110
|
-
}
|
|
111
|
-
/**
|
|
112
|
-
* Stagehand ends a launched Chrome with SIGTERM to its whole process group, which kills the network service before it
|
|
113
|
-
* writes cookies to disk. Browser.close shuts Chrome down in order; waiting for its process to exit means Stagehand's
|
|
114
|
-
* close then has nothing left to signal, so a persistent profile keeps its logins.
|
|
115
|
-
*/
|
|
116
|
-
async function quitChrome(port) {
|
|
117
|
-
const version = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) });
|
|
118
|
-
const socket = new WebSocket((await version.json()).webSocketDebuggerUrl);
|
|
119
|
-
let pid;
|
|
120
|
-
socket.addEventListener("message", event => {
|
|
121
|
-
const reply = JSON.parse(String(event.data));
|
|
122
|
-
if (reply.id === 1)
|
|
123
|
-
pid = reply.result?.processInfo?.find(entry => entry.type === "browser")?.id;
|
|
124
|
-
});
|
|
125
|
-
const closed = once(socket, "close");
|
|
126
|
-
socket.addEventListener("open", () => {
|
|
127
|
-
socket.send(JSON.stringify({ id: 1, method: "SystemInfo.getProcessInfo" }));
|
|
128
|
-
socket.send(JSON.stringify({ id: 2, method: "Browser.close" }));
|
|
129
|
-
}, { once: true });
|
|
130
|
-
await closed;
|
|
131
|
-
// The endpoint closes before Chrome finishes writing the profile.
|
|
132
|
-
for (let i = 0; pid && i < 200 && running(pid); i++)
|
|
133
|
-
await delay(20);
|
|
134
|
-
}
|
|
135
|
-
/** Reloading Stagehand's extension can replace its service worker between discovery and attachment; attaching again then succeeds. */
|
|
136
|
-
async function connectRetrying(connect, signal) {
|
|
137
|
-
for (let attempt = 0;; attempt++) {
|
|
138
|
-
try {
|
|
139
|
-
return await connect();
|
|
140
|
-
}
|
|
141
|
-
catch (error) {
|
|
142
|
-
if (attempt >= 3 || !/No target with given id found/.test(messageOf(error)))
|
|
143
|
-
throw error;
|
|
144
|
-
await delay(100, undefined, { signal });
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
function running(pid) {
|
|
149
|
-
try {
|
|
150
|
-
process.kill(pid, 0);
|
|
151
|
-
return true;
|
|
152
|
-
}
|
|
153
|
-
catch (error) {
|
|
154
|
-
return error.code === "EPERM";
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
53
|
/** How long a tab may take to answer a trivial evaluate before it counts as unresponsive. */
|
|
158
54
|
const TAB_PROBE_MS = 2_000;
|
|
159
55
|
/** How long the reads after a completed action may take before the result reports the tab unresponsive instead of failing. */
|
|
@@ -179,140 +75,10 @@ const DIALOG_GUARD = `(() => {
|
|
|
179
75
|
window.addEventListener("beforeunload", event => event.stopImmediatePropagation(), true);
|
|
180
76
|
})()`;
|
|
181
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 ?? ""); }
|
|
182
79
|
function changesPage(p) {
|
|
183
80
|
return !KEEPS_REFS.has(p.action) || Boolean(p.url);
|
|
184
81
|
}
|
|
185
|
-
/** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
|
|
186
|
-
function scriptError(message) {
|
|
187
|
-
if (!/^Uncaught\b/.test(message))
|
|
188
|
-
return undefined;
|
|
189
|
-
const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
|
|
190
|
-
return new BrowseToolError("script_error", (detail
|
|
191
|
-
? `The script threw: ${detail}.`
|
|
192
|
-
: "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
|
|
193
|
-
+ " Side effects before the throw may have happened.");
|
|
194
|
-
}
|
|
195
|
-
function messageOf(error) {
|
|
196
|
-
return error instanceof Error ? error.message : String(error);
|
|
197
|
-
}
|
|
198
|
-
/**
|
|
199
|
-
* Stagehand on a browser another client may just have left. The in-browser runtime releases a lost or detached client's
|
|
200
|
-
* instance asynchronously, so a create that arrives first sees it still initialized and is retried.
|
|
201
|
-
*/
|
|
202
|
-
async function createStagehand(browser, model, signal) {
|
|
203
|
-
for (let attempt = 0;; attempt++) {
|
|
204
|
-
try {
|
|
205
|
-
return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
206
|
-
}
|
|
207
|
-
catch (error) {
|
|
208
|
-
if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
|
|
209
|
-
throw error;
|
|
210
|
-
await delay(250, undefined, { signal });
|
|
211
|
-
}
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
/** Runs `use` over a short-lived raw CDP connection to a browser-level endpoint, then closes it. */
|
|
215
|
-
async function withRawCdp(connectUrl, signal, use) {
|
|
216
|
-
const socket = new WebSocket(connectUrl);
|
|
217
|
-
const pending = new Map();
|
|
218
|
-
let nextId = 0;
|
|
219
|
-
const closed = new Promise((_, reject) => {
|
|
220
|
-
const fail = () => reject(new Error("CDP connection closed"));
|
|
221
|
-
socket.addEventListener("close", fail);
|
|
222
|
-
socket.addEventListener("error", fail);
|
|
223
|
-
});
|
|
224
|
-
closed.catch(() => undefined);
|
|
225
|
-
socket.addEventListener("message", event => {
|
|
226
|
-
const message = JSON.parse(String(event.data));
|
|
227
|
-
const entry = pending.get(message.id);
|
|
228
|
-
if (!entry)
|
|
229
|
-
return;
|
|
230
|
-
pending.delete(message.id);
|
|
231
|
-
if (message.error)
|
|
232
|
-
entry.reject(new Error(message.error.message));
|
|
233
|
-
else
|
|
234
|
-
entry.resolve(message.result);
|
|
235
|
-
});
|
|
236
|
-
const send = (method, params = {}, sessionId) => {
|
|
237
|
-
const id = ++nextId;
|
|
238
|
-
const reply = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
|
|
239
|
-
socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
|
|
240
|
-
return abortable(Promise.race([reply, closed]), signal);
|
|
241
|
-
};
|
|
242
|
-
try {
|
|
243
|
-
await abortable(Promise.race([new Promise(resolve => socket.addEventListener("open", resolve, { once: true })), closed]), signal);
|
|
244
|
-
return await use(send);
|
|
245
|
-
}
|
|
246
|
-
finally {
|
|
247
|
-
socket.close();
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Opens a window with a blank tab in a running browser that has no tab, and returns its id; else undefined. macOS
|
|
252
|
-
* Chrome keeps running after its last window closes, and in that state no client can create a tab, so Stagehand cannot
|
|
253
|
-
* attach. The tab belongs to whoever attaches, whose close removes it again.
|
|
254
|
-
*/
|
|
255
|
-
async function ensurePageTarget(connectUrl, signal) {
|
|
256
|
-
return withRawCdp(connectUrl, signal, async (send) => {
|
|
257
|
-
const { targetInfos } = await send("Target.getTargets");
|
|
258
|
-
if (targetInfos.some(target => target.type === "page"))
|
|
259
|
-
return undefined;
|
|
260
|
-
const { targetId } = await send("Target.createTarget", { url: "about:blank", newWindow: true });
|
|
261
|
-
return z.string().parse(targetId);
|
|
262
|
-
});
|
|
263
|
-
}
|
|
264
|
-
/**
|
|
265
|
-
* Lets go of a shared local browser. An attached one is disconnected, which closes Stagehand's instance in it and leaves
|
|
266
|
-
* the browser running for the next client; a launched profile's Chrome is quit so it writes its cookies.
|
|
267
|
-
*/
|
|
268
|
-
async function release(shared) {
|
|
269
|
-
if (shared.guard) {
|
|
270
|
-
try {
|
|
271
|
-
await deadline(shared.browser.disconnect(), 5000);
|
|
272
|
-
}
|
|
273
|
-
finally {
|
|
274
|
-
await shared.guard.close();
|
|
275
|
-
}
|
|
276
|
-
return;
|
|
277
|
-
}
|
|
278
|
-
await deadline(shared.stagehand?.close() ?? Promise.resolve(), 1500).catch(() => undefined);
|
|
279
|
-
if (shared.quitPort)
|
|
280
|
-
await deadline(quitChrome(shared.quitPort), 5000).catch(() => undefined);
|
|
281
|
-
await deadline(shared.browser.close(), 5000);
|
|
282
|
-
}
|
|
283
|
-
/** Gives recurring Stagehand failures a code and a next step; anything else passes through unchanged. */
|
|
284
|
-
function translate(error) {
|
|
285
|
-
if (error instanceof BrowseToolError)
|
|
286
|
-
return error;
|
|
287
|
-
const message = messageOf(error);
|
|
288
|
-
if (/ERR_BLOCKED_BY_CLIENT/.test(message))
|
|
289
|
-
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.");
|
|
290
|
-
if (/^No Page found|^Stagehand callback batch page was not found:|^Stagehand has no active page\.|^Stagehand page ".+" was not found;/.test(message))
|
|
291
|
-
return new BrowseToolError("tab_missing", "The tab closed or navigated away during the action. List tabs, select one, and take a snapshot.");
|
|
292
|
-
if (/^Connection error\.?$/.test(message))
|
|
293
|
-
return new BrowseToolError("network_error", "Could not reach Browserbase. Retry once; if it persists, check this machine's network.");
|
|
294
|
-
// Stagehand admits one client per browser and refuses a second while the first is connected.
|
|
295
|
-
if (/A Stagehand client is already connected/.test(message))
|
|
296
|
-
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.");
|
|
297
|
-
if (/does not support the client watchdog|requires Chrome 137 or later/.test(message))
|
|
298
|
-
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.");
|
|
299
|
-
// Stagehand's own per-request limit: the tab stopped answering, typically a busy script.
|
|
300
|
-
const rpc = /^RPC response timed out: (\S+)/.exec(message);
|
|
301
|
-
if (rpc)
|
|
302
|
-
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.`);
|
|
303
|
-
// Page-level waits and navigations that ran out of time, in Stagehand's wording, sometimes wrapped as a page exception.
|
|
304
|
-
const pageTimeout = /^(?:Uncaught (?:\(in promise\) )?(?:Error: )?)?(.*(?:timed out after \d+ ?ms|Timeout \d+ ?ms exceeded).*)$/s.exec(message);
|
|
305
|
-
if (pageTimeout)
|
|
306
|
-
return new BrowseToolError("timeout", `${pageTimeout[1].slice(0, 300)}. The browser was kept; take a snapshot to check the page, or raise timeoutMs.`);
|
|
307
|
-
// Strict structured output (OpenAI models on Model Gateway) rejects schemas with optional properties.
|
|
308
|
-
if (/^Invalid schema for response_format/.test(message)) {
|
|
309
|
-
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.`);
|
|
310
|
-
}
|
|
311
|
-
if (/extension world not ready for frame/i.test(message)) {
|
|
312
|
-
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.");
|
|
313
|
-
}
|
|
314
|
-
return error;
|
|
315
|
-
}
|
|
316
82
|
/** `(expr)[n]` with balanced outer parentheses. Stagehand's shadow-DOM XPath resolver ignores a grouped position. */
|
|
317
83
|
function groupedPosition(selector) {
|
|
318
84
|
const text = selector.trim().replace(/^xpath=/, "");
|
|
@@ -337,51 +103,10 @@ function groupedPosition(selector) {
|
|
|
337
103
|
}
|
|
338
104
|
return { base: `xpath=${match[1]}`, index: Number(match[2]) - 1 };
|
|
339
105
|
}
|
|
340
|
-
/** A comma- or space-separated domain list from the environment; empty counts as unset. */
|
|
341
|
-
function domainList(value) {
|
|
342
|
-
const domains = value?.split(/[\s,]+/).filter(Boolean);
|
|
343
|
-
return domains?.length ? domains : undefined;
|
|
344
|
-
}
|
|
345
|
-
export function environmentConfig(scope) {
|
|
346
|
-
return {
|
|
347
|
-
...(scope?.httpAuth && (process.env.BROWSE_HTTP_AUTH_USERNAME || process.env.BROWSE_HTTP_AUTH_PASSWORD) ? { httpAuth: {
|
|
348
|
-
origin: process.env.BROWSE_HTTP_AUTH_ORIGIN ?? "", username: process.env.BROWSE_HTTP_AUTH_USERNAME ?? "",
|
|
349
|
-
password: process.env.BROWSE_HTTP_AUTH_PASSWORD ?? "", hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true",
|
|
350
|
-
} } : {}),
|
|
351
|
-
...(scope?.httpAuth && process.env.BROWSE_HTTP_AUTH_USE_STORE === "true"
|
|
352
|
-
? { httpAuthStore: { hosted: process.env.BROWSE_HTTP_AUTH_HOSTED === "true", origin: process.env.BROWSE_HTTP_AUTH_ORIGIN } } : {}),
|
|
353
|
-
apiKey: process.env.BROWSERBASE_API_KEY ?? "",
|
|
354
|
-
projectId: process.env.BROWSERBASE_PROJECT_ID ?? "",
|
|
355
|
-
model: process.env.STAGEHAND_MODEL,
|
|
356
|
-
modelApiKey: process.env.STAGEHAND_MODEL_API_KEY,
|
|
357
|
-
jevApiKey: process.env.AI_GATEWAY_API_KEY,
|
|
358
|
-
cloudflareAccountId: process.env.CLOUDFLARE_ACCOUNT_ID,
|
|
359
|
-
cloudflareApiKey: process.env.CLOUDFLARE_API_KEY,
|
|
360
|
-
region: process.env.BROWSERBASE_REGION,
|
|
361
|
-
allowedDomains: domainList(process.env.BROWSE_ALLOWED_DOMAINS),
|
|
362
|
-
blockedDomains: domainList(process.env.BROWSE_BLOCKED_DOMAINS),
|
|
363
|
-
navigationPolicyId: process.env.BROWSERBASE_NAVIGATION_POLICY_ID,
|
|
364
|
-
jevModel: process.env.BROWSE_JEV_MODEL,
|
|
365
|
-
askModel: process.env.BROWSE_ASK_MODEL,
|
|
366
|
-
};
|
|
367
|
-
}
|
|
368
|
-
export class BrowseToolError extends Error {
|
|
369
|
-
code;
|
|
370
|
-
batch;
|
|
371
|
-
/** `batch` is set on a failed batch call. */
|
|
372
|
-
constructor(code, message, batch) {
|
|
373
|
-
super(message);
|
|
374
|
-
this.code = code;
|
|
375
|
-
this.batch = batch;
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
106
|
/** Shared browsers by key (`launch:<userDataDir>` or `attach:<cdpUrl>`), for every BrowseSession in this process. */
|
|
379
107
|
const sharedBrowsers = new Map();
|
|
380
108
|
/** A shared browser still quitting; a new launch of the same profile waits for Chrome to release it. */
|
|
381
109
|
const retiringBrowsers = new Map();
|
|
382
|
-
function abortError(message = "Operation cancelled.") {
|
|
383
|
-
return new BrowseToolError("cancelled", message);
|
|
384
|
-
}
|
|
385
110
|
/** A fixed wait needs headroom past its own duration, or the default deadline would reject waits the schema allows. */
|
|
386
111
|
function operationTimeout(params, ai) {
|
|
387
112
|
if (params.timeoutMs)
|
|
@@ -394,26 +119,6 @@ function operationTimeout(params, ai) {
|
|
|
394
119
|
const wait = "durationMs" in params ? params.durationMs : undefined;
|
|
395
120
|
return wait ? Math.max(30_000, wait + 5_000) : 30_000;
|
|
396
121
|
}
|
|
397
|
-
/** Stops waiting immediately; the caller is responsible for closing the remote browser. */
|
|
398
|
-
function abortable(promise, signal) {
|
|
399
|
-
return new Promise((resolve, reject) => {
|
|
400
|
-
const abort = () => reject(signal.reason ?? abortError());
|
|
401
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
402
|
-
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
403
|
-
if (signal.aborted)
|
|
404
|
-
abort();
|
|
405
|
-
});
|
|
406
|
-
}
|
|
407
|
-
async function deadline(promise, ms) {
|
|
408
|
-
const controller = new AbortController();
|
|
409
|
-
const timer = setTimeout(() => controller.abort(new BrowseToolError("timeout", "Browser cleanup timed out.")), ms);
|
|
410
|
-
try {
|
|
411
|
-
return await abortable(promise, controller.signal);
|
|
412
|
-
}
|
|
413
|
-
finally {
|
|
414
|
-
clearTimeout(timer);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
122
|
export class BrowseSession {
|
|
418
123
|
resolveConfig;
|
|
419
124
|
hostClassify;
|
|
@@ -428,6 +133,7 @@ export class BrowseSession {
|
|
|
428
133
|
snapshotNumber = 0;
|
|
429
134
|
generation = 0;
|
|
430
135
|
contextReadyAt = new Map();
|
|
136
|
+
results = new ToolResults();
|
|
431
137
|
secrets = new Set();
|
|
432
138
|
/** Cleared for the process lifetime once Browserbase refuses keepAlive for this plan. */
|
|
433
139
|
keepAliveAllowed = true;
|
|
@@ -441,7 +147,9 @@ export class BrowseSession {
|
|
|
441
147
|
extensions = new Map();
|
|
442
148
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
443
149
|
stagehandModel;
|
|
150
|
+
aiOwner = { inference: {}, aiTurn: Promise.resolve() };
|
|
444
151
|
describeInference;
|
|
152
|
+
defaultGenerate;
|
|
445
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. */
|
|
446
154
|
defaultBackend = "local";
|
|
447
155
|
constructor(resolveConfig = environmentConfig, inference, hostClassify, identity = { name: "Host", integration: "browse-core" }, options = {}) {
|
|
@@ -450,9 +158,19 @@ export class BrowseSession {
|
|
|
450
158
|
this.identity = identity;
|
|
451
159
|
this.profileBroker = options.profileBroker ?? true;
|
|
452
160
|
this.cookies = options.cookies ?? localCookieProvider;
|
|
453
|
-
this.stagehandModel = inference ? { model: { generate:
|
|
454
|
-
|
|
455
|
-
|
|
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)); }
|
|
456
174
|
redact(text) {
|
|
457
175
|
// Longest first: a shorter secret nested in a longer one must not leave the longer one's remainder visible.
|
|
458
176
|
for (const secret of [...this.secrets].sort((a, b) => b.length - a.length))
|
|
@@ -475,8 +193,6 @@ export class BrowseSession {
|
|
|
475
193
|
signal?.throwIfAborted();
|
|
476
194
|
if (generation !== this.generation)
|
|
477
195
|
throw abortError("The conversation changed before this browser operation started.");
|
|
478
|
-
if (typeof ai === "function")
|
|
479
|
-
ai();
|
|
480
196
|
const controller = new AbortController();
|
|
481
197
|
const cancel = () => controller.abort(abortError());
|
|
482
198
|
signal?.addEventListener("abort", cancel, { once: true });
|
|
@@ -492,7 +208,14 @@ export class BrowseSession {
|
|
|
492
208
|
await this.closeReal();
|
|
493
209
|
controller.signal.throwIfAborted();
|
|
494
210
|
this.batchSent = false;
|
|
495
|
-
|
|
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);
|
|
496
219
|
}
|
|
497
220
|
catch (error) {
|
|
498
221
|
// Shutdown releases the browser itself. A fired deadline or cancellation leaves only the last action's
|
|
@@ -514,6 +237,8 @@ export class BrowseSession {
|
|
|
514
237
|
}
|
|
515
238
|
finally {
|
|
516
239
|
clearTimeout(timer);
|
|
240
|
+
if (isAi)
|
|
241
|
+
controller.abort(abortError("The browser model call has ended."));
|
|
517
242
|
signal?.removeEventListener("abort", cancel);
|
|
518
243
|
if (this.active === controller)
|
|
519
244
|
this.active = undefined;
|
|
@@ -536,6 +261,7 @@ export class BrowseSession {
|
|
|
536
261
|
});
|
|
537
262
|
}
|
|
538
263
|
async shutdown() {
|
|
264
|
+
this.results.clear();
|
|
539
265
|
this.generation++;
|
|
540
266
|
this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
|
|
541
267
|
// Begin releasing immediately, in case the host cuts shutdown handlers short.
|
|
@@ -567,7 +293,8 @@ export class BrowseSession {
|
|
|
567
293
|
const jevClassifier = describe("jev", jev), askClassifier = describe("ask", ask);
|
|
568
294
|
return {
|
|
569
295
|
credentials: Boolean(browser?.apiKey?.trim() && browser?.projectId?.trim()),
|
|
570
|
-
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),
|
|
571
298
|
aiModel: browser?.model?.trim() || undefined,
|
|
572
299
|
jevModel: jevClassifier.model,
|
|
573
300
|
jevKey: jevClassifier.key,
|
|
@@ -578,16 +305,20 @@ export class BrowseSession {
|
|
|
578
305
|
};
|
|
579
306
|
}
|
|
580
307
|
owner(context) {
|
|
581
|
-
return
|
|
308
|
+
return JSON.stringify([context.profile, context.sessionId]);
|
|
582
309
|
}
|
|
583
310
|
/** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
|
|
584
|
-
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();
|
|
585
316
|
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded.
|
|
586
317
|
if (!this.real && !this.delegate && !this.session && !ai && opensBrowser(params))
|
|
587
318
|
this.real = await this.realBrowser(params, context);
|
|
588
319
|
if (this.real) {
|
|
589
320
|
try {
|
|
590
|
-
return await this.inRealBrowser(this.real, params, context, ai);
|
|
321
|
+
return await this.inRealBrowser(this.real, params, context, ai, generate);
|
|
591
322
|
}
|
|
592
323
|
catch (error) {
|
|
593
324
|
// OpenCode Browse is gone, and this conversation's tabs with it: the next start may choose another browser.
|
|
@@ -616,8 +347,8 @@ export class BrowseSession {
|
|
|
616
347
|
if (this.delegate && !ai && params.action === "start" && params.httpAuth)
|
|
617
348
|
throw new BrowseToolError("browser_change", "Close the shared browser before starting an isolated HTTP-auth session.");
|
|
618
349
|
if (this.delegate)
|
|
619
|
-
return this.forward(params, context, ai);
|
|
620
|
-
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);
|
|
621
352
|
try {
|
|
622
353
|
return await attempt();
|
|
623
354
|
}
|
|
@@ -662,10 +393,10 @@ export class BrowseSession {
|
|
|
662
393
|
const groupId = createHash("sha256").update(JSON.stringify([this.identity.integration, context.profile, context.sessionId])).digest("hex").slice(0, 24);
|
|
663
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}`]));
|
|
664
395
|
}
|
|
665
|
-
async inRealBrowser(real, params, context, ai) {
|
|
396
|
+
async inRealBrowser(real, params, context, ai, generate) {
|
|
666
397
|
// SAFETY: `ai` marks a browse_ai call, whose arguments are AIParams; every other call's are BrowserParams.
|
|
667
398
|
if (ai)
|
|
668
|
-
return this.aiInRealBrowser(real, params, context);
|
|
399
|
+
return this.aiInRealBrowser(real, params, context, generate);
|
|
669
400
|
const p = params;
|
|
670
401
|
if (p.httpAuth || p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
|
|
671
402
|
throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
|
|
@@ -735,8 +466,7 @@ export class BrowseSession {
|
|
|
735
466
|
* browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
|
|
736
467
|
* inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
|
|
737
468
|
*/
|
|
738
|
-
async aiInRealBrowser(real, p, context) {
|
|
739
|
-
const generate = this.stagehandModel.model?.generate;
|
|
469
|
+
async aiInRealBrowser(real, p, context, generate) {
|
|
740
470
|
if (!generate) {
|
|
741
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".`);
|
|
742
472
|
}
|
|
@@ -787,13 +517,13 @@ export class BrowseSession {
|
|
|
787
517
|
await real?.close(AbortSignal.timeout(5000)).catch(() => undefined);
|
|
788
518
|
}
|
|
789
519
|
/** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
|
|
790
|
-
async forward(params, context, ai) {
|
|
520
|
+
async forward(params, context, ai, generate) {
|
|
791
521
|
const { conv, connection } = this.delegate;
|
|
792
522
|
const { signal, purpose: _purpose, ...rest } = context;
|
|
793
523
|
// The broker reports a batch's progress itself; a broker that goes away mid-call leaves it unknown.
|
|
794
524
|
this.batchSent = true;
|
|
795
525
|
try {
|
|
796
|
-
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);
|
|
797
527
|
if (params.action === "close")
|
|
798
528
|
await this.dropDelegate();
|
|
799
529
|
return output;
|
|
@@ -1084,8 +814,8 @@ export class BrowseSession {
|
|
|
1084
814
|
});
|
|
1085
815
|
if (saved.projectId !== config.projectId)
|
|
1086
816
|
throw new BrowseToolError("context_project", "The saved context belongs to a different Browserbase project.");
|
|
1087
|
-
//
|
|
1088
|
-
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 })) {
|
|
1089
819
|
throw new BrowseToolError("context_profile", `The saved context was not created by this extension under the "${context.profile}" profile.`);
|
|
1090
820
|
}
|
|
1091
821
|
const remaining = (this.contextReadyAt.get(contextId) ?? 0) - Date.now();
|
|
@@ -1325,10 +1055,10 @@ export class BrowseSession {
|
|
|
1325
1055
|
return shared.closing;
|
|
1326
1056
|
}
|
|
1327
1057
|
/** Runs a browse_ai call on a shared Stagehand in turn, lending it this conversation's default inference meanwhile. */
|
|
1328
|
-
takeAiTurn(shared, signal, run) {
|
|
1058
|
+
takeAiTurn(shared, signal, generate, run) {
|
|
1329
1059
|
const turn = shared.aiTurn.then(async () => {
|
|
1330
1060
|
signal.throwIfAborted();
|
|
1331
|
-
shared.inference.generate =
|
|
1061
|
+
shared.inference.generate = generate;
|
|
1332
1062
|
try {
|
|
1333
1063
|
return await run();
|
|
1334
1064
|
}
|
|
@@ -1513,7 +1243,7 @@ export class BrowseSession {
|
|
|
1513
1243
|
}
|
|
1514
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. */
|
|
1515
1245
|
prepare(session, p, budget) {
|
|
1516
|
-
const control =
|
|
1246
|
+
const control = ["click", "fill", "select", "hover", "upload"].includes(p.action);
|
|
1517
1247
|
// Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
|
|
1518
1248
|
const input = {
|
|
1519
1249
|
...p, action: p.action, readTimeoutMs: RESULT_READ_MS,
|
|
@@ -1521,7 +1251,7 @@ export class BrowseSession {
|
|
|
1521
1251
|
};
|
|
1522
1252
|
// The worker writes the version into the refs it returns, so it is taken before the call; a failed call skips a number.
|
|
1523
1253
|
if (p.action === "snapshot")
|
|
1524
|
-
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 };
|
|
1525
1255
|
const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
|
|
1526
1256
|
if (refused)
|
|
1527
1257
|
throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
|
|
@@ -1547,7 +1277,7 @@ export class BrowseSession {
|
|
|
1547
1277
|
if (snapshot) {
|
|
1548
1278
|
const { version } = input.snapshot;
|
|
1549
1279
|
session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.refs });
|
|
1550
|
-
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 }) };
|
|
1551
1281
|
}
|
|
1552
1282
|
else if (p.action === "select") {
|
|
1553
1283
|
data = { selected: value };
|
|
@@ -1562,11 +1292,43 @@ export class BrowseSession {
|
|
|
1562
1292
|
}
|
|
1563
1293
|
return { ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}), ...(image ? { image: new Uint8Array(Buffer.from(image, "base64")) } : {}) };
|
|
1564
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
|
+
}
|
|
1565
1325
|
async direct(session, p, context) {
|
|
1566
1326
|
let input, result;
|
|
1567
1327
|
try {
|
|
1568
1328
|
input = this.prepare(session, p, operationTimeout(p, false));
|
|
1569
|
-
|
|
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);
|
|
1570
1332
|
if (result.error) {
|
|
1571
1333
|
if (result.error.code === "stale_ref")
|
|
1572
1334
|
session.snapshots.delete(result.tabId);
|
|
@@ -1610,7 +1372,35 @@ export class BrowseSession {
|
|
|
1610
1372
|
let result;
|
|
1611
1373
|
try {
|
|
1612
1374
|
this.batchSent = true;
|
|
1613
|
-
|
|
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);
|
|
1614
1404
|
}
|
|
1615
1405
|
catch (cause) {
|
|
1616
1406
|
// Sent or not is all that is known here: run() reports the outcome as unknown unless the request never left.
|
|
@@ -1723,7 +1513,7 @@ export class BrowseSession {
|
|
|
1723
1513
|
let model = session?.config.model;
|
|
1724
1514
|
if (!session) {
|
|
1725
1515
|
try {
|
|
1726
|
-
model = (await this.resolveConfig(context)).model;
|
|
1516
|
+
model = (await this.resolveConfig({ ...context, backend: this.defaultBackend })).model;
|
|
1727
1517
|
}
|
|
1728
1518
|
catch { /* Status stays available before configuration exists. */ }
|
|
1729
1519
|
}
|
|
@@ -1745,16 +1535,8 @@ export class BrowseSession {
|
|
|
1745
1535
|
throw new BrowseToolError("unsupported_backend", "Saved contexts are Browserbase-only. Close the local browser first.");
|
|
1746
1536
|
const config = await this.config(context);
|
|
1747
1537
|
const created = await (await this.client(config)).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
|
|
1748
|
-
const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile };
|
|
1749
|
-
|
|
1750
|
-
if (config.contextHistoryPath) {
|
|
1751
|
-
try {
|
|
1752
|
-
await mkdir(dirname(config.contextHistoryPath), { recursive: true });
|
|
1753
|
-
await appendFile(config.contextHistoryPath, `${JSON.stringify(saved)}\n`, { mode: 0o600 });
|
|
1754
|
-
historySaved = true;
|
|
1755
|
-
}
|
|
1756
|
-
catch { /* The remote context exists; return its identifier even if local history is unavailable. */ }
|
|
1757
|
-
}
|
|
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);
|
|
1758
1540
|
return { action: p.action, sessionId: null, contextId: created.id, projectId: config.projectId, data: { ...saved, historySaved } };
|
|
1759
1541
|
}
|
|
1760
1542
|
// The profile is settled before cookie_import starts a browser, so an import that cannot proceed launches nothing.
|
|
@@ -1867,9 +1649,9 @@ export class BrowseSession {
|
|
|
1867
1649
|
}
|
|
1868
1650
|
// Every other action ran above; what is left names its element by target.
|
|
1869
1651
|
const jev = await this.locate(session, page, p, p.target, context);
|
|
1870
|
-
if (!jev.
|
|
1652
|
+
if (!jev.selector)
|
|
1871
1653
|
return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.none ? "jev_none" : "jev_uncertain", isError: true };
|
|
1872
|
-
const output = await this.direct(session, { ...p, target: undefined, selector: jev.
|
|
1654
|
+
const output = await this.direct(session, { ...p, target: undefined, selector: jev.selector }, context);
|
|
1873
1655
|
return { ...output, data: { ...output.data, jev: jev.result } };
|
|
1874
1656
|
}
|
|
1875
1657
|
/**
|
|
@@ -1904,8 +1686,7 @@ export class BrowseSession {
|
|
|
1904
1686
|
}
|
|
1905
1687
|
}
|
|
1906
1688
|
/**
|
|
1907
|
-
* JEV mode: a classifier (Jev unless jevModel names another) picks
|
|
1908
|
-
* 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.
|
|
1909
1690
|
*/
|
|
1910
1691
|
async locate(session, page, p, target, context) {
|
|
1911
1692
|
const action = p.action, visual = p.visual;
|
|
@@ -1925,8 +1706,8 @@ export class BrowseSession {
|
|
|
1925
1706
|
const version = `s${++this.snapshotNumber}`;
|
|
1926
1707
|
session.snapshots.set(page.pageId, { version, url, refs });
|
|
1927
1708
|
if (pick.chosen)
|
|
1928
|
-
return {
|
|
1929
|
-
return {
|
|
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}`) };
|
|
1930
1711
|
}
|
|
1931
1712
|
/** Jev's pick among the candidates; a failed request says whether retrying can help. */
|
|
1932
1713
|
async pick(candidates, state, classify, image, signal) {
|
|
@@ -1965,7 +1746,7 @@ export class BrowseSession {
|
|
|
1965
1746
|
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1966
1747
|
};
|
|
1967
1748
|
}
|
|
1968
|
-
async ai(p, context) {
|
|
1749
|
+
async ai(p, context, generate) {
|
|
1969
1750
|
const session = this.current();
|
|
1970
1751
|
const config = await this.config(context, session.backend);
|
|
1971
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.
|
|
@@ -2005,7 +1786,10 @@ export class BrowseSession {
|
|
|
2005
1786
|
session.snapshots.clear();
|
|
2006
1787
|
}
|
|
2007
1788
|
};
|
|
2008
|
-
|
|
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();
|
|
2009
1793
|
return { ...await this.output(p.action, session, page, result), isError, ...(isError ? { code: "act_failed" } : {}) };
|
|
2010
1794
|
}
|
|
2011
1795
|
}
|