@edlsh/browse-core 0.7.0 → 0.8.1
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 +103 -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 +10 -4
- 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 +5 -4
- package/dist/real-browser-client.js +1 -1
- package/dist/real-browser-session.d.ts +4 -2
- package/dist/real-browser-session.js +47 -21
- package/dist/schema.d.ts +36 -0
- package/dist/schema.js +37 -10
- 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 +152 -352
- 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.
|
|
@@ -545,7 +271,7 @@ export class BrowseSession {
|
|
|
545
271
|
async readiness(context, signal) {
|
|
546
272
|
const resolve = async (purpose) => {
|
|
547
273
|
try {
|
|
548
|
-
return await this.resolveConfig({ ...context, signal, purpose, backend: this.session?.backend ?? this.defaultBackend });
|
|
274
|
+
return await this.resolveConfig({ ...context, signal, purpose, probe: true, backend: this.session?.backend ?? this.defaultBackend });
|
|
549
275
|
}
|
|
550
276
|
catch {
|
|
551
277
|
return undefined;
|
|
@@ -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,28 @@ 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
|
+
// A pre-open `tabs` / failed `tab_select` leaves an idle real-browser handle; release it before an opening call
|
|
318
|
+
// so backend switches, launch options, and domain policies are evaluated fresh.
|
|
319
|
+
if (!ai && this.real && !this.real.active && opensBrowser(params))
|
|
320
|
+
await this.closeReal();
|
|
321
|
+
const attachesReal = opensBrowser(params)
|
|
322
|
+
|| params.action === "tabs"
|
|
323
|
+
|| params.action === "tab_select"
|
|
324
|
+
|| (params.tabId !== undefined && !["close", "status", "result_read", "cookie_profiles", "cookie_import"].includes(params.action));
|
|
325
|
+
if (!this.real && !this.delegate && !this.session && !ai && attachesReal)
|
|
587
326
|
this.real = await this.realBrowser(params, context);
|
|
588
327
|
if (this.real) {
|
|
589
328
|
try {
|
|
590
|
-
return await this.inRealBrowser(this.real, params, context, ai);
|
|
329
|
+
return await this.inRealBrowser(this.real, params, context, ai, generate);
|
|
591
330
|
}
|
|
592
331
|
catch (error) {
|
|
593
332
|
// OpenCode Browse is gone, and this conversation's tabs with it: the next start may choose another browser.
|
|
@@ -616,8 +355,8 @@ export class BrowseSession {
|
|
|
616
355
|
if (this.delegate && !ai && params.action === "start" && params.httpAuth)
|
|
617
356
|
throw new BrowseToolError("browser_change", "Close the shared browser before starting an isolated HTTP-auth session.");
|
|
618
357
|
if (this.delegate)
|
|
619
|
-
return this.forward(params, context, ai);
|
|
620
|
-
const attempt = () => ai ? this.ai(params, context) : this.browse(params, context);
|
|
358
|
+
return this.forward(params, context, ai, generate);
|
|
359
|
+
const attempt = () => ai ? this.ai(params, context, generate) : this.browse(params, context);
|
|
621
360
|
try {
|
|
622
361
|
return await attempt();
|
|
623
362
|
}
|
|
@@ -662,14 +401,22 @@ export class BrowseSession {
|
|
|
662
401
|
const groupId = createHash("sha256").update(JSON.stringify([this.identity.integration, context.profile, context.sessionId])).digest("hex").slice(0, 24);
|
|
663
402
|
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
403
|
}
|
|
665
|
-
async inRealBrowser(real, params, context, ai) {
|
|
404
|
+
async inRealBrowser(real, params, context, ai, generate) {
|
|
666
405
|
// SAFETY: `ai` marks a browse_ai call, whose arguments are AIParams; every other call's are BrowserParams.
|
|
667
406
|
if (ai)
|
|
668
|
-
return this.aiInRealBrowser(real, params, context);
|
|
407
|
+
return this.aiInRealBrowser(real, params, context, generate);
|
|
669
408
|
const p = params;
|
|
670
409
|
if (p.httpAuth || p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
|
|
671
410
|
throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
|
|
672
411
|
}
|
|
412
|
+
if (p.action === "start" && (p.allowedDomains || p.blockedDomains)) {
|
|
413
|
+
const config = await this.config(context, "local");
|
|
414
|
+
const next = domainLists(config, p);
|
|
415
|
+
const nextOrigins = next?.allowedDomains?.flatMap(domain => [domain, `*.${domain}`]);
|
|
416
|
+
if (next?.blockedDomains?.length || JSON.stringify(nextOrigins) !== JSON.stringify(real.allowedOrigins)) {
|
|
417
|
+
throw new BrowseToolError("domain_policy_change", "Close the current browser before starting with different allowed or blocked domains.");
|
|
418
|
+
}
|
|
419
|
+
}
|
|
673
420
|
// Listing the cookie sources needs no browser.
|
|
674
421
|
if (p.action === "cookie_profiles")
|
|
675
422
|
return this.browse(p, context);
|
|
@@ -735,8 +482,7 @@ export class BrowseSession {
|
|
|
735
482
|
* browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
|
|
736
483
|
* inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
|
|
737
484
|
*/
|
|
738
|
-
async aiInRealBrowser(real, p, context) {
|
|
739
|
-
const generate = this.stagehandModel.model?.generate;
|
|
485
|
+
async aiInRealBrowser(real, p, context, generate) {
|
|
740
486
|
if (!generate) {
|
|
741
487
|
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
488
|
}
|
|
@@ -787,13 +533,13 @@ export class BrowseSession {
|
|
|
787
533
|
await real?.close(AbortSignal.timeout(5000)).catch(() => undefined);
|
|
788
534
|
}
|
|
789
535
|
/** 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) {
|
|
536
|
+
async forward(params, context, ai, generate) {
|
|
791
537
|
const { conv, connection } = this.delegate;
|
|
792
538
|
const { signal, purpose: _purpose, ...rest } = context;
|
|
793
539
|
// The broker reports a batch's progress itself; a broker that goes away mid-call leaves it unknown.
|
|
794
540
|
this.batchSent = true;
|
|
795
541
|
try {
|
|
796
|
-
const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal);
|
|
542
|
+
const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal, generate);
|
|
797
543
|
if (params.action === "close")
|
|
798
544
|
await this.dropDelegate();
|
|
799
545
|
return output;
|
|
@@ -1084,8 +830,8 @@ export class BrowseSession {
|
|
|
1084
830
|
});
|
|
1085
831
|
if (saved.projectId !== config.projectId)
|
|
1086
832
|
throw new BrowseToolError("context_project", "The saved context belongs to a different Browserbase project.");
|
|
1087
|
-
//
|
|
1088
|
-
if (!saved.name?.startsWith(`${context.profile}:`)) {
|
|
833
|
+
// A remote name is not proof of origin. Check the locally recorded ID as well as the remote project and prefix.
|
|
834
|
+
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
835
|
throw new BrowseToolError("context_profile", `The saved context was not created by this extension under the "${context.profile}" profile.`);
|
|
1090
836
|
}
|
|
1091
837
|
const remaining = (this.contextReadyAt.get(contextId) ?? 0) - Date.now();
|
|
@@ -1325,10 +1071,10 @@ export class BrowseSession {
|
|
|
1325
1071
|
return shared.closing;
|
|
1326
1072
|
}
|
|
1327
1073
|
/** Runs a browse_ai call on a shared Stagehand in turn, lending it this conversation's default inference meanwhile. */
|
|
1328
|
-
takeAiTurn(shared, signal, run) {
|
|
1074
|
+
takeAiTurn(shared, signal, generate, run) {
|
|
1329
1075
|
const turn = shared.aiTurn.then(async () => {
|
|
1330
1076
|
signal.throwIfAborted();
|
|
1331
|
-
shared.inference.generate =
|
|
1077
|
+
shared.inference.generate = generate;
|
|
1332
1078
|
try {
|
|
1333
1079
|
return await run();
|
|
1334
1080
|
}
|
|
@@ -1513,7 +1259,7 @@ export class BrowseSession {
|
|
|
1513
1259
|
}
|
|
1514
1260
|
/** 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
1261
|
prepare(session, p, budget) {
|
|
1516
|
-
const control =
|
|
1262
|
+
const control = ["click", "fill", "select", "hover", "upload"].includes(p.action);
|
|
1517
1263
|
// Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
|
|
1518
1264
|
const input = {
|
|
1519
1265
|
...p, action: p.action, readTimeoutMs: RESULT_READ_MS,
|
|
@@ -1521,7 +1267,7 @@ export class BrowseSession {
|
|
|
1521
1267
|
};
|
|
1522
1268
|
// The worker writes the version into the refs it returns, so it is taken before the call; a failed call skips a number.
|
|
1523
1269
|
if (p.action === "snapshot")
|
|
1524
|
-
input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000 };
|
|
1270
|
+
input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000, offset: p.offset, interactive: p.interactive };
|
|
1525
1271
|
const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
|
|
1526
1272
|
if (refused)
|
|
1527
1273
|
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 +1293,7 @@ export class BrowseSession {
|
|
|
1547
1293
|
if (snapshot) {
|
|
1548
1294
|
const { version } = input.snapshot;
|
|
1549
1295
|
session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.refs });
|
|
1550
|
-
data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated };
|
|
1296
|
+
data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated, ...(snapshot.nextOffset === undefined ? {} : { nextOffset: snapshot.nextOffset }) };
|
|
1551
1297
|
}
|
|
1552
1298
|
else if (p.action === "select") {
|
|
1553
1299
|
data = { selected: value };
|
|
@@ -1562,11 +1308,43 @@ export class BrowseSession {
|
|
|
1562
1308
|
}
|
|
1563
1309
|
return { ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}), ...(image ? { image: new Uint8Array(Buffer.from(image, "base64")) } : {}) };
|
|
1564
1310
|
}
|
|
1311
|
+
/** Stagehand 4.4 keyPress loses printable Shift key metadata. Send this chord through the selected tab's DevTools target. */
|
|
1312
|
+
async shiftedKey(session, page, key, signal) {
|
|
1313
|
+
const base = key.slice(6).replace(/^(space|spacebar)$/i, " ");
|
|
1314
|
+
const low = "1234567890-=[];'/.,\\`", high = '!@#$%^&*()_+{}:"?><|~';
|
|
1315
|
+
const codes = ["Digit1", "Digit2", "Digit3", "Digit4", "Digit5", "Digit6", "Digit7", "Digit8", "Digit9", "Digit0", "Minus", "Equal", "BracketLeft", "BracketRight", "Semicolon", "Quote", "Slash", "Period", "Comma", "Backslash", "Backquote"];
|
|
1316
|
+
const vks = [49, 50, 51, 52, 53, 54, 55, 56, 57, 48, 189, 187, 219, 221, 186, 222, 191, 190, 188, 220, 192];
|
|
1317
|
+
const pos = Math.max(low.indexOf(base), high.indexOf(base));
|
|
1318
|
+
const char = pos >= 0 ? high[pos] : base.toUpperCase();
|
|
1319
|
+
const stroke = { key: char, code: pos >= 0 ? codes[pos] : base === " " ? "Space" : /^[a-z]$/i.test(base) ? "Key" + char : undefined,
|
|
1320
|
+
windowsVirtualKeyCode: pos >= 0 ? vks[pos] : /^[a-z ]$/i.test(base) ? char.charCodeAt(0) : undefined, modifiers: 8 };
|
|
1321
|
+
const shift = { key: "Shift", code: "ShiftLeft", windowsVirtualKeyCode: 16, location: 1 };
|
|
1322
|
+
await withRawCdp(session.shared?.guard?.url ?? await this.devToolsUrl(session, signal), signal, async (send) => {
|
|
1323
|
+
const { sessionId } = await send("Target.attachToTarget", { targetId: page.pageId, flatten: true });
|
|
1324
|
+
const event = (type, params) => send("Input.dispatchKeyEvent", { type, ...params }, sessionId);
|
|
1325
|
+
await event("rawKeyDown", { ...shift, modifiers: 8 });
|
|
1326
|
+
try {
|
|
1327
|
+
await event("keyDown", { ...stroke, text: char, unmodifiedText: base });
|
|
1328
|
+
}
|
|
1329
|
+
finally {
|
|
1330
|
+
try {
|
|
1331
|
+
await event("keyUp", stroke);
|
|
1332
|
+
}
|
|
1333
|
+
finally {
|
|
1334
|
+
await event("keyUp", { ...shift, modifiers: 0 });
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
});
|
|
1338
|
+
const { origin: _origin, ...view } = await this.view(session, page);
|
|
1339
|
+
return view;
|
|
1340
|
+
}
|
|
1565
1341
|
async direct(session, p, context) {
|
|
1566
1342
|
let input, result;
|
|
1567
1343
|
try {
|
|
1568
1344
|
input = this.prepare(session, p, operationTimeout(p, false));
|
|
1569
|
-
|
|
1345
|
+
const page = await this.tab(session, p.tabId);
|
|
1346
|
+
result = p.action === "press" && shifted(p.key) ? await this.shiftedKey(session, page, p.key, context.signal)
|
|
1347
|
+
: await this.batch(session, p, context, pageOperation, input, page);
|
|
1570
1348
|
if (result.error) {
|
|
1571
1349
|
if (result.error.code === "stale_ref")
|
|
1572
1350
|
session.snapshots.delete(result.tabId);
|
|
@@ -1610,7 +1388,35 @@ export class BrowseSession {
|
|
|
1610
1388
|
let result;
|
|
1611
1389
|
try {
|
|
1612
1390
|
this.batchSent = true;
|
|
1613
|
-
|
|
1391
|
+
if (prepared.some(step => step.action === "press" && shifted(step.key))) {
|
|
1392
|
+
// A shifted printable needs host-side CDP. Keep step ordering, the same tab, deadline and partial results.
|
|
1393
|
+
result = { results: [] };
|
|
1394
|
+
let refsValid = true;
|
|
1395
|
+
for (const [index, step] of prepared.entries()) {
|
|
1396
|
+
context.signal.throwIfAborted();
|
|
1397
|
+
if (step.reference && !refsValid) {
|
|
1398
|
+
result.failure = { index, code: "stale_ref", message: "An earlier step invalidated this ref.", outcomeUnknown: false };
|
|
1399
|
+
break;
|
|
1400
|
+
}
|
|
1401
|
+
try {
|
|
1402
|
+
const value = step.action === "press" && shifted(step.key) ? await this.shiftedKey(session, page, step.key, context.signal)
|
|
1403
|
+
: await this.batch(session, p, context, pageOperation, step, page);
|
|
1404
|
+
if (value.error) {
|
|
1405
|
+
result.failure = { index, ...value.error, outcomeUnknown: false };
|
|
1406
|
+
break;
|
|
1407
|
+
}
|
|
1408
|
+
result.results.push(value);
|
|
1409
|
+
if (step.action === "snapshot" || changesPage(steps[index]))
|
|
1410
|
+
refsValid = false;
|
|
1411
|
+
}
|
|
1412
|
+
catch (error) {
|
|
1413
|
+
result.failure = { index, code: "browser_error", message: messageOf(error), outcomeUnknown: true };
|
|
1414
|
+
break;
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
else
|
|
1419
|
+
result = await this.batch(session, p, context, pageOperation, { id, steps: prepared, timeoutMs: budget }, page);
|
|
1614
1420
|
}
|
|
1615
1421
|
catch (cause) {
|
|
1616
1422
|
// Sent or not is all that is known here: run() reports the outcome as unknown unless the request never left.
|
|
@@ -1723,7 +1529,7 @@ export class BrowseSession {
|
|
|
1723
1529
|
let model = session?.config.model;
|
|
1724
1530
|
if (!session) {
|
|
1725
1531
|
try {
|
|
1726
|
-
model = (await this.resolveConfig(context)).model;
|
|
1532
|
+
model = (await this.resolveConfig({ ...context, probe: true, backend: this.defaultBackend })).model;
|
|
1727
1533
|
}
|
|
1728
1534
|
catch { /* Status stays available before configuration exists. */ }
|
|
1729
1535
|
}
|
|
@@ -1745,16 +1551,8 @@ export class BrowseSession {
|
|
|
1745
1551
|
throw new BrowseToolError("unsupported_backend", "Saved contexts are Browserbase-only. Close the local browser first.");
|
|
1746
1552
|
const config = await this.config(context);
|
|
1747
1553
|
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
|
-
}
|
|
1554
|
+
const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile, integration: this.identity.integration };
|
|
1555
|
+
const historySaved = await rememberContext(contextRegistry(config.contextHistoryPath, this.identity.integration), saved).then(() => true, () => false);
|
|
1758
1556
|
return { action: p.action, sessionId: null, contextId: created.id, projectId: config.projectId, data: { ...saved, historySaved } };
|
|
1759
1557
|
}
|
|
1760
1558
|
// The profile is settled before cookie_import starts a browser, so an import that cannot proceed launches nothing.
|
|
@@ -1867,9 +1665,9 @@ export class BrowseSession {
|
|
|
1867
1665
|
}
|
|
1868
1666
|
// Every other action ran above; what is left names its element by target.
|
|
1869
1667
|
const jev = await this.locate(session, page, p, p.target, context);
|
|
1870
|
-
if (!jev.
|
|
1668
|
+
if (!jev.selector)
|
|
1871
1669
|
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.
|
|
1670
|
+
const output = await this.direct(session, { ...p, target: undefined, selector: jev.selector }, context);
|
|
1873
1671
|
return { ...output, data: { ...output.data, jev: jev.result } };
|
|
1874
1672
|
}
|
|
1875
1673
|
/**
|
|
@@ -1904,8 +1702,7 @@ export class BrowseSession {
|
|
|
1904
1702
|
}
|
|
1905
1703
|
}
|
|
1906
1704
|
/**
|
|
1907
|
-
* JEV mode: a classifier (Jev unless jevModel names another) picks
|
|
1908
|
-
* fresh snapshot; no xpath means it declined to act.
|
|
1705
|
+
* JEV mode: a classifier (Jev unless jevModel names another) picks a versioned snapshot ref. The worker must still verify it after inference.
|
|
1909
1706
|
*/
|
|
1910
1707
|
async locate(session, page, p, target, context) {
|
|
1911
1708
|
const action = p.action, visual = p.visual;
|
|
@@ -1925,8 +1722,8 @@ export class BrowseSession {
|
|
|
1925
1722
|
const version = `s${++this.snapshotNumber}`;
|
|
1926
1723
|
session.snapshots.set(page.pageId, { version, url, refs });
|
|
1927
1724
|
if (pick.chosen)
|
|
1928
|
-
return {
|
|
1929
|
-
return {
|
|
1725
|
+
return { selector: `@${version}:${pick.chosen.ref}`, none: false, result: { model, label: pick.chosen.label, confidence: pick.confidence } };
|
|
1726
|
+
return { selector: undefined, none: pick.none, result: this.declined(model, pick, ref => `@${version}:${ref}`) };
|
|
1930
1727
|
}
|
|
1931
1728
|
/** Jev's pick among the candidates; a failed request says whether retrying can help. */
|
|
1932
1729
|
async pick(candidates, state, classify, image, signal) {
|
|
@@ -1965,7 +1762,7 @@ export class BrowseSession {
|
|
|
1965
1762
|
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1966
1763
|
};
|
|
1967
1764
|
}
|
|
1968
|
-
async ai(p, context) {
|
|
1765
|
+
async ai(p, context, generate) {
|
|
1969
1766
|
const session = this.current();
|
|
1970
1767
|
const config = await this.config(context, session.backend);
|
|
1971
1768
|
// 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 +1802,10 @@ export class BrowseSession {
|
|
|
2005
1802
|
session.snapshots.clear();
|
|
2006
1803
|
}
|
|
2007
1804
|
};
|
|
2008
|
-
|
|
1805
|
+
// Stagehand registers one callback per runtime, not per request. Hold its turn until the actual SDK
|
|
1806
|
+
// promise settles, even if the caller has already received a timeout.
|
|
1807
|
+
const { result, isError } = await this.takeAiTurn(session.shared ?? this.aiOwner, context.signal, generate, run);
|
|
1808
|
+
context.signal.throwIfAborted();
|
|
2009
1809
|
return { ...await this.output(p.action, session, page, result), isError, ...(isError ? { code: "act_failed" } : {}) };
|
|
2010
1810
|
}
|
|
2011
1811
|
}
|