@edlsh/browse-core 0.4.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- 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/page-operations.d.ts +91 -4
- package/dist/page-operations.js +270 -83
- package/dist/schema.d.ts +198 -1
- package/dist/schema.js +112 -17
- package/dist/session.d.ts +48 -7
- package/dist/session.js +313 -241
- package/package.json +3 -2
package/dist/schema.js
CHANGED
|
@@ -40,13 +40,14 @@ const askField = z.object({
|
|
|
40
40
|
if (field.unit !== undefined && field.type !== "duration")
|
|
41
41
|
ctx.addIssue({ code: "custom", path: ["unit"], message: "unit is only supported for duration" });
|
|
42
42
|
});
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
43
|
+
const ACTIONS = [
|
|
44
|
+
"start", "status", "close", "open", "back", "forward", "reload", "snapshot", "ask",
|
|
45
|
+
"click", "fill", "select", "press", "scroll", "wait", "screenshot", "evaluate",
|
|
46
|
+
"tabs", "tab_new", "tab_select", "tab_close", "live_view", "context_create", "cookie_profiles", "cookie_import",
|
|
47
|
+
"har_start", "har_stop",
|
|
48
|
+
];
|
|
49
|
+
/** Every action's arguments. A batch step reuses the direct controls' definitions from here instead of redefining them. */
|
|
50
|
+
const browserFields = {
|
|
50
51
|
backend: z.enum(["browserbase", "local"]).optional().describe("Only for start. Default local (or the profile's /browse backend setting); choose browserbase for clean-slate isolation, proxyCountry, a saved contextId, or at the user's request. Close before changing backends."),
|
|
51
52
|
cdpUrl: z.url({ protocol: /^(?:https?|wss?)$/ }).refine(value => {
|
|
52
53
|
if (!URL.canParse(value))
|
|
@@ -88,10 +89,78 @@ export const browserParameters = z.object({
|
|
|
88
89
|
fields: z.record(z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/), askField).optional().describe("Required for ask: 1 to 20 named questions about the selected page. text, number, date, datetime, and duration read a value (null when the page does not say); bool answers yes/no; choice picks one of options."),
|
|
89
90
|
path: z.string().regex(/^\/.*\.har$/, "path must be an absolute path ending in .har").optional().describe("Only for har_stop: absolute file path for the HAR, e.g. /abs/scratch/capture.har. Default: a new file in the system temp directory."),
|
|
90
91
|
timeoutMs: z.number().int().min(1).max(120_000).optional().describe("Operation deadline; default 30000 (a fixed wait gets durationMs + 5000). Page waits and navigation time out up to 2s earlier. On the deadline the browser is kept if it still responds."),
|
|
91
|
-
}
|
|
92
|
+
};
|
|
93
|
+
/** Direct controls a batch step may run. Every other action, including a nested batch, stays a separate call. */
|
|
94
|
+
const BATCH_ACTIONS = ["open", "back", "forward", "reload", "snapshot", "click", "fill", "select", "press", "scroll", "wait", "evaluate"];
|
|
95
|
+
/** A step has no arguments of its own: every field is the direct control's definition above, so it validates the same way. */
|
|
96
|
+
const batchStepFields = z.object({
|
|
97
|
+
action: z.enum(BATCH_ACTIONS, `A batch step must be one of ${BATCH_ACTIONS.join(", ")}; every other action, including a nested batch, is a separate call.`),
|
|
98
|
+
url: browserFields.url.describe("An http or https URL. Required for open."),
|
|
99
|
+
selector: browserFields.selector.describe("Snapshot reference such as @s1:0-24 (preferred), CSS, xpath=... or //..., or text=.... Required for click, fill, and select; for wait, the element to wait for."),
|
|
100
|
+
value: browserFields.value,
|
|
101
|
+
values: browserFields.values,
|
|
102
|
+
key: browserFields.key,
|
|
103
|
+
deltaX: browserFields.deltaX,
|
|
104
|
+
deltaY: browserFields.deltaY,
|
|
105
|
+
x: browserFields.x,
|
|
106
|
+
y: browserFields.y,
|
|
107
|
+
durationMs: browserFields.durationMs,
|
|
108
|
+
loadState: browserFields.loadState,
|
|
109
|
+
state: browserFields.state,
|
|
110
|
+
script: browserFields.script,
|
|
111
|
+
maxChars: browserFields.maxChars,
|
|
112
|
+
}, {
|
|
113
|
+
error: issue => issue.code === "unrecognized_keys"
|
|
114
|
+
? `A batch step does not accept ${issue.keys.join(", ")}. Set tabId and timeoutMs on the batch, address elements by selector (no JEV target), and give each step only its action's arguments.`
|
|
115
|
+
: undefined,
|
|
116
|
+
}).strict();
|
|
117
|
+
/** The arguments each batch action reads. A step carrying any other would see it silently ignored, so it is rejected. */
|
|
118
|
+
const STEP_ARGUMENTS = {
|
|
119
|
+
open: { url: true }, back: {}, forward: {}, reload: {}, snapshot: { maxChars: true },
|
|
120
|
+
click: { selector: true }, fill: { selector: true, value: true }, select: { selector: true, values: true },
|
|
121
|
+
press: { key: true }, scroll: { deltaX: true, deltaY: true, x: true, y: true },
|
|
122
|
+
wait: { durationMs: true, selector: true, loadState: true, state: true }, evaluate: { script: true },
|
|
123
|
+
};
|
|
124
|
+
/** Arguments a direct control cannot run without, for ordinary calls and batch steps alike. */
|
|
125
|
+
const DIRECT_REQUIRED = {
|
|
126
|
+
open: ["url"], fill: ["value"], select: ["values"], press: ["key"], evaluate: ["script"],
|
|
127
|
+
};
|
|
128
|
+
/** Rules a direct control follows whether it runs on its own or as a batch step. */
|
|
129
|
+
function checkDirectArguments(p, ctx) {
|
|
130
|
+
if (p.action === "wait" && [p.durationMs, p.selector, p.loadState].filter(v => v !== undefined).length !== 1) {
|
|
131
|
+
ctx.addIssue({ code: "custom", message: "wait requires exactly one of durationMs, selector, or loadState" });
|
|
132
|
+
}
|
|
133
|
+
if (p.action === "scroll" && p.deltaX === undefined && p.deltaY === undefined) {
|
|
134
|
+
ctx.addIssue({ code: "custom", message: "scroll requires deltaX or deltaY" });
|
|
135
|
+
}
|
|
136
|
+
if (p.key !== undefined && !keyTokens(p.key).every(token => [...token].length === 1 || KEY_NAMES.has(token.toLowerCase()))) {
|
|
137
|
+
ctx.addIssue({ code: "custom", path: ["key"], message: `Unsupported key "${p.key}". Use one character or one of: ${KEY_LIST}, optionally joined with modifiers (Control, Shift, Alt, Meta), e.g. Control+A.` });
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const batchStep = batchStepFields.superRefine((step, ctx) => {
|
|
141
|
+
const takes = STEP_ARGUMENTS[step.action];
|
|
142
|
+
for (const [field, value] of Object.entries(step)) {
|
|
143
|
+
if (field !== "action" && value !== undefined && !Object.hasOwn(takes, field)) {
|
|
144
|
+
ctx.addIssue({ code: "custom", path: [field], message: `${step.action} does not take ${field}; it takes ${Object.keys(takes).join(", ") || "no arguments"}` });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
for (const field of DIRECT_REQUIRED[step.action] ?? []) {
|
|
148
|
+
if (step[field] === undefined)
|
|
149
|
+
ctx.addIssue({ code: "custom", path: [field], message: `${field} is required for ${step.action}` });
|
|
150
|
+
}
|
|
151
|
+
if ((step.action === "click" || step.action === "fill" || step.action === "select") && step.selector === undefined) {
|
|
152
|
+
ctx.addIssue({ code: "custom", path: ["selector"], message: `selector is required for ${step.action}` });
|
|
153
|
+
}
|
|
154
|
+
if (step.action === "wait" && step.state !== undefined && step.selector === undefined) {
|
|
155
|
+
ctx.addIssue({ code: "custom", path: ["state"], message: "state only applies to a wait on a selector" });
|
|
156
|
+
}
|
|
157
|
+
checkDirectArguments(step, ctx);
|
|
158
|
+
});
|
|
159
|
+
const singleCall = z.object({ action: z.enum(ACTIONS), ...browserFields }).strict();
|
|
160
|
+
/** The rules of every action but batch. */
|
|
161
|
+
function checkCall(p, ctx) {
|
|
92
162
|
const required = {
|
|
93
|
-
|
|
94
|
-
select: ["values"], press: ["key"], evaluate: ["script"],
|
|
163
|
+
...DIRECT_REQUIRED, ask: ["fields"],
|
|
95
164
|
tab_select: ["tabId"], tab_close: ["tabId"], context_create: ["name"], cookie_import: ["domains"],
|
|
96
165
|
};
|
|
97
166
|
for (const field of required[p.action] ?? []) {
|
|
@@ -168,18 +237,44 @@ export const browserParameters = z.object({
|
|
|
168
237
|
if (p.browser !== undefined && p.action !== "cookie_import" && p.action !== "cookie_profiles") {
|
|
169
238
|
ctx.addIssue({ code: "custom", path: ["browser"], message: "browser is only supported for cookie_profiles and cookie_import" });
|
|
170
239
|
}
|
|
171
|
-
|
|
172
|
-
ctx.addIssue({ code: "custom", message: "wait requires exactly one of durationMs, selector, or loadState" });
|
|
173
|
-
}
|
|
240
|
+
checkDirectArguments(p, ctx);
|
|
174
241
|
// Without timeoutMs the deadline already extends past durationMs.
|
|
175
242
|
if (p.action === "wait" && p.durationMs !== undefined && p.timeoutMs !== undefined && p.durationMs >= p.timeoutMs) {
|
|
176
243
|
ctx.addIssue({ code: "custom", message: "durationMs must be shorter than timeoutMs; omit timeoutMs to let it follow durationMs" });
|
|
177
244
|
}
|
|
178
|
-
|
|
179
|
-
|
|
245
|
+
}
|
|
246
|
+
/** The browse tool's parameters without batch: what a host that has not adopted batch registers. */
|
|
247
|
+
export const browserParameters = singleCall.superRefine(checkCall);
|
|
248
|
+
/** The only arguments a batch itself takes; everything else belongs inside a step. */
|
|
249
|
+
const BATCH_ARGUMENTS = { action: true, steps: true, tabId: true, timeoutMs: true };
|
|
250
|
+
/**
|
|
251
|
+
* The browse tool's parameters with the batch action. A host opts in by registering this schema, since it owns the
|
|
252
|
+
* prompts and approval rules a batch needs: one call can navigate, act, and run page script.
|
|
253
|
+
*/
|
|
254
|
+
export const browserBatchParameters = z.object({
|
|
255
|
+
action: z.enum([...ACTIONS, "batch"]),
|
|
256
|
+
...browserFields,
|
|
257
|
+
steps: z.array(batchStep).min(1, "A batch needs at least one step").max(20, "A batch takes at most 20 steps; split a longer sequence into several batches").optional().describe("Only for batch: 1 to 20 steps run in order on one tab, in one request, with one timeoutMs for all of them. Use it when every step is already known and none needs an earlier result. Each step is an action (open, back, forward, reload, snapshot, click, fill, select, press, scroll, wait, evaluate) with only that action's arguments: no per-step tabId or timeoutMs (set them on the batch), no target, no nested batch. A batch whose first step is open starts a browser when none is running. The first failure stops the rest and nothing is rolled back. After a click, press, evaluate, navigation, or snapshot step, refs from before the batch stop working: use literal selectors, or end the batch with a snapshot."),
|
|
258
|
+
}).strict().superRefine((p, ctx) => {
|
|
259
|
+
if (p.action !== "batch") {
|
|
260
|
+
if (p.steps !== undefined)
|
|
261
|
+
ctx.addIssue({ code: "custom", path: ["steps"], message: "steps is only supported for batch" });
|
|
262
|
+
// SAFETY: with batch excluded, what is left is exactly a single call's shape.
|
|
263
|
+
checkCall(p, ctx);
|
|
264
|
+
return;
|
|
180
265
|
}
|
|
181
|
-
if (p.
|
|
182
|
-
ctx.addIssue({ code: "custom", path: ["
|
|
266
|
+
if (p.steps === undefined)
|
|
267
|
+
ctx.addIssue({ code: "custom", path: ["steps"], message: "steps is required for batch" });
|
|
268
|
+
for (const [field, value] of Object.entries(p)) {
|
|
269
|
+
if (value !== undefined && !Object.hasOwn(BATCH_ARGUMENTS, field)) {
|
|
270
|
+
ctx.addIssue({ code: "custom", path: [field], message: `${field} is not supported for batch, which takes only steps, tabId, and timeoutMs; put step arguments inside steps` });
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
// One deadline covers every step, so fixed waits must leave time for the rest; a lone fixed wait extends its own default instead.
|
|
274
|
+
const fixedWaitMs = (p.steps ?? []).reduce((total, step) => total + (step.action === "wait" ? step.durationMs ?? 0 : 0), 0);
|
|
275
|
+
const deadlineMs = p.timeoutMs ?? 30_000;
|
|
276
|
+
if (fixedWaitMs >= deadlineMs) {
|
|
277
|
+
ctx.addIssue({ code: "custom", path: ["steps"], message: `Fixed waits total ${fixedWaitMs} ms but the batch deadline is ${deadlineMs} ms; keep them shorter, or raise timeoutMs (maximum 120000)` });
|
|
183
278
|
}
|
|
184
279
|
});
|
|
185
280
|
export const aiParameters = z.object({
|
package/dist/session.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Stagehand } from "@browserbasehq/stagehand";
|
|
1
|
+
import type { Stagehand } from "@browserbasehq/stagehand";
|
|
2
2
|
import type { AIParams, BrowserParams } from "./schema.ts";
|
|
3
3
|
import { type CookieProvider } from "./browser-cookies.ts";
|
|
4
4
|
import { type HostClassify } from "./classifier.ts";
|
|
@@ -108,9 +108,25 @@ export interface ConfigurationContext {
|
|
|
108
108
|
}
|
|
109
109
|
export type ConfigResolver = (context: ConfigurationContext) => BrowseConfig | Promise<BrowseConfig>;
|
|
110
110
|
export declare function environmentConfig(): BrowseConfig;
|
|
111
|
+
/** How far a batch got. */
|
|
112
|
+
export interface BatchProgress {
|
|
113
|
+
total: number;
|
|
114
|
+
/** Steps confirmed to have completed; absent when a lost reply, deadline, or cancellation leaves that unknown. */
|
|
115
|
+
completed?: number;
|
|
116
|
+
/** Zero-based index of the step that stopped the batch. */
|
|
117
|
+
failedIndex?: number;
|
|
118
|
+
/** True when steps may have run without being confirmed: inspect the page before repeating anything. */
|
|
119
|
+
outcomeUnknown: boolean;
|
|
120
|
+
error?: {
|
|
121
|
+
code: string;
|
|
122
|
+
message: string;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
111
125
|
export declare class BrowseToolError extends Error {
|
|
112
126
|
readonly code: string;
|
|
113
|
-
|
|
127
|
+
readonly batch?: BatchProgress | undefined;
|
|
128
|
+
/** `batch` is set on a failed batch call. */
|
|
129
|
+
constructor(code: string, message: string, batch?: BatchProgress | undefined);
|
|
114
130
|
}
|
|
115
131
|
export interface BrowserOutput {
|
|
116
132
|
action: string;
|
|
@@ -136,6 +152,8 @@ export interface BrowserOutput {
|
|
|
136
152
|
note?: string;
|
|
137
153
|
/** False when the tab stopped answering right after the action, so its title is unknown. */
|
|
138
154
|
responsive?: false;
|
|
155
|
+
/** A batch's progress; `data.results` holds one result per completed step. */
|
|
156
|
+
batch?: BatchProgress;
|
|
139
157
|
}
|
|
140
158
|
export declare class BrowseSession {
|
|
141
159
|
private readonly resolveConfig;
|
|
@@ -144,6 +162,10 @@ export declare class BrowseSession {
|
|
|
144
162
|
private session?;
|
|
145
163
|
private queue;
|
|
146
164
|
private active?;
|
|
165
|
+
/** Asks the running batch to stop before its next step. */
|
|
166
|
+
private stopBatch?;
|
|
167
|
+
/** Whether the running batch may have reached the browser, so its steps may have run. */
|
|
168
|
+
private batchSent;
|
|
147
169
|
private snapshotNumber;
|
|
148
170
|
private generation;
|
|
149
171
|
private readonly contextReadyAt;
|
|
@@ -154,8 +176,8 @@ export declare class BrowseSession {
|
|
|
154
176
|
private readonly cookies;
|
|
155
177
|
/** This conversation's calls run in the broker that owns its shared browser, until close. */
|
|
156
178
|
private delegate?;
|
|
157
|
-
/** Stagehand's runtime extension, uploaded once
|
|
158
|
-
private
|
|
179
|
+
/** Stagehand's runtime extension per Browserbase project, uploaded once and reused across conversations and processes. */
|
|
180
|
+
private readonly extensions;
|
|
159
181
|
/** Default inference for every Stagehand instance; without it, unconfigured AI calls use Model Gateway's automatic selection. */
|
|
160
182
|
private readonly stagehandModel;
|
|
161
183
|
private readonly describeInference;
|
|
@@ -214,9 +236,11 @@ export declare class BrowseSession {
|
|
|
214
236
|
private classifier;
|
|
215
237
|
/** Refuses visual before any screenshot when the classifier is known to read text only. */
|
|
216
238
|
private visualAllowed;
|
|
217
|
-
/** The viewport as JPEG for a classifier: smaller than PNG, and every image-capable classifier takes it. */
|
|
218
|
-
private viewport;
|
|
219
239
|
private client;
|
|
240
|
+
/**
|
|
241
|
+
* The project's uploaded Stagehand extension: the one the cache file remembers, else a new upload. `fresh` uploads
|
|
242
|
+
* again after the project turned out to have lost the remembered one.
|
|
243
|
+
*/
|
|
220
244
|
private extensionId;
|
|
221
245
|
private current;
|
|
222
246
|
private start;
|
|
@@ -242,14 +266,31 @@ export declare class BrowseSession {
|
|
|
242
266
|
private harStart;
|
|
243
267
|
private closeOwned;
|
|
244
268
|
private page;
|
|
269
|
+
/**
|
|
270
|
+
* The tab a call acts on, named by its ID without asking the browser for its tabs: the batch executor finds the live tab
|
|
271
|
+
* itself and reports a closed one. Only a call with no selected tab lists them. In a shared browser, acting on a tab
|
|
272
|
+
* claims it before the request, so no other conversation can take it meanwhile.
|
|
273
|
+
*/
|
|
274
|
+
private tab;
|
|
275
|
+
private tabMissing;
|
|
245
276
|
/**
|
|
246
277
|
* Runs one operation beside the browser in a single round trip. Stagehand cannot cancel a running batch: on a deadline
|
|
247
278
|
* or cancellation the browser-side batch stops at its own timeout, and run() checks whether the browser still answers.
|
|
248
279
|
*/
|
|
249
280
|
private batch;
|
|
281
|
+
/** 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. */
|
|
282
|
+
private prepare;
|
|
283
|
+
/** Applies a completed action to the conversation's state (selected tab, snapshot refs) and returns what its result reports. */
|
|
284
|
+
private finish;
|
|
250
285
|
private direct;
|
|
286
|
+
/**
|
|
287
|
+
* batch: the steps run in order beside the browser in one request, under one deadline. The first failure stops the
|
|
288
|
+
* rest and nothing is rolled back; the result says how many steps completed.
|
|
289
|
+
*/
|
|
290
|
+
private sequence;
|
|
251
291
|
private reference;
|
|
252
|
-
|
|
292
|
+
/** 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. */
|
|
293
|
+
private view;
|
|
253
294
|
private output;
|
|
254
295
|
/** A cookie provider call, with its refusals as tool errors. */
|
|
255
296
|
private fromCookies;
|