@edlsh/browse-core 0.4.1 → 0.6.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 +17 -0
- package/dist/ask.d.ts +6 -2
- package/dist/ask.js +1 -1
- package/dist/broker-client.d.ts +2 -0
- package/dist/broker-client.js +7 -1
- package/dist/broker-protocol.d.ts +33 -0
- package/dist/broker-protocol.js +12 -2
- package/dist/broker.js +4 -4
- package/dist/cdp-guard.js +8 -7
- package/dist/extension-cache.d.ts +23 -0
- package/dist/extension-cache.js +48 -0
- package/dist/har.d.ts +39 -0
- package/dist/har.js +32 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/jev.d.ts +5 -0
- package/dist/jev.js +31 -0
- package/dist/page-operations.d.ts +91 -4
- package/dist/page-operations.js +270 -83
- package/dist/real-browser-ai.d.ts +16 -0
- package/dist/real-browser-ai.js +54 -0
- package/dist/real-browser-client.d.ts +36 -0
- package/dist/real-browser-client.js +127 -0
- package/dist/real-browser-session.d.ts +55 -0
- package/dist/real-browser-session.js +255 -0
- package/dist/schema.d.ts +202 -1
- package/dist/schema.js +116 -18
- package/dist/session.d.ts +79 -7
- package/dist/session.js +518 -270
- package/package.json +3 -2
package/dist/session.js
CHANGED
|
@@ -4,18 +4,19 @@ import { createServer } from "node:net";
|
|
|
4
4
|
import { tmpdir } from "node:os";
|
|
5
5
|
import { dirname, join } from "node:path";
|
|
6
6
|
import { setTimeout as delay } from "node:timers/promises";
|
|
7
|
-
import { Browserbase } from "@browserbasehq/sdk";
|
|
8
|
-
import { browserbase, getExtensionArchive, localBrowser, Stagehand } from "@browserbasehq/stagehand";
|
|
9
7
|
import { z } from "zod";
|
|
10
8
|
import { askNeeds, askPage, DECIDE_TEXT } from "./ask.js";
|
|
11
9
|
import { guardEndpoint } from "./cdp-guard.js";
|
|
12
|
-
import { HarRecorder } from "./har.js";
|
|
10
|
+
import { HarRecorder, writeCaptureHar } from "./har.js";
|
|
13
11
|
import { nameChromeProfile, refreshExtensionWorkers } from "./chrome-profile.js";
|
|
14
12
|
import { BrokerConnection } from "./broker-client.js";
|
|
13
|
+
import { RealBrowserSession } from "./real-browser-session.js";
|
|
14
|
+
import { extractPage, observePage } from "./real-browser-ai.js";
|
|
15
|
+
import { extensionCacheKey, extensionCachePath, provisionExtension } from "./extension-cache.js";
|
|
15
16
|
import { randomUUID } from "node:crypto";
|
|
16
|
-
import { pageOperation, tabsOperation } from "./page-operations.js";
|
|
17
|
+
import { cancelPageBatch, pageOperation, readOperation, tabsOperation, viewOperation } from "./page-operations.js";
|
|
17
18
|
import { CookieSourceError, localCookieProvider, normalizeCookieDomains } from "./browser-cookies.js";
|
|
18
|
-
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, pickTarget, treeCandidates } from "./jev.js";
|
|
19
|
+
import { fitsAction, JEV_MIN_CONFIDENCE, jevChooser, outlineCandidates, pickTarget, treeCandidates } from "./jev.js";
|
|
19
20
|
import { CLEF, classifierName, ClassifierRefusal, classifierSpec, takesImages, VERCEL_JEV, vercelClassifier, WORKERS_AI_JEV, workersAiClassifier } from "./classifier.js";
|
|
20
21
|
/** Whether `domain` is `parent` or one of its subdomains. */
|
|
21
22
|
function within(domain, parent) {
|
|
@@ -65,6 +66,11 @@ function stagehandPolicy(lists) {
|
|
|
65
66
|
...(lists.blockedDomains ? { blockedDomains: patterns(lists.blockedDomains) } : {}),
|
|
66
67
|
};
|
|
67
68
|
}
|
|
69
|
+
/**
|
|
70
|
+
* Stagehand and the Browserbase SDK load on first browser use. Loading them with this package cost every host about
|
|
71
|
+
* 85 ms at startup, whether or not the conversation ever opened a browser.
|
|
72
|
+
*/
|
|
73
|
+
const stagehandSdk = () => import("@browserbasehq/stagehand");
|
|
68
74
|
const REGIONS = ["us-west-2", "us-east-1", "eu-central-1", "ap-southeast-1"];
|
|
69
75
|
/** JEV's classifier unless jevModel names another: Jev on Vercel AI Gateway. */
|
|
70
76
|
const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
|
|
@@ -72,6 +78,10 @@ const JEV_DEFAULT = { service: "vercel", model: VERCEL_JEV };
|
|
|
72
78
|
const ASK_DEFAULT = { service: "workers-ai", model: CLEF };
|
|
73
79
|
/** Actions that open a browser when none is open. */
|
|
74
80
|
const OPENS_BROWSER = new Set(["start", "open", "tab_new", "cookie_import", "har_start"]);
|
|
81
|
+
/** Whether a call opens a browser when none is open: one of those actions, or a batch whose first step is open. */
|
|
82
|
+
function opensBrowser(p) {
|
|
83
|
+
return OPENS_BROWSER.has(p.action) || (p.action === "batch" && p.steps?.[0]?.action === "open");
|
|
84
|
+
}
|
|
75
85
|
/** Hard cap on a remote session's life. close and the host's session shutdown release it sooner; this bounds a leak after a crash. */
|
|
76
86
|
const SESSION_LIFETIME_SECONDS = 3600;
|
|
77
87
|
/** Stagehand's errors once the transport to the remote browser is gone. */
|
|
@@ -80,14 +90,10 @@ const CONNECTION_LOST = /RPC client is closed|RPC client closed|CDP connection c
|
|
|
80
90
|
const NOT_SENT = /RPC client is closed/i;
|
|
81
91
|
/** Actions that are safe to repeat after a reconnect whatever happened to the first attempt. */
|
|
82
92
|
const REPEATABLE = new Set(["open", "snapshot", "ask", "screenshot", "tabs", "wait", "live_view", "observe", "extract"]);
|
|
83
|
-
/** Actions that keep snapshot refs: they change values, not which DOM nodes exist;
|
|
84
|
-
const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll"]);
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
* A tab's first history entry, before any page: about:blank for the session's first tab, Stagehand's own start page
|
|
88
|
-
* for tabs it opens. open only accepts http(s), so neither is a page the model navigated to.
|
|
89
|
-
*/
|
|
90
|
-
const START_PAGE = /^(?:about:blank|chrome-extension:\/\/[a-p]{32}\/blank\.html)$/;
|
|
93
|
+
/** Actions that keep snapshot refs: they read, or change values, not which DOM nodes exist; each ref is still re-verified before use. */
|
|
94
|
+
const KEEPS_REFS = new Set(["wait", "start", "fill", "select", "scroll", "snapshot", "screenshot", "tab_select"]);
|
|
95
|
+
/** Actions that validate, act, and read their result beside the browser in one request. */
|
|
96
|
+
const DIRECT_ACTIONS = new Set(["start", "open", "back", "forward", "reload", "wait", "snapshot", "click", "fill", "select", "press", "scroll", "evaluate", "screenshot", "tab_select"]);
|
|
91
97
|
/**
|
|
92
98
|
* Stagehand launch defaults a persistent profile must drop: the mock Keychain encrypts its saved cookies with a fixed,
|
|
93
99
|
* publicly known key, disabled background networking stops installed extensions from updating, and disabled default
|
|
@@ -171,8 +177,20 @@ const DIALOG_GUARD = `(() => {
|
|
|
171
177
|
window.prompt = function prompt(message) { note("prompt", message, "cancel"); return null; };
|
|
172
178
|
window.addEventListener("beforeunload", event => event.stopImmediatePropagation(), true);
|
|
173
179
|
})()`;
|
|
174
|
-
/**
|
|
175
|
-
|
|
180
|
+
/** Whether an action can replace DOM nodes, which ends the use of earlier snapshot refs. */
|
|
181
|
+
function changesPage(p) {
|
|
182
|
+
return !KEEPS_REFS.has(p.action) || Boolean(p.url);
|
|
183
|
+
}
|
|
184
|
+
/** Stagehand reports an exception a page script threw as "Uncaught ..."; anything else is not a script error. */
|
|
185
|
+
function scriptError(message) {
|
|
186
|
+
if (!/^Uncaught\b/.test(message))
|
|
187
|
+
return undefined;
|
|
188
|
+
const detail = message.replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
|
|
189
|
+
return new BrowseToolError("script_error", (detail
|
|
190
|
+
? `The script threw: ${detail}.`
|
|
191
|
+
: "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
|
|
192
|
+
+ " Side effects before the throw may have happened.");
|
|
193
|
+
}
|
|
176
194
|
function messageOf(error) {
|
|
177
195
|
return error instanceof Error ? error.message : String(error);
|
|
178
196
|
}
|
|
@@ -183,7 +201,7 @@ function messageOf(error) {
|
|
|
183
201
|
async function createStagehand(browser, model, signal) {
|
|
184
202
|
for (let attempt = 0;; attempt++) {
|
|
185
203
|
try {
|
|
186
|
-
return await Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
204
|
+
return await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...model });
|
|
187
205
|
}
|
|
188
206
|
catch (error) {
|
|
189
207
|
if (attempt >= 4 || !/already initialized/i.test(messageOf(error)))
|
|
@@ -342,9 +360,12 @@ export function environmentConfig() {
|
|
|
342
360
|
}
|
|
343
361
|
export class BrowseToolError extends Error {
|
|
344
362
|
code;
|
|
345
|
-
|
|
363
|
+
batch;
|
|
364
|
+
/** `batch` is set on a failed batch call. */
|
|
365
|
+
constructor(code, message, batch) {
|
|
346
366
|
super(message);
|
|
347
367
|
this.code = code;
|
|
368
|
+
this.batch = batch;
|
|
348
369
|
}
|
|
349
370
|
}
|
|
350
371
|
/** Shared browsers by key (`launch:<userDataDir>` or `attach:<cdpUrl>`), for every BrowseSession in this process. */
|
|
@@ -360,24 +381,12 @@ function operationTimeout(params, ai) {
|
|
|
360
381
|
return params.timeoutMs;
|
|
361
382
|
if (ai)
|
|
362
383
|
return 120_000;
|
|
384
|
+
// A person signing in or approving a prompt takes longer than any page action.
|
|
385
|
+
if (params.action === "handoff")
|
|
386
|
+
return 600_000;
|
|
363
387
|
const wait = "durationMs" in params ? params.durationMs : undefined;
|
|
364
388
|
return wait ? Math.max(30_000, wait + 5_000) : 30_000;
|
|
365
389
|
}
|
|
366
|
-
/**
|
|
367
|
-
* Stagehand's goto resolves without a response when the browser cancels the navigation, leaving the tab on its start page;
|
|
368
|
-
* Helium does this to a navigation made in about its first second after launch. One retry covers that; a second is an error.
|
|
369
|
-
*/
|
|
370
|
-
async function navigate(page, url, timeout, signal) {
|
|
371
|
-
const started = Date.now();
|
|
372
|
-
for (let attempt = 1;; attempt++) {
|
|
373
|
-
signal.throwIfAborted();
|
|
374
|
-
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: Math.max(1, timeout - (Date.now() - started)) });
|
|
375
|
-
if (response || !START_PAGE.test(await page.url()))
|
|
376
|
-
return response?.status();
|
|
377
|
-
if (attempt === 2)
|
|
378
|
-
throw new BrowseToolError("navigation_cancelled", "The browser cancelled the navigation twice and the tab is still blank. An extension or policy in this browser may block the URL; check it in the browser, or retry open.");
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
390
|
/** Stops waiting immediately; the caller is responsible for closing the remote browser. */
|
|
382
391
|
function abortable(promise, signal) {
|
|
383
392
|
return new Promise((resolve, reject) => {
|
|
@@ -405,6 +414,10 @@ export class BrowseSession {
|
|
|
405
414
|
session;
|
|
406
415
|
queue = Promise.resolve();
|
|
407
416
|
active;
|
|
417
|
+
/** Asks the running batch to stop before its next step. */
|
|
418
|
+
stopBatch;
|
|
419
|
+
/** Whether the running batch may have reached the browser, so its steps may have run. */
|
|
420
|
+
batchSent = false;
|
|
408
421
|
snapshotNumber = 0;
|
|
409
422
|
generation = 0;
|
|
410
423
|
contextReadyAt = new Map();
|
|
@@ -415,8 +428,10 @@ export class BrowseSession {
|
|
|
415
428
|
cookies;
|
|
416
429
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
417
430
|
delegate;
|
|
418
|
-
/**
|
|
419
|
-
|
|
431
|
+
/** This conversation's tabs in the user's real browser, until close. */
|
|
432
|
+
real;
|
|
433
|
+
/** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
|
|
434
|
+
extensions = new Map();
|
|
420
435
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
421
436
|
stagehandModel;
|
|
422
437
|
describeInference;
|
|
@@ -466,7 +481,10 @@ export class BrowseSession {
|
|
|
466
481
|
await this.closeOwned();
|
|
467
482
|
if (this.delegate && this.delegate.owner !== this.owner(scope))
|
|
468
483
|
await this.dropDelegate();
|
|
484
|
+
if (this.real && this.real.owner !== this.owner(scope))
|
|
485
|
+
await this.closeReal();
|
|
469
486
|
controller.signal.throwIfAborted();
|
|
487
|
+
this.batchSent = false;
|
|
470
488
|
return await abortable(this.dispatch(params, scope, isAi), controller.signal);
|
|
471
489
|
}
|
|
472
490
|
catch (error) {
|
|
@@ -476,8 +494,10 @@ export class BrowseSession {
|
|
|
476
494
|
throw error;
|
|
477
495
|
const timedOut = error instanceof BrowseToolError && error.code === "timeout";
|
|
478
496
|
// The broker keeps or releases a shared browser by its own deadline; only the outcome here is unknown.
|
|
479
|
-
|
|
497
|
+
// So does OpenCode Browse with the real browser's tabs.
|
|
498
|
+
if (this.delegate || this.real)
|
|
480
499
|
throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. Take a snapshot before retrying.`);
|
|
500
|
+
await this.stopBatch?.();
|
|
481
501
|
const kept = await this.keepIfResponsive(params.tabId);
|
|
482
502
|
throw new BrowseToolError(timedOut ? "timeout" : "cancelled", `${timedOut ? "Operation timed out" : "Operation cancelled"}; the action may have completed. ${{
|
|
483
503
|
kept: "The browser still responds and was kept: take a snapshot before retrying.",
|
|
@@ -493,21 +513,26 @@ export class BrowseSession {
|
|
|
493
513
|
}
|
|
494
514
|
});
|
|
495
515
|
this.queue = work.catch(() => undefined);
|
|
496
|
-
|
|
516
|
+
const reply = signal ? abortable(work, signal) : work;
|
|
517
|
+
if (isAi || params.action !== "batch")
|
|
518
|
+
return reply;
|
|
519
|
+
// Every batch failure says how far the batch got, or that it cannot tell.
|
|
520
|
+
return reply.catch(cause => {
|
|
521
|
+
if (cause instanceof BrowseToolError && cause.batch)
|
|
522
|
+
throw cause;
|
|
523
|
+
const known = translate(cause);
|
|
524
|
+
const code = known instanceof BrowseToolError ? known.code : signal?.aborted ? "cancelled" : "browser_error";
|
|
525
|
+
const total = params.steps?.length ?? 0;
|
|
526
|
+
if (!this.batchSent)
|
|
527
|
+
throw new BrowseToolError(code, `${messageOf(known)} No batch steps were run.`, { total, completed: 0, outcomeUnknown: false });
|
|
528
|
+
throw new BrowseToolError(code, `${messageOf(known)} The batch may have partly run; inspect the page before repeating anything.`, { total, outcomeUnknown: true });
|
|
529
|
+
});
|
|
497
530
|
}
|
|
498
531
|
async shutdown() {
|
|
499
532
|
this.generation++;
|
|
500
533
|
this.active?.abort(abortError("The conversation ended; browser cleanup requested."));
|
|
501
534
|
// Begin releasing immediately, in case the host cuts shutdown handlers short.
|
|
502
|
-
await Promise.all([this.closeOwned(), this.dropDelegate()]);
|
|
503
|
-
// Only after release: a live session may still be using the extension. Best-effort within the host's shutdown time.
|
|
504
|
-
// Content-Type is cleared on the bodyless DELETE as Stagehand's own cleanup does.
|
|
505
|
-
const extension = this.extension;
|
|
506
|
-
this.extension = undefined;
|
|
507
|
-
if (extension) {
|
|
508
|
-
await deadline(extension.id.then(id => extension.client.extensions.delete(id, { headers: { "Content-Type": null }, timeout: 500, maxRetries: 0 })), 500)
|
|
509
|
-
.catch(() => undefined);
|
|
510
|
-
}
|
|
535
|
+
await Promise.all([this.closeOwned(), this.dropDelegate(), this.closeReal()]);
|
|
511
536
|
}
|
|
512
537
|
/** Which credentials resolve for this profile. Starts no browser and leaves the session alone. */
|
|
513
538
|
async readiness(context, signal) {
|
|
@@ -550,7 +575,21 @@ export class BrowseSession {
|
|
|
550
575
|
}
|
|
551
576
|
/** Runs one operation; a dropped connection is repaired and the operation repeated only when that cannot double an action. */
|
|
552
577
|
async dispatch(params, context, ai) {
|
|
553
|
-
|
|
578
|
+
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded.
|
|
579
|
+
if (!this.real && !this.delegate && !this.session && !ai && opensBrowser(params))
|
|
580
|
+
this.real = await this.realBrowser(params, context);
|
|
581
|
+
if (this.real) {
|
|
582
|
+
try {
|
|
583
|
+
return await this.inRealBrowser(this.real, params, context, ai);
|
|
584
|
+
}
|
|
585
|
+
catch (error) {
|
|
586
|
+
// OpenCode Browse is gone, and this conversation's tabs with it: the next start may choose another browser.
|
|
587
|
+
if (error instanceof BrowseToolError && error.code === "real_browser_unreachable")
|
|
588
|
+
await this.closeReal();
|
|
589
|
+
throw error;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (!this.delegate && !this.session && this.profileBroker && !ai && opensBrowser(params)) {
|
|
554
593
|
// SAFETY: only browse actions open a browser, and browse_ai calls were excluded above.
|
|
555
594
|
const key = await this.sharedKey(params, context);
|
|
556
595
|
// The broker reads cookies with its own machine's browsers, not a host's provider.
|
|
@@ -596,10 +635,151 @@ export class BrowseSession {
|
|
|
596
635
|
}
|
|
597
636
|
return config.localUserDataDir ? `launch:${config.localUserDataDir}` : undefined;
|
|
598
637
|
}
|
|
638
|
+
/** The real-browser session a call would open: a local start that asks for no browser of its own, in a profile that configures one. */
|
|
639
|
+
async realBrowser(p, context) {
|
|
640
|
+
if ((p.backend ?? this.defaultBackend) !== "local" || p.cdpUrl || p.endpoint || p.headless !== undefined)
|
|
641
|
+
return undefined;
|
|
642
|
+
// The real browser has the person's logins already; an import is for a browser this tool launches.
|
|
643
|
+
if (p.action === "cookie_import")
|
|
644
|
+
return undefined;
|
|
645
|
+
const config = await this.config(context, "local");
|
|
646
|
+
if (!config.realBrowser?.command.length)
|
|
647
|
+
return undefined;
|
|
648
|
+
const policy = domainLists(config, p);
|
|
649
|
+
// OpenCode Browse fences where a tab may navigate; it has nothing that refuses named domains.
|
|
650
|
+
if (policy?.blockedDomains?.length) {
|
|
651
|
+
throw new BrowseToolError("unsupported_backend", "Blocked domains cannot be enforced in the user's real browser. Start with headless true or backend \"browserbase\" to keep them.");
|
|
652
|
+
}
|
|
653
|
+
return RealBrowserSession.open(config.realBrowser.command, { name: this.identity.integration, version: "1" }, this.owner(context), `${this.identity.name} ${context.sessionId.slice(0, 6)}`, policy?.allowedDomains?.flatMap(domain => [domain, `*.${domain}`]));
|
|
654
|
+
}
|
|
655
|
+
async inRealBrowser(real, params, context, ai) {
|
|
656
|
+
// SAFETY: `ai` marks a browse_ai call, whose arguments are AIParams; every other call's are BrowserParams.
|
|
657
|
+
if (ai)
|
|
658
|
+
return this.aiInRealBrowser(real, params, context);
|
|
659
|
+
const p = params;
|
|
660
|
+
if (p.backend === "browserbase" || p.cdpUrl || p.endpoint || p.headless !== undefined) {
|
|
661
|
+
throw new BrowseToolError("browser_change", "Close the current browser before changing its backend, endpoint, or launch settings.");
|
|
662
|
+
}
|
|
663
|
+
// Listing the cookie sources needs no browser.
|
|
664
|
+
if (p.action === "cookie_profiles")
|
|
665
|
+
return this.browse(p, context);
|
|
666
|
+
if (p.action === "ask" || p.target !== undefined)
|
|
667
|
+
return this.classifyInRealBrowser(real, p, context);
|
|
668
|
+
if (p.action === "har_stop") {
|
|
669
|
+
const { capture, view } = await real.harStop(context.signal, operationTimeout(p, false));
|
|
670
|
+
const path = p.path ?? join(tmpdir(), `${this.identity.integration}-har`, `${new Date().toISOString().replace(/[:.]/g, "-")}.har`);
|
|
671
|
+
const summary = await writeCaptureHar(capture, path, this.identity.integration);
|
|
672
|
+
return {
|
|
673
|
+
action: p.action, sessionId: null, backend: "local", origin: "connected", ...view,
|
|
674
|
+
data: { ...summary, note: "The real browser's capture redacts credentials, leaves out the bodies of pages, scripts, styles, and images, and holds at most 1000 requests. Read the HAR with scripts; for a complete recording, record a browser started with headless true or backend \"browserbase\"." },
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
// Steps run one at a time from here on, so a batch that fails later may have partly run.
|
|
678
|
+
if (p.action === "batch")
|
|
679
|
+
this.batchSent = true;
|
|
680
|
+
const output = await real.run(p, context.signal, operationTimeout(p, false));
|
|
681
|
+
if (p.action === "close")
|
|
682
|
+
this.real = undefined;
|
|
683
|
+
return output;
|
|
684
|
+
}
|
|
685
|
+
/**
|
|
686
|
+
* ask and JEV in the real browser. They read OpenCode Browse's outline and the page's visible text where a
|
|
687
|
+
* Stagehand browser reads its snapshot tree; the classifiers and their settings are the same.
|
|
688
|
+
*/
|
|
689
|
+
async classifyInRealBrowser(real, p, context) {
|
|
690
|
+
const purpose = p.action === "ask" ? "ask" : "jev";
|
|
691
|
+
const config = await this.config({ ...context, purpose }, "local");
|
|
692
|
+
const jev = purpose === "jev" ? this.classifier("jev", config) : undefined;
|
|
693
|
+
if (jev && p.visual)
|
|
694
|
+
this.visualAllowed(jev.spec, "jevModel");
|
|
695
|
+
const models = purpose === "ask" ? this.askModels(config, p.fields, p.visual) : undefined;
|
|
696
|
+
const read = await real.read(p.tabId, Boolean(p.visual), context.signal, operationTimeout(p, false));
|
|
697
|
+
const image = read.image && { mimeType: read.image.mimeType === "image/jpeg" ? "image/jpeg" : "image/png", data: read.image.data };
|
|
698
|
+
const view = { sessionId: null, backend: "local", origin: "connected", tabId: read.tabId, url: read.url, title: read.title };
|
|
699
|
+
const title = read.title ?? "";
|
|
700
|
+
if (models) {
|
|
701
|
+
// The text says what the page shows; the outline adds what controls hold and whether they are checked.
|
|
702
|
+
const text = `${read.text}\n\nControls:\n${read.outline.replace(/ \[ref=e\d+\]/g, "").replace(/\[ref=e\d+ /g, "[")}`;
|
|
703
|
+
try {
|
|
704
|
+
return { action: p.action, ...view, data: await askPage({ ...models, ...(image ? { images: [image] } : {}) }, { url: read.url, title, text }, p.fields, context.signal) };
|
|
705
|
+
}
|
|
706
|
+
catch (error) {
|
|
707
|
+
if (context.signal.aborted)
|
|
708
|
+
throw error;
|
|
709
|
+
throw new BrowseToolError("ask_error", `${messageOf(error)} Take a snapshot and read the page instead.`);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const candidates = outlineCandidates(read.outline, p.action);
|
|
713
|
+
if (!candidates.length)
|
|
714
|
+
throw new BrowseToolError("jev_no_candidates", "The page has no elements this action can target. Take a snapshot to inspect it.");
|
|
715
|
+
const model = classifierName(jev.spec);
|
|
716
|
+
const pick = await this.pick(candidates, { url: read.url, title, action: p.action, request: p.target }, jev.classify, image, context.signal);
|
|
717
|
+
if (!pick.chosen)
|
|
718
|
+
return { action: p.action, ...view, data: { jev: this.declined(model, pick, ref => ref) }, code: pick.none ? "jev_none" : "jev_uncertain", isError: true };
|
|
719
|
+
const output = await real.run({ ...p, target: undefined, visual: undefined, selector: pick.chosen.ref }, context.signal, operationTimeout(p, false));
|
|
720
|
+
return { ...output, data: { ...output.data, jev: { model, label: pick.chosen.label, confidence: pick.confidence } } };
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* browse_ai in the real browser: act, observe, and extract on the page's outline and text, with the host's own
|
|
724
|
+
* inference. act performs the one action the model chose; a page that offers none is a failed act, not an error.
|
|
725
|
+
*/
|
|
726
|
+
async aiInRealBrowser(real, p, context) {
|
|
727
|
+
const generate = this.stagehandModel.model?.generate;
|
|
728
|
+
if (!generate) {
|
|
729
|
+
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".`);
|
|
730
|
+
}
|
|
731
|
+
let schema;
|
|
732
|
+
try {
|
|
733
|
+
schema = p.schema ? z.fromJSONSchema(p.schema) : undefined;
|
|
734
|
+
}
|
|
735
|
+
catch (error) {
|
|
736
|
+
throw new BrowseToolError("invalid_arguments", `schema is not a supported JSON Schema: ${messageOf(error).slice(0, 300)}`);
|
|
737
|
+
}
|
|
738
|
+
const timeout = operationTimeout(p, true);
|
|
739
|
+
const read = await real.read(p.tabId, false, context.signal, timeout);
|
|
740
|
+
const view = { action: p.action, sessionId: null, backend: "local", origin: "connected", tabId: read.tabId, url: read.url, title: read.title };
|
|
741
|
+
try {
|
|
742
|
+
if (p.action === "extract") {
|
|
743
|
+
const extracted = await extractPage(generate, read, p.instruction, p.schema);
|
|
744
|
+
const checked = schema?.safeParse(extracted);
|
|
745
|
+
if (checked && !checked.success)
|
|
746
|
+
throw new BrowseToolError("ai_error", "The model's answer does not match the schema. Retry, or take a snapshot and read the page.");
|
|
747
|
+
return { ...view, data: extracted };
|
|
748
|
+
}
|
|
749
|
+
const actions = await observePage(generate, read, p.instruction, p.action === "act");
|
|
750
|
+
if (p.action === "observe")
|
|
751
|
+
return { ...view, data: actions };
|
|
752
|
+
const [action] = actions;
|
|
753
|
+
if (!action)
|
|
754
|
+
return { ...view, data: { success: false, message: "The page offers no element that carries out the instruction. Take a snapshot to check the page.", actions: [] }, isError: true, code: "act_failed" };
|
|
755
|
+
const [first = ""] = action.arguments;
|
|
756
|
+
// press acts on the focused element, so the chosen one is clicked into first.
|
|
757
|
+
const steps = action.method === "press"
|
|
758
|
+
? [{ action: "click", selector: action.selector, tabId: read.tabId }, { action: "press", key: first, tabId: read.tabId }]
|
|
759
|
+
: [{ action: action.method, selector: action.selector, tabId: read.tabId, ...(action.method === "fill" ? { value: first } : action.method === "select" ? { values: action.arguments } : {}) }];
|
|
760
|
+
let done;
|
|
761
|
+
for (const step of steps)
|
|
762
|
+
done = await real.run(step, context.signal, timeout);
|
|
763
|
+
return { ...view, url: done?.url ?? read.url, title: done?.title ?? read.title, data: { success: true, message: `${action.method} on ${action.description}`, actions: [action] } };
|
|
764
|
+
}
|
|
765
|
+
catch (error) {
|
|
766
|
+
if (context.signal.aborted || error instanceof BrowseToolError)
|
|
767
|
+
throw error;
|
|
768
|
+
throw new BrowseToolError("ai_error", `${messageOf(error).slice(0, 300)} Use browse with a snapshot and refs instead.`);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
/** Closes this conversation's tabs in the real browser; the browser itself is the user's and stays. */
|
|
772
|
+
async closeReal() {
|
|
773
|
+
const real = this.real;
|
|
774
|
+
this.real = undefined;
|
|
775
|
+
await real?.close(AbortSignal.timeout(5000)).catch(() => undefined);
|
|
776
|
+
}
|
|
599
777
|
/** Runs a call in the broker; close ends the conversation there, and a lost broker is reopened by the next call. */
|
|
600
778
|
async forward(params, context, ai) {
|
|
601
779
|
const { conv, connection } = this.delegate;
|
|
602
780
|
const { signal, purpose: _purpose, ...rest } = context;
|
|
781
|
+
// The broker reports a batch's progress itself; a broker that goes away mid-call leaves it unknown.
|
|
782
|
+
this.batchSent = true;
|
|
603
783
|
try {
|
|
604
784
|
const output = await connection.run(conv, params, rest, ai, this.defaultBackend, signal);
|
|
605
785
|
if (params.action === "close")
|
|
@@ -636,7 +816,7 @@ export class BrowseSession {
|
|
|
636
816
|
// Old and unused handles are dropped, never closed: closing any Browserbase handle releases the remote session.
|
|
637
817
|
let browser, stagehand;
|
|
638
818
|
try {
|
|
639
|
-
browser = await connectRetrying(() => browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
|
|
819
|
+
browser = await connectRetrying(async () => (await stagehandSdk()).browserbase.connect({ apiKey: session.config.apiKey, sessionId }), context.signal);
|
|
640
820
|
stagehand = await createStagehand(browser, this.stagehandModel, context.signal);
|
|
641
821
|
}
|
|
642
822
|
catch (error) {
|
|
@@ -785,27 +965,34 @@ export class BrowseSession {
|
|
|
785
965
|
return;
|
|
786
966
|
throw new BrowseToolError("visual_unsupported", `${classifierName(spec)} reads text only. Pick an image-capable classifier with /browse ${setting === "jevModel" ? "jev" : "ask"}-model (workers-ai, or one of the host's), or retry without visual.`);
|
|
787
967
|
}
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
const image = await page.screenshot({ type: "jpeg", quality: 70, fullPage: false, timeout: 10_000 });
|
|
791
|
-
return { mimeType: "image/jpeg", data: Buffer.from(image).toString("base64") };
|
|
792
|
-
}
|
|
793
|
-
client(config) {
|
|
968
|
+
async client(config) {
|
|
969
|
+
const { Browserbase } = await import("@browserbasehq/sdk");
|
|
794
970
|
return new Browserbase({ apiKey: config.apiKey, timeout: 15_000, maxRetries: 0 });
|
|
795
971
|
}
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
extension
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
972
|
+
/**
|
|
973
|
+
* The project's uploaded Stagehand extension: the one the cache file remembers, else a new upload. `fresh` uploads
|
|
974
|
+
* again after the project turned out to have lost the remembered one.
|
|
975
|
+
*/
|
|
976
|
+
extensionId(client, config, fresh = false) {
|
|
977
|
+
const key = extensionCacheKey(config.apiKey ?? "", config.projectId ?? "");
|
|
978
|
+
let extension = fresh ? undefined : this.extensions.get(key);
|
|
979
|
+
if (!extension) {
|
|
980
|
+
// No signal: a cancelled start leaves the upload remembered for the next launch.
|
|
981
|
+
extension = (async () => provisionExtension({
|
|
982
|
+
path: extensionCachePath(), key, archive: await (await stagehandSdk()).getExtensionArchive(), fresh,
|
|
983
|
+
upload: async () => {
|
|
984
|
+
const archive = await (await stagehandSdk()).getExtensionArchive();
|
|
985
|
+
return (await client.extensions.create({ file: new File([archive.slice().buffer], "stagehand-extension.zip", { type: "application/zip" }) })).id;
|
|
986
|
+
},
|
|
987
|
+
// Content-Type is cleared on the bodyless DELETE as Stagehand's own cleanup does.
|
|
988
|
+
remove: id => client.extensions.delete(id, { headers: { "Content-Type": null }, timeout: 5000, maxRetries: 0 }),
|
|
989
|
+
}))();
|
|
990
|
+
const pending = extension;
|
|
991
|
+
this.extensions.set(key, pending);
|
|
992
|
+
pending.catch(() => { if (this.extensions.get(key) === pending)
|
|
993
|
+
this.extensions.delete(key); });
|
|
994
|
+
}
|
|
995
|
+
return extension;
|
|
809
996
|
}
|
|
810
997
|
current() {
|
|
811
998
|
if (!this.session || this.session.closing || this.session.browser.closed || !this.session.stagehand) {
|
|
@@ -853,13 +1040,13 @@ export class BrowseSession {
|
|
|
853
1040
|
return this.joinShared(context, config, p, domainPolicy, attach, userDataDir);
|
|
854
1041
|
// A temporary profile belongs to this conversation alone.
|
|
855
1042
|
const port = await freePort();
|
|
856
|
-
const browser = await localBrowser.launch({
|
|
1043
|
+
const browser = await (await stagehandSdk()).localBrowser.launch({
|
|
857
1044
|
headless: headless ?? false, viewport: { width: 1280, height: 800 },
|
|
858
1045
|
...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}), port,
|
|
859
1046
|
});
|
|
860
1047
|
return this.initialize({ owner: this.owner(context), backend, config, browser, headless: headless ?? false, debugPort: port, snapshots: new Map(), keepAlive: false, domainPolicy, ownedTabs: new Set(), createdTabs: new Set() }, context);
|
|
861
1048
|
}
|
|
862
|
-
const client = this.client(config);
|
|
1049
|
+
const client = await this.client(config);
|
|
863
1050
|
if (contextId) {
|
|
864
1051
|
const saved = await client.contexts.retrieve(contextId, { signal: context.signal }).catch(error => {
|
|
865
1052
|
throw error.status === 404
|
|
@@ -876,10 +1063,11 @@ export class BrowseSession {
|
|
|
876
1063
|
if (remaining > 0)
|
|
877
1064
|
await delay(remaining, undefined, { signal: context.signal });
|
|
878
1065
|
}
|
|
879
|
-
|
|
1066
|
+
let extension = await this.extensionId(client, config);
|
|
880
1067
|
context.signal.throwIfAborted();
|
|
881
|
-
const
|
|
882
|
-
|
|
1068
|
+
const { browserbase } = await stagehandSdk();
|
|
1069
|
+
const create = (keepAlive) => browserbase.launch({
|
|
1070
|
+
apiKey: config.apiKey, projectId: config.projectId, region: config.region, extensionId: extension.id, api_timeout: SESSION_LIFETIME_SECONDS, keepAlive,
|
|
883
1071
|
browserSettings: {
|
|
884
1072
|
viewport: { width: 1280, height: 800 }, ...(contextId ? { context: { id: contextId, persist: true } } : {}),
|
|
885
1073
|
...(config.navigationPolicyId ? { riskPolicyId: config.navigationPolicyId } : {}),
|
|
@@ -887,6 +1075,22 @@ export class BrowseSession {
|
|
|
887
1075
|
...(proxyCountry ? { proxies: [{ type: "browserbase", geolocation: { country: proxyCountry } }] } : {}),
|
|
888
1076
|
userMetadata: { integration: this.identity.integration, profile: context.profile, conversation: context.sessionId },
|
|
889
1077
|
});
|
|
1078
|
+
// Browserbase refuses a session that names an extension the project no longer has, and Stagehand hides why a
|
|
1079
|
+
// session failed: after a failure with a remembered extension, ask whether it still exists, and upload again if not.
|
|
1080
|
+
const launch = async (keepAlive) => {
|
|
1081
|
+
try {
|
|
1082
|
+
return await create(keepAlive);
|
|
1083
|
+
}
|
|
1084
|
+
catch (error) {
|
|
1085
|
+
const gone = extension.cached && await client.extensions.retrieve(extension.id, { timeout: 5000, maxRetries: 0 })
|
|
1086
|
+
.then(() => false, (cause) => cause.status === 404);
|
|
1087
|
+
if (!gone)
|
|
1088
|
+
throw error;
|
|
1089
|
+
context.signal.throwIfAborted();
|
|
1090
|
+
extension = await this.extensionId(client, config, true);
|
|
1091
|
+
return create(keepAlive);
|
|
1092
|
+
}
|
|
1093
|
+
};
|
|
890
1094
|
let keepAlive = this.keepAliveAllowed;
|
|
891
1095
|
let browser;
|
|
892
1096
|
try {
|
|
@@ -911,7 +1115,7 @@ export class BrowseSession {
|
|
|
911
1115
|
}
|
|
912
1116
|
this.session = session;
|
|
913
1117
|
try {
|
|
914
|
-
session.stagehand = await Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
|
|
1118
|
+
session.stagehand = await (await stagehandSdk()).Stagehand.create({ browser, logging: { level: "off" }, ...this.stagehandModel });
|
|
915
1119
|
context.signal.throwIfAborted();
|
|
916
1120
|
if (this.session !== session)
|
|
917
1121
|
throw abortError();
|
|
@@ -1008,7 +1212,7 @@ export class BrowseSession {
|
|
|
1008
1212
|
// guard, and one that ends with this process would take the extension's connection down with the client's.
|
|
1009
1213
|
const extensionCdpUrl = attach.extensionCdpUrl ?? opened.browserUrl;
|
|
1010
1214
|
try {
|
|
1011
|
-
browser = await connectRetrying(() => localBrowser.connect({ cdpUrl: opened.url, extensionCdpUrl }), context.signal).catch(error => {
|
|
1215
|
+
browser = await connectRetrying(async () => (await stagehandSdk()).localBrowser.connect({ cdpUrl: opened.url, extensionCdpUrl }), context.signal).catch(error => {
|
|
1012
1216
|
const known = translate(error);
|
|
1013
1217
|
if (known instanceof BrowseToolError)
|
|
1014
1218
|
throw known;
|
|
@@ -1023,9 +1227,9 @@ export class BrowseSession {
|
|
|
1023
1227
|
else {
|
|
1024
1228
|
// The avatar and profile menu then say which harness owns the window; a profile Chrome cannot rename still launches.
|
|
1025
1229
|
await nameChromeProfile(userDataDir, `${this.identity.name} browse`).catch(() => undefined);
|
|
1026
|
-
await refreshExtensionWorkers(userDataDir, await getExtensionArchive());
|
|
1230
|
+
await refreshExtensionWorkers(userDataDir, await (await stagehandSdk()).getExtensionArchive());
|
|
1027
1231
|
quitPort = await freePort();
|
|
1028
|
-
browser = await localBrowser.launch({
|
|
1232
|
+
browser = await (await stagehandSdk()).localBrowser.launch({
|
|
1029
1233
|
headless: p.headless ?? false, viewport: { width: 1280, height: 800 },
|
|
1030
1234
|
...(config.localExecutablePath ? { executablePath: config.localExecutablePath } : {}),
|
|
1031
1235
|
port: quitPort, userDataDir, ignoreDefaultArgs: PERSISTENT_PROFILE_IGNORED_ARGS,
|
|
@@ -1216,17 +1420,34 @@ export class BrowseSession {
|
|
|
1216
1420
|
const id = tabId ?? session.tabId;
|
|
1217
1421
|
// In a shared browser only a tab chosen by id is taken over; no conversation drifts into the user's or a closed one.
|
|
1218
1422
|
const page = id ? pages.find(page => page.pageId === id) : pages.find(page => session.ownedTabs.has(page.pageId)) ?? (session.shared ? undefined : pages[0]);
|
|
1219
|
-
if (!page)
|
|
1220
|
-
throw
|
|
1221
|
-
? "This conversation has no tab here, or the target tab is closed or another conversation's. Open one with tab_new, or select one of the listed tabs by tabId."
|
|
1222
|
-
: "The target tab is closed or missing. List tabs, select an existing tab, or create a new one.");
|
|
1223
|
-
}
|
|
1423
|
+
if (!page)
|
|
1424
|
+
throw this.tabMissing(session);
|
|
1224
1425
|
if (!session.tabId)
|
|
1225
1426
|
session.tabId = page.pageId;
|
|
1226
1427
|
// In a shared browser, acting on a tab claims it, so no other conversation can use it meanwhile.
|
|
1227
1428
|
session.ownedTabs.add(page.pageId);
|
|
1228
1429
|
return page;
|
|
1229
1430
|
}
|
|
1431
|
+
/**
|
|
1432
|
+
* The tab a call acts on, named by its ID without asking the browser for its tabs: the batch executor finds the live tab
|
|
1433
|
+
* itself and reports a closed one. Only a call with no selected tab lists them. In a shared browser, acting on a tab
|
|
1434
|
+
* claims it before the request, so no other conversation can take it meanwhile.
|
|
1435
|
+
*/
|
|
1436
|
+
async tab(session, tabId) {
|
|
1437
|
+
const id = tabId ?? session.tabId;
|
|
1438
|
+
if (!id)
|
|
1439
|
+
return this.page(session);
|
|
1440
|
+
if (this.ownedByOther(session, id))
|
|
1441
|
+
throw this.tabMissing(session);
|
|
1442
|
+
session.ownedTabs.add(id);
|
|
1443
|
+
const { Page } = await stagehandSdk();
|
|
1444
|
+
return new Page(session.stagehand.rpcClient, { pageId: id });
|
|
1445
|
+
}
|
|
1446
|
+
tabMissing(session) {
|
|
1447
|
+
return new BrowseToolError("tab_missing", session.shared
|
|
1448
|
+
? "This conversation has no tab here, or the target tab is closed or another conversation's. Open one with tab_new, or select one of the listed tabs by tabId."
|
|
1449
|
+
: "The target tab is closed or missing. List tabs, select an existing tab, or create a new one.");
|
|
1450
|
+
}
|
|
1230
1451
|
/**
|
|
1231
1452
|
* Runs one operation beside the browser in a single round trip. Stagehand cannot cancel a running batch: on a deadline
|
|
1232
1453
|
* or cancellation the browser-side batch stops at its own timeout, and run() checks whether the browser still answers.
|
|
@@ -1235,77 +1456,159 @@ export class BrowseSession {
|
|
|
1235
1456
|
context.signal.throwIfAborted();
|
|
1236
1457
|
const result = await session.stagehand.experimentalBatch(operation, JSON.parse(JSON.stringify(input)), {
|
|
1237
1458
|
...(page ? { page } : {}), timeout: operationTimeout(p, false),
|
|
1459
|
+
}).catch(error => {
|
|
1460
|
+
if (!page || !/^Stagehand callback batch page was not found:/.test(messageOf(error)))
|
|
1461
|
+
throw error;
|
|
1462
|
+
// The tab closed since it was last seen: give up the claim tab() made on it.
|
|
1463
|
+
session.ownedTabs.delete(page.pageId);
|
|
1464
|
+
throw this.tabMissing(session);
|
|
1238
1465
|
});
|
|
1239
1466
|
// A cancelled reply must not install a late snapshot or alter the next call's selected tab.
|
|
1240
1467
|
context.signal.throwIfAborted();
|
|
1241
1468
|
return result;
|
|
1242
1469
|
}
|
|
1243
|
-
|
|
1244
|
-
|
|
1470
|
+
/** 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. */
|
|
1471
|
+
prepare(session, p, budget) {
|
|
1245
1472
|
const control = p.action === "click" || p.action === "fill" || p.action === "select";
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
}
|
|
1257
|
-
|
|
1473
|
+
// Page-level waits get up to 2s less than the operation deadline so a clean timeout reply wins the race.
|
|
1474
|
+
const input = {
|
|
1475
|
+
...p, action: p.action, readTimeoutMs: RESULT_READ_MS,
|
|
1476
|
+
pageTimeoutMs: Math.ceil(Math.max(budget - 2_000, budget / 2)), fenced: Boolean(session.domainPolicy),
|
|
1477
|
+
};
|
|
1478
|
+
// The worker writes the version into the refs it returns, so it is taken before the call; a failed call skips a number.
|
|
1479
|
+
if (p.action === "snapshot")
|
|
1480
|
+
input.snapshot = { version: `s${++this.snapshotNumber}`, maxChars: p.maxChars ?? 20_000 };
|
|
1481
|
+
const refused = p.url ? fenced(p.url, session.domainPolicy) : undefined;
|
|
1482
|
+
if (refused)
|
|
1483
|
+
throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
|
|
1484
|
+
if (control || (p.action === "wait" && p.selector)) {
|
|
1485
|
+
const target = this.reference(session, p.tabId ?? session.tabId, p.selector);
|
|
1486
|
+
const position = control ? groupedPosition(target.selector) : undefined;
|
|
1258
1487
|
input.selector = position?.base ?? target.selector;
|
|
1259
1488
|
input.nth = position?.index;
|
|
1260
1489
|
if (target.cached)
|
|
1261
1490
|
input.reference = { url: target.cached.url, id: target.refId, xpath: target.selector };
|
|
1262
1491
|
}
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
session.snapshots.delete(result.tabId);
|
|
1269
|
-
throw new BrowseToolError(result.error.code, result.error.message);
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
catch (error) {
|
|
1273
|
-
if (changesPage && !context.signal.aborted && !NOT_SENT.test(messageOf(error)))
|
|
1274
|
-
session.snapshots.clear();
|
|
1275
|
-
if (p.action !== "evaluate" || !/^Uncaught\b/.test(messageOf(error)))
|
|
1276
|
-
throw error;
|
|
1277
|
-
const detail = messageOf(error).replace(/^Uncaught\s*(?:\(in promise\)\s*)?/, "").slice(0, 500);
|
|
1278
|
-
throw new BrowseToolError("script_error", (detail
|
|
1279
|
-
? `The script threw: ${detail}.`
|
|
1280
|
-
: "The script threw; Stagehand hides the exception message. To see it, wrap the script: (() => { try { ... } catch (e) { return String(e) } })().")
|
|
1281
|
-
+ " Side effects before the throw may have happened.");
|
|
1282
|
-
}
|
|
1283
|
-
if (changesPage)
|
|
1492
|
+
return input;
|
|
1493
|
+
}
|
|
1494
|
+
/** Applies a completed action to the conversation's state (selected tab, snapshot refs) and returns what its result reports. */
|
|
1495
|
+
finish(session, p, input, result) {
|
|
1496
|
+
if (changesPage(p))
|
|
1284
1497
|
session.snapshots.clear();
|
|
1285
1498
|
if (!session.tabId || p.action === "tab_select")
|
|
1286
1499
|
session.tabId = result.tabId;
|
|
1287
|
-
const { value, snapshot, snapshotUrl, error: _error, ...view } = result;
|
|
1500
|
+
const { value, snapshot, snapshotUrl, navigation, image, error: _error, ...view } = result;
|
|
1288
1501
|
let data;
|
|
1289
1502
|
let note;
|
|
1290
1503
|
if (snapshot) {
|
|
1291
|
-
const version =
|
|
1292
|
-
session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.
|
|
1293
|
-
|
|
1294
|
-
const limit = p.maxChars ?? 20_000;
|
|
1295
|
-
data = { snapshotId: version, tree: tree.slice(0, limit), truncated: tree.length > limit };
|
|
1504
|
+
const { version } = input.snapshot;
|
|
1505
|
+
session.snapshots.set(result.tabId, { version, url: snapshotUrl, refs: snapshot.refs });
|
|
1506
|
+
data = { snapshotId: version, tree: snapshot.tree, truncated: snapshot.truncated };
|
|
1296
1507
|
}
|
|
1297
1508
|
else if (p.action === "select") {
|
|
1298
|
-
|
|
1299
|
-
if (!selected.length)
|
|
1300
|
-
throw new BrowseToolError("not_select", "select works only on a native <select> element. For a custom dropdown, click it and then click the option.");
|
|
1301
|
-
data = { selected };
|
|
1509
|
+
data = { selected: value };
|
|
1302
1510
|
}
|
|
1303
1511
|
else if (p.action === "evaluate") {
|
|
1304
1512
|
data = value;
|
|
1305
1513
|
if (value === null || value === undefined)
|
|
1306
1514
|
note = "null can also mean undefined or a value JSON cannot carry (NaN, Infinity, -0, BigInt, a function); return String(value) to tell them apart.";
|
|
1307
1515
|
}
|
|
1308
|
-
|
|
1516
|
+
else if (navigation) {
|
|
1517
|
+
data = navigation;
|
|
1518
|
+
}
|
|
1519
|
+
return { ...view, ...(data === undefined ? {} : { data }), ...(note ? { note } : {}), ...(image ? { image: new Uint8Array(Buffer.from(image, "base64")) } : {}) };
|
|
1520
|
+
}
|
|
1521
|
+
async direct(session, p, context) {
|
|
1522
|
+
let input, result;
|
|
1523
|
+
try {
|
|
1524
|
+
input = this.prepare(session, p, operationTimeout(p, false));
|
|
1525
|
+
result = await this.batch(session, p, context, pageOperation, input, await this.tab(session, p.tabId));
|
|
1526
|
+
if (result.error) {
|
|
1527
|
+
if (result.error.code === "stale_ref")
|
|
1528
|
+
session.snapshots.delete(result.tabId);
|
|
1529
|
+
throw new BrowseToolError(result.error.code, result.error.message);
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
catch (error) {
|
|
1533
|
+
if (changesPage(p) && !NOT_SENT.test(messageOf(error)))
|
|
1534
|
+
session.snapshots.clear();
|
|
1535
|
+
throw (p.action === "evaluate" ? scriptError(messageOf(error)) : undefined) ?? error;
|
|
1536
|
+
}
|
|
1537
|
+
return { ...await this.output(p.action, session), ...this.finish(session, p, input, result) };
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* batch: the steps run in order beside the browser in one request, under one deadline. The first failure stops the
|
|
1541
|
+
* rest and nothing is rolled back; the result says how many steps completed.
|
|
1542
|
+
*/
|
|
1543
|
+
async sequence(session, p, context, budget) {
|
|
1544
|
+
// SAFETY: a step is a direct control's arguments, and every direct control is a BrowserParams.
|
|
1545
|
+
const steps = p.steps.map(step => ({ ...step, tabId: p.tabId }));
|
|
1546
|
+
const total = steps.length;
|
|
1547
|
+
const prepared = [];
|
|
1548
|
+
for (const step of steps) {
|
|
1549
|
+
try {
|
|
1550
|
+
prepared.push(this.prepare(session, step, budget));
|
|
1551
|
+
}
|
|
1552
|
+
catch (cause) {
|
|
1553
|
+
throw new BrowseToolError(cause instanceof BrowseToolError ? cause.code : "browser_error", `${messageOf(cause)} No batch steps were run.`, { total, completed: 0, failedIndex: prepared.length, outcomeUnknown: false });
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
const page = await this.tab(session, p.tabId);
|
|
1557
|
+
const stagehand = session.stagehand;
|
|
1558
|
+
const id = randomUUID();
|
|
1559
|
+
let stopping;
|
|
1560
|
+
// A request of its own: the worker runs it while the batch waits on a step, and the batch stops before its next one.
|
|
1561
|
+
const stop = () => stopping ??= deadline(stagehand.experimentalBatch(cancelPageBatch, { id, ttlMs: budget + 15_000 }, { page, timeout: 2_000 }), 2_000)
|
|
1562
|
+
.then(() => undefined, () => undefined);
|
|
1563
|
+
const abort = () => { void stop(); };
|
|
1564
|
+
this.stopBatch = stop;
|
|
1565
|
+
context.signal.addEventListener("abort", abort, { once: true });
|
|
1566
|
+
let result;
|
|
1567
|
+
try {
|
|
1568
|
+
this.batchSent = true;
|
|
1569
|
+
result = await this.batch(session, p, context, pageOperation, { id, steps: prepared, timeoutMs: budget }, page);
|
|
1570
|
+
}
|
|
1571
|
+
catch (cause) {
|
|
1572
|
+
// Sent or not is all that is known here: run() reports the outcome as unknown unless the request never left.
|
|
1573
|
+
if (NOT_SENT.test(messageOf(cause)))
|
|
1574
|
+
this.batchSent = false;
|
|
1575
|
+
else
|
|
1576
|
+
session.snapshots.clear();
|
|
1577
|
+
throw cause;
|
|
1578
|
+
}
|
|
1579
|
+
finally {
|
|
1580
|
+
context.signal.removeEventListener("abort", abort);
|
|
1581
|
+
if (this.stopBatch === stop)
|
|
1582
|
+
this.stopBatch = undefined;
|
|
1583
|
+
}
|
|
1584
|
+
const results = result.results.map((step, index) => {
|
|
1585
|
+
const { tabId: _tab, ...reported } = this.finish(session, steps[index], prepared[index], step);
|
|
1586
|
+
return { action: steps[index].action, ...reported };
|
|
1587
|
+
});
|
|
1588
|
+
const progress = { total, completed: results.length, outcomeUnknown: false };
|
|
1589
|
+
const last = results.at(-1);
|
|
1590
|
+
const output = {
|
|
1591
|
+
...await this.output(p.action, session), tabId: page.pageId, ...(last ? { url: last.url, title: last.title } : {}),
|
|
1592
|
+
// Progress comes before the results, so it survives a host that truncates a long result.
|
|
1593
|
+
batch: progress, data: { results },
|
|
1594
|
+
};
|
|
1595
|
+
if (result.failure) {
|
|
1596
|
+
const failed = steps[result.failure.index];
|
|
1597
|
+
const cause = result.failure.code === "browser_error"
|
|
1598
|
+
? (failed.action === "evaluate" ? scriptError(result.failure.message) : undefined) ?? translate(new Error(result.failure.message))
|
|
1599
|
+
: new BrowseToolError(result.failure.code, result.failure.message);
|
|
1600
|
+
if (result.failure.outcomeUnknown || changesPage(failed))
|
|
1601
|
+
session.snapshots.clear();
|
|
1602
|
+
else if (result.failure.code === "stale_ref")
|
|
1603
|
+
session.snapshots.delete(page.pageId);
|
|
1604
|
+
progress.failedIndex = result.failure.index;
|
|
1605
|
+
progress.outcomeUnknown = result.failure.outcomeUnknown;
|
|
1606
|
+
progress.error = { code: cause instanceof BrowseToolError ? cause.code : "browser_error", message: this.redact(messageOf(cause)).slice(0, 4000) };
|
|
1607
|
+
output.isError = true;
|
|
1608
|
+
output.code = progress.error.code;
|
|
1609
|
+
output.note = "The batch stopped at the failed step: later steps did not run, and earlier ones were not rolled back. Inspect the page before repeating anything.";
|
|
1610
|
+
}
|
|
1611
|
+
return output;
|
|
1309
1612
|
}
|
|
1310
1613
|
reference(session, tabId, selector) {
|
|
1311
1614
|
const reference = selector.replace(/^@/, "").replace(/^\[|\]$/g, "");
|
|
@@ -1326,34 +1629,16 @@ export class BrowseSession {
|
|
|
1326
1629
|
}
|
|
1327
1630
|
return { selector: xpath, cached, refId: match[2] };
|
|
1328
1631
|
}
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
session.snapshots.delete(page.pageId);
|
|
1336
|
-
throw new BrowseToolError("stale_ref", url !== target.cached.url
|
|
1337
|
-
? "The tab navigated since that snapshot. Take a new snapshot."
|
|
1338
|
-
: "The referenced element changed or disappeared. Take a new snapshot.");
|
|
1339
|
-
}
|
|
1340
|
-
return target.selector;
|
|
1341
|
-
}
|
|
1342
|
-
async output(action, session, page, data) {
|
|
1343
|
-
// Read in parallel, and bounded: the action already ran, so a tab that blocks now yields a result marked unresponsive
|
|
1344
|
-
// rather than a failure. A page without the guard (or mid-navigation) reports no dialogs.
|
|
1345
|
-
const view = page && await Promise.all([
|
|
1346
|
-
page.url(),
|
|
1347
|
-
deadline(page.title(), RESULT_READ_MS).catch(error => { if (expired(error))
|
|
1348
|
-
return undefined; throw error; }),
|
|
1349
|
-
deadline(page.evaluate(TAKE_DIALOGS), RESULT_READ_MS).catch(() => []),
|
|
1350
|
-
]);
|
|
1351
|
-
const dialogs = view && Array.isArray(view[2]) && view[2].length ? { dialogs: view[2] } : {};
|
|
1632
|
+
/** A tab's URL, title, answered dialogs, and document identity, in one bounded request: the action already ran, so a tab that blocks now is reported unresponsive rather than failing. */
|
|
1633
|
+
view(session, page) {
|
|
1634
|
+
return session.stagehand.experimentalBatch(viewOperation, { readTimeoutMs: RESULT_READ_MS }, { page, timeout: RESULT_READ_MS + 5_000 });
|
|
1635
|
+
}
|
|
1636
|
+
async output(action, session, page, data, seen) {
|
|
1637
|
+
const { origin: _origin, ...view } = seen ?? (page ? await this.view(session, page) : { origin: null });
|
|
1352
1638
|
return {
|
|
1353
1639
|
action, sessionId: session.browser.sessionId ?? null, backend: session.backend, origin: session.browser.origin,
|
|
1354
1640
|
...(session.backend === "browserbase" ? { projectId: session.config.projectId, contextId: session.contextId } : {}),
|
|
1355
|
-
...
|
|
1356
|
-
...(data === undefined ? {} : { data }),
|
|
1641
|
+
...view, ...(data === undefined ? {} : { data }),
|
|
1357
1642
|
};
|
|
1358
1643
|
}
|
|
1359
1644
|
/** A cookie provider call, with its refusals as tool errors. */
|
|
@@ -1382,9 +1667,9 @@ export class BrowseSession {
|
|
|
1382
1667
|
throw new BrowseToolError("cookie_profile_ambiguous", `Several browser profiles have cookies for these domains: ${listed}. Retry with browser and profile set to the one matching the task's account or organization; if the task does not say, ask the user which one.`);
|
|
1383
1668
|
}
|
|
1384
1669
|
async browse(p, context) {
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1670
|
+
if (p.action === "handoff") {
|
|
1671
|
+
throw new BrowseToolError("unsupported_backend", "handoff works in the user's real browser only. On Browserbase use live_view; a launched local browser has a visible window the user can act in.");
|
|
1672
|
+
}
|
|
1388
1673
|
if (p.action === "cookie_profiles") {
|
|
1389
1674
|
const browsers = await this.fromCookies(() => this.cookies.list(p.browser, context.signal));
|
|
1390
1675
|
return { action: p.action, sessionId: null, data: { browsers } };
|
|
@@ -1415,7 +1700,7 @@ export class BrowseSession {
|
|
|
1415
1700
|
if (this.session?.backend === "local")
|
|
1416
1701
|
throw new BrowseToolError("unsupported_backend", "Saved contexts are Browserbase-only. Close the local browser first.");
|
|
1417
1702
|
const config = await this.config(context);
|
|
1418
|
-
const created = await this.client(config).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
|
|
1703
|
+
const created = await (await this.client(config)).contexts.create({ projectId: config.projectId, name: `${context.profile}:${p.name}` }, { signal: context.signal });
|
|
1419
1704
|
const saved = { contextId: created.id, name: p.name, projectId: config.projectId, profile: context.profile };
|
|
1420
1705
|
let historySaved = false;
|
|
1421
1706
|
if (config.contextHistoryPath) {
|
|
@@ -1437,7 +1722,8 @@ export class BrowseSession {
|
|
|
1437
1722
|
if (p.action === "har_start" && this.session?.browser.origin === "connected") {
|
|
1438
1723
|
throw new BrowseToolError("unsupported_backend", "har_start records a browser this tool launched or hosts; an attached browser's tabs are the user's own.");
|
|
1439
1724
|
}
|
|
1440
|
-
const
|
|
1725
|
+
const began = Date.now();
|
|
1726
|
+
const session = opensBrowser(p) ? await this.start(context, p) : this.current();
|
|
1441
1727
|
context.signal.throwIfAborted();
|
|
1442
1728
|
if (p.action === "har_start")
|
|
1443
1729
|
return this.harStart(session, context);
|
|
@@ -1479,7 +1765,10 @@ export class BrowseSession {
|
|
|
1479
1765
|
matched: imported.matched, imported: imported.cookies.length, skipped: imported.skipped,
|
|
1480
1766
|
reloadRequired: imported.cookies.length > 0, persistedOnClose: Boolean(session.contextId || session.quitPort || session.shared?.quitPort) });
|
|
1481
1767
|
}
|
|
1482
|
-
|
|
1768
|
+
// A batch that started a browser spent part of its deadline doing so.
|
|
1769
|
+
if (p.action === "batch")
|
|
1770
|
+
return this.sequence(session, p, context, Math.max(1_000, operationTimeout(p, false) - (Date.now() - began)));
|
|
1771
|
+
if (!p.target && DIRECT_ACTIONS.has(p.action))
|
|
1483
1772
|
return this.direct(session, p, context);
|
|
1484
1773
|
if (p.action === "tabs") {
|
|
1485
1774
|
const input = { selectedTabId: session.tabId ?? null, readTimeoutMs: TAB_PROBE_MS };
|
|
@@ -1506,21 +1795,8 @@ export class BrowseSession {
|
|
|
1506
1795
|
await session.har?.follow(page.pageId);
|
|
1507
1796
|
return this.output(p.action, session, page);
|
|
1508
1797
|
}
|
|
1509
|
-
const page = await this.page(session, p.tabId);
|
|
1510
|
-
if (p.action === "tab_select") {
|
|
1511
|
-
context.signal.throwIfAborted();
|
|
1512
|
-
await session.browser.context.setActivePage(page);
|
|
1513
|
-
session.tabId = page.pageId;
|
|
1514
|
-
return this.output(p.action, session, page);
|
|
1515
|
-
}
|
|
1516
|
-
if (p.action === "live_view") {
|
|
1517
|
-
const live = await session.client.sessions.debug(session.browser.sessionId, { signal: context.signal, timeout: 10_000, maxRetries: 0 });
|
|
1518
|
-
// A person may change anything in the page, so no earlier ref stays trustworthy.
|
|
1519
|
-
session.snapshots.clear();
|
|
1520
|
-
const liveViewUrl = live.pages.find(entry => entry.id === page.pageId)?.debuggerFullscreenUrl ?? live.debuggerFullscreenUrl;
|
|
1521
|
-
return { ...await this.output(p.action, session, page), liveViewUrl };
|
|
1522
|
-
}
|
|
1523
1798
|
if (p.action === "tab_close") {
|
|
1799
|
+
const page = await this.page(session, p.tabId);
|
|
1524
1800
|
context.signal.throwIfAborted();
|
|
1525
1801
|
session.shared?.closedTabs.add(page.pageId);
|
|
1526
1802
|
await page.close();
|
|
@@ -1533,68 +1809,24 @@ export class BrowseSession {
|
|
|
1533
1809
|
}
|
|
1534
1810
|
return this.output(p.action, session, undefined, { closedTabId: page.pageId, selectedTabId: session.tabId ?? null });
|
|
1535
1811
|
}
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
if (jev && !jev.xpath)
|
|
1544
|
-
return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.result.match === "none" ? "jev_none" : "jev_uncertain", isError: true };
|
|
1545
|
-
if (jev) {
|
|
1546
|
-
const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
|
|
1547
|
-
return { ...output, data: { ...output.data, jev: jev.result } };
|
|
1548
|
-
}
|
|
1549
|
-
let data;
|
|
1550
|
-
const changesPage = !KEEPS_REFS.has(p.action) || Boolean(p.url);
|
|
1551
|
-
try {
|
|
1552
|
-
switch (p.action) {
|
|
1553
|
-
case "start":
|
|
1554
|
-
case "open":
|
|
1555
|
-
if (p.url) {
|
|
1556
|
-
const refused = fenced(p.url, session.domainPolicy);
|
|
1557
|
-
if (refused)
|
|
1558
|
-
throw new BrowseToolError("domain_blocked", `${refused}. Close and start again to change the domains, or ask the user to change the profile's.`);
|
|
1559
|
-
data = { httpStatus: await navigate(page, p.url, pageTimeout, context.signal) };
|
|
1560
|
-
// A redirect the fence refuses ends on Chrome's error page instead of throwing.
|
|
1561
|
-
if (session.domainPolicy && (await page.url()).startsWith("chrome-error://")) {
|
|
1562
|
-
throw new BrowseToolError("domain_blocked", "The navigation ended on Chrome's error page; this browser's domain policy likely refused a redirect. Check status for the allowed and blocked domains.");
|
|
1563
|
-
}
|
|
1564
|
-
}
|
|
1565
|
-
break;
|
|
1566
|
-
case "back":
|
|
1567
|
-
case "forward":
|
|
1568
|
-
case "reload": {
|
|
1569
|
-
context.signal.throwIfAborted();
|
|
1570
|
-
const options = { waitUntil: "domcontentloaded", timeout: pageTimeout };
|
|
1571
|
-
const response = await (p.action === "back" ? page.goBack(options) : p.action === "forward" ? page.goForward(options) : page.reload(options));
|
|
1572
|
-
// Going back to the start page would hand the model a blank tab, or an extension URL.
|
|
1573
|
-
if (p.action === "back" && START_PAGE.test(await page.url())) {
|
|
1574
|
-
await page.goForward(options);
|
|
1575
|
-
throw new BrowseToolError("no_history", "This tab has no earlier page to go back to; it stays on the current page.");
|
|
1576
|
-
}
|
|
1577
|
-
data = { httpStatus: response?.status() };
|
|
1578
|
-
break;
|
|
1579
|
-
}
|
|
1580
|
-
case "wait":
|
|
1581
|
-
if (p.selector) {
|
|
1582
|
-
const target = await this.target(session, page, p.selector);
|
|
1583
|
-
context.signal.throwIfAborted();
|
|
1584
|
-
await page.waitForSelector(target, { state: p.state ?? "visible", timeout: pageTimeout });
|
|
1585
|
-
}
|
|
1586
|
-
else if (p.loadState)
|
|
1587
|
-
await page.waitForLoadState(p.loadState, pageTimeout);
|
|
1588
|
-
else
|
|
1589
|
-
await page.waitForTimeout(p.durationMs);
|
|
1590
|
-
break;
|
|
1591
|
-
}
|
|
1812
|
+
const page = await this.tab(session, p.tabId);
|
|
1813
|
+
if (p.action === "live_view") {
|
|
1814
|
+
const live = await session.client.sessions.debug(session.browser.sessionId, { signal: context.signal, timeout: 10_000, maxRetries: 0 });
|
|
1815
|
+
// A person may change anything in the page, so no earlier ref stays trustworthy.
|
|
1816
|
+
session.snapshots.clear();
|
|
1817
|
+
const liveViewUrl = live.pages.find(entry => entry.id === page.pageId)?.debuggerFullscreenUrl ?? live.debuggerFullscreenUrl;
|
|
1818
|
+
return { ...await this.output(p.action, session, page), liveViewUrl };
|
|
1592
1819
|
}
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1820
|
+
if (p.action === "ask") {
|
|
1821
|
+
const { result, view } = await this.ask(session, page, p, context);
|
|
1822
|
+
return this.output(p.action, session, page, result, view);
|
|
1596
1823
|
}
|
|
1597
|
-
|
|
1824
|
+
// Every other action ran above; what is left names its element by target.
|
|
1825
|
+
const jev = await this.locate(session, page, p, p.target, context);
|
|
1826
|
+
if (!jev.xpath)
|
|
1827
|
+
return { ...await this.output(p.action, session, page, { jev: jev.result }), code: jev.none ? "jev_none" : "jev_uncertain", isError: true };
|
|
1828
|
+
const output = await this.direct(session, { ...p, target: undefined, selector: jev.xpath }, context);
|
|
1829
|
+
return { ...output, data: { ...output.data, jev: jev.result } };
|
|
1598
1830
|
}
|
|
1599
1831
|
/**
|
|
1600
1832
|
* ask: Clairic reads values and a decision classifier (Clef unless askModel names another) answers bool and choice
|
|
@@ -1602,35 +1834,27 @@ export class BrowseSession {
|
|
|
1602
1834
|
* leave answers about a page that is gone, under the new page's URL and title, so a changed document (its timeOrigin)
|
|
1603
1835
|
* redoes the read once.
|
|
1604
1836
|
*/
|
|
1605
|
-
async ask(session, page,
|
|
1606
|
-
const
|
|
1607
|
-
const
|
|
1608
|
-
const decider = needs.decide ? this.classifier("ask", config) : undefined;
|
|
1609
|
-
if (visual && decider)
|
|
1610
|
-
this.visualAllowed(decider.spec, "askModel");
|
|
1611
|
-
const accountId = config.cloudflareAccountId?.trim(), apiKey = config.cloudflareApiKey?.trim();
|
|
1612
|
-
if (needs.extract && (!accountId || !apiKey))
|
|
1613
|
-
throw new BrowseToolError("ask_not_configured", "Configure CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID (Workers AI) to use ask, or take a snapshot and read the page.");
|
|
1614
|
-
const models = {
|
|
1615
|
-
...(accountId && apiKey ? { cloudflare: { accountId, apiKey } } : {}),
|
|
1616
|
-
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1617
|
-
};
|
|
1618
|
-
// A context destroyed mid-navigation reads as NaN, which never matches, so the read is redone.
|
|
1619
|
-
const document = () => page.evaluate("performance.timeOrigin").catch(() => NaN);
|
|
1837
|
+
async ask(session, page, p, context) {
|
|
1838
|
+
const fields = p.fields, visual = p.visual;
|
|
1839
|
+
const models = this.askModels(await this.purposeConfig(session, context, "ask"), fields, visual);
|
|
1620
1840
|
for (let attempt = 1;; attempt++) {
|
|
1621
|
-
|
|
1622
|
-
const
|
|
1841
|
+
// One request reads the document's identity, the tree, and the viewport; ask needs no XPaths.
|
|
1842
|
+
const read = await this.batch(session, p, context, readOperation, { refs: false, image: Boolean(visual) }, page);
|
|
1843
|
+
// A context destroyed mid-navigation has no origin to report, which never matches, so the read is redone.
|
|
1844
|
+
const before = read.origin;
|
|
1623
1845
|
let result;
|
|
1624
1846
|
try {
|
|
1625
|
-
result = await askPage({ ...models, ...(image ? { images: [image] } : {}) }, { url, title, tree:
|
|
1847
|
+
result = await askPage({ ...models, ...(read.image ? { images: [{ mimeType: "image/jpeg", data: read.image }] } : {}) }, { url: read.url, title: read.title, tree: read.tree }, fields, context.signal);
|
|
1626
1848
|
}
|
|
1627
1849
|
catch (error) {
|
|
1628
1850
|
if (context.signal.aborted)
|
|
1629
1851
|
throw error;
|
|
1630
1852
|
throw new BrowseToolError("ask_error", `${messageOf(error)} Take a snapshot and read the page instead.`);
|
|
1631
1853
|
}
|
|
1632
|
-
|
|
1633
|
-
|
|
1854
|
+
// The closing read doubles as the result's view of the tab.
|
|
1855
|
+
const view = await this.view(session, page);
|
|
1856
|
+
if (before !== null && view.origin === before)
|
|
1857
|
+
return { result, view };
|
|
1634
1858
|
if (attempt === 2)
|
|
1635
1859
|
throw new BrowseToolError("page_changed", "The page navigated while ask read it, twice. Wait for it to settle (wait with a selector on the expected page, or loadState networkidle), then ask again.");
|
|
1636
1860
|
}
|
|
@@ -1639,39 +1863,63 @@ export class BrowseSession {
|
|
|
1639
1863
|
* JEV mode: a classifier (Jev unless jevModel names another) picks the element for a plain-language target from a
|
|
1640
1864
|
* fresh snapshot; no xpath means it declined to act.
|
|
1641
1865
|
*/
|
|
1642
|
-
async locate(session, page,
|
|
1866
|
+
async locate(session, page, p, target, context) {
|
|
1867
|
+
const action = p.action, visual = p.visual;
|
|
1643
1868
|
const { spec, classify } = this.classifier("jev", await this.purposeConfig(session, context, "jev"));
|
|
1644
1869
|
const model = classifierName(spec);
|
|
1645
1870
|
if (visual)
|
|
1646
1871
|
this.visualAllowed(spec, "jevModel");
|
|
1647
|
-
|
|
1648
|
-
const
|
|
1872
|
+
// One request reads the tree, the XPaths a target can name, and the viewport.
|
|
1873
|
+
const read = await this.batch(session, p, context, readOperation, { refs: true, image: Boolean(visual) }, page);
|
|
1874
|
+
const refs = read.refs ?? {}, { url, title } = read;
|
|
1875
|
+
const image = read.image ? { mimeType: "image/jpeg", data: read.image } : undefined;
|
|
1876
|
+
const candidates = treeCandidates(read.tree).filter(c => refs[c.ref] && fitsAction(action, c, refs[c.ref]));
|
|
1649
1877
|
if (!candidates.length)
|
|
1650
1878
|
throw new BrowseToolError("jev_no_candidates", "The page has no elements this action can target. Take a snapshot to inspect it.");
|
|
1651
|
-
const
|
|
1652
|
-
|
|
1879
|
+
const pick = await this.pick(candidates, { url, title, action, request: target }, classify, image, context.signal);
|
|
1880
|
+
// Keep this snapshot so returned candidate selectors work without another snapshot.
|
|
1881
|
+
const version = `s${++this.snapshotNumber}`;
|
|
1882
|
+
session.snapshots.set(page.pageId, { version, url, refs });
|
|
1883
|
+
if (pick.chosen)
|
|
1884
|
+
return { xpath: refs[pick.chosen.ref], none: false, result: { model, label: pick.chosen.label, confidence: pick.confidence } };
|
|
1885
|
+
return { xpath: undefined, none: pick.none, result: this.declined(model, pick, ref => `@${version}:${ref}`) };
|
|
1886
|
+
}
|
|
1887
|
+
/** Jev's pick among the candidates; a failed request says whether retrying can help. */
|
|
1888
|
+
async pick(candidates, state, classify, image, signal) {
|
|
1653
1889
|
try {
|
|
1654
|
-
|
|
1890
|
+
return await pickTarget(candidates, state, jevChooser(classify, image && [image]), signal);
|
|
1655
1891
|
}
|
|
1656
1892
|
catch (error) {
|
|
1657
|
-
if (
|
|
1893
|
+
if (signal.aborted)
|
|
1658
1894
|
throw error;
|
|
1659
1895
|
const message = error instanceof Error ? error.message : "Jev request failed.";
|
|
1660
1896
|
// A refused key or empty balance fails every later target too.
|
|
1661
1897
|
throw new BrowseToolError(error instanceof ClassifierRefusal ? "jev_unavailable" : "jev_error", message);
|
|
1662
1898
|
}
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1899
|
+
}
|
|
1900
|
+
/** What a call reports when Jev declined to act: its best candidates, each with a selector the caller can use as is. */
|
|
1901
|
+
declined(model, pick, selector) {
|
|
1902
|
+
return {
|
|
1903
|
+
model, acted: false, match: pick.none ? "none" : "uncertain", confidence: pick.confidence, threshold: JEV_MIN_CONFIDENCE,
|
|
1904
|
+
candidates: pick.ranked.map(c => ({ selector: selector(c.ref), label: c.label, probability: c.probability })),
|
|
1905
|
+
hint: pick.none
|
|
1906
|
+
? "Jev found no listed element matching the target. Take a snapshot to check the page, or describe the element differently."
|
|
1907
|
+
: "Jev was not confident enough to act. Retry with one candidate selector, a more specific target, or a snapshot.",
|
|
1908
|
+
};
|
|
1909
|
+
}
|
|
1910
|
+
/** ask's models for a profile: Workers AI for the values Clairic reads, and the decision classifier for bool and choice. */
|
|
1911
|
+
askModels(config, fields, visual) {
|
|
1912
|
+
const needs = askNeeds(fields);
|
|
1913
|
+
const decider = needs.decide ? this.classifier("ask", config) : undefined;
|
|
1914
|
+
if (visual && decider)
|
|
1915
|
+
this.visualAllowed(decider.spec, "askModel");
|
|
1916
|
+
const accountId = config.cloudflareAccountId?.trim(), apiKey = config.cloudflareApiKey?.trim();
|
|
1917
|
+
if (needs.extract && (!accountId || !apiKey))
|
|
1918
|
+
throw new BrowseToolError("ask_not_configured", "Configure CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID (Workers AI) to use ask, or take a snapshot and read the page.");
|
|
1919
|
+
return {
|
|
1920
|
+
...(accountId && apiKey ? { cloudflare: { accountId, apiKey } } : {}),
|
|
1921
|
+
...(decider ? { decide: decider.classify, decideText: decider.spec.service === "workers-ai" ? DECIDE_TEXT[decider.spec.model] : undefined } : {}),
|
|
1922
|
+
};
|
|
1675
1923
|
}
|
|
1676
1924
|
async ai(p, context) {
|
|
1677
1925
|
const session = this.current();
|