@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/page-operations.js
CHANGED
|
@@ -1,85 +1,246 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Asks a running batch to stop before its next step. A request of its own, since the worker runs it while the batch waits
|
|
3
|
+
* on a step. Serialized into the worker: no outside dependencies.
|
|
4
|
+
*/
|
|
5
|
+
export async function cancelPageBatch(_context, input) {
|
|
6
|
+
// SAFETY: this worker global is created and read only by these two callbacks; page scripts have their own globals.
|
|
7
|
+
const batches = globalThis.__browseBatches ??= new Map();
|
|
8
|
+
const control = batches.get(input.id) ?? { cancelled: false };
|
|
9
|
+
control.cancelled = true;
|
|
10
|
+
batches.set(input.id, control);
|
|
11
|
+
// Kept in case the stop arrives before the batch starts; dropped if the batch never does.
|
|
12
|
+
setTimeout(() => { if (batches.get(input.id) === control)
|
|
13
|
+
batches.delete(input.id); }, input.ttlMs);
|
|
14
|
+
return true;
|
|
15
|
+
}
|
|
2
16
|
export async function pageOperation({ page, context }, input) {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
17
|
+
let batch;
|
|
18
|
+
if (!("steps" in input))
|
|
19
|
+
return execute(input);
|
|
20
|
+
// SAFETY: as in cancelPageBatch.
|
|
21
|
+
const batches = globalThis.__browseBatches ??= new Map();
|
|
22
|
+
const control = batches.get(input.id) ?? { cancelled: false };
|
|
23
|
+
batch = control;
|
|
24
|
+
batches.set(input.id, control);
|
|
25
|
+
const results = [];
|
|
26
|
+
const stop = (code, message, outcomeUnknown = false) => ({ results, failure: { index: results.length, code, message, outcomeUnknown } });
|
|
27
|
+
// Refs from before the batch name nodes of the page as it was: a step that can replace nodes ends their use.
|
|
28
|
+
let refsValid = true;
|
|
29
|
+
const expires = performance.now() + input.timeoutMs;
|
|
30
|
+
try {
|
|
31
|
+
for (const step of input.steps) {
|
|
32
|
+
const remaining = Math.ceil(expires - performance.now());
|
|
33
|
+
if (control.cancelled)
|
|
34
|
+
return stop("cancelled", "The batch was cancelled before this step.");
|
|
35
|
+
if (remaining <= 0)
|
|
36
|
+
return stop("timeout", "The batch's deadline passed before this step.");
|
|
37
|
+
if (step.reference && !refsValid)
|
|
38
|
+
return stop("stale_ref", "An earlier step in this batch ended the use of this snapshot reference. After a navigation, click, press, evaluate, or snapshot step, use a literal selector, or take a new snapshot and send the rest as another call.");
|
|
39
|
+
const result = await execute({ ...step, pageTimeoutMs: Math.min(step.pageTimeoutMs, Math.ceil(Math.max(remaining - 2_000, remaining / 2))), readTimeoutMs: Math.min(step.readTimeoutMs, remaining) });
|
|
40
|
+
if (result.error)
|
|
41
|
+
return stop(result.error.code, result.error.message);
|
|
42
|
+
results.push(result);
|
|
43
|
+
if (step.action !== "fill" && step.action !== "select" && step.action !== "scroll" && step.action !== "wait")
|
|
44
|
+
refsValid = false;
|
|
22
45
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
46
|
+
return { results };
|
|
47
|
+
}
|
|
48
|
+
catch (cause) {
|
|
49
|
+
return stop("browser_error", cause instanceof Error ? cause.message : String(cause), true);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
if (batches.get(input.id) === control)
|
|
53
|
+
batches.delete(input.id);
|
|
54
|
+
}
|
|
55
|
+
async function execute(input) {
|
|
56
|
+
const control = input.action === "click" || input.action === "fill" || input.action === "select";
|
|
57
|
+
const base = control ? page.locator(input.selector) : undefined;
|
|
58
|
+
const locator = input.nth === undefined ? base : base.nth(input.nth);
|
|
59
|
+
/** A tab's first history entry, before any page: about:blank, or Stagehand's own start page for tabs it opens. */
|
|
60
|
+
const startPage = /^(?:about:blank|chrome-extension:\/\/[a-p]{32}\/blank\.html)$/;
|
|
61
|
+
if (control || input.reference) {
|
|
62
|
+
// Independent reads can overlap. Observe rejections even when cardinality rejects the target first.
|
|
63
|
+
const settle = (work) => work.then(value => ({ ok: true, value }), (error) => ({ ok: false, error }));
|
|
64
|
+
const optionsRead = input.action === "select" ? settle(locator.innerHtml()) : undefined;
|
|
65
|
+
// Snapshot ref IDs name DOM nodes, so a fresh snapshot also detects an element replaced at the same XPath.
|
|
66
|
+
const [count, url, fresh] = await Promise.all([control ? base.count() : 0, page.url(), input.reference ? page.snapshot({ includeIframes: true }) : undefined]);
|
|
67
|
+
const found = count > (input.nth ?? 0);
|
|
68
|
+
const optionsResult = found && optionsRead ? await optionsRead : undefined;
|
|
69
|
+
if (optionsResult && !optionsResult.ok)
|
|
70
|
+
throw optionsResult.error;
|
|
71
|
+
const html = optionsResult?.ok ? optionsResult.value : undefined;
|
|
72
|
+
const failure = (code, message) => ({ tabId: page.pageId, url, error: { code, message } });
|
|
73
|
+
if (input.reference && (url !== input.reference.url || fresh.xpathMap[input.reference.id] !== input.reference.xpath)) {
|
|
74
|
+
return failure("stale_ref", url !== input.reference.url
|
|
75
|
+
? "The tab navigated since that snapshot. Take a new snapshot."
|
|
76
|
+
: "The referenced element changed or disappeared. Take a new snapshot.");
|
|
77
|
+
}
|
|
78
|
+
if (control && (input.nth === undefined ? count !== 1 : count <= input.nth)) {
|
|
79
|
+
return failure(count && input.nth === undefined ? "ambiguous_target" : "not_found", `The selector matched ${count} element(s)${input.nth === undefined ? "; it must match exactly one" : `; position ${input.nth + 1} does not exist`}. `
|
|
80
|
+
+ "Use a ref from a fresh snapshot, or (xpath)[n] for the nth match. Playwright-only syntax such as :has-text() or >> nth= is not supported.");
|
|
81
|
+
}
|
|
82
|
+
if (input.action === "select") {
|
|
83
|
+
// Keep the same value/label validation: the SDK otherwise deselects everything on a typo.
|
|
84
|
+
const entities = { amp: "&", lt: "<", gt: ">", quot: "\"", nbsp: "\u00a0" };
|
|
85
|
+
const decode = (text) => text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (entity, name) => {
|
|
86
|
+
if (/^#x/i.test(name))
|
|
87
|
+
return String.fromCodePoint(Number.parseInt(name.slice(2), 16));
|
|
88
|
+
if (name[0] === "#")
|
|
89
|
+
return String.fromCodePoint(Number(name.slice(1)));
|
|
90
|
+
return entities[name.toLowerCase()] ?? entity;
|
|
91
|
+
});
|
|
92
|
+
const options = [...html.matchAll(/<option\b([^>]*)>([\s\S]*?)<\/option>/gi)].map(([, attributes, inner]) => {
|
|
93
|
+
const attribute = (name) => {
|
|
94
|
+
const found = new RegExp(`\\s${name}="([^"]*)"`, "i").exec(attributes);
|
|
95
|
+
return found ? decode(found[1]) : undefined;
|
|
96
|
+
};
|
|
97
|
+
const text = decode(inner.replace(/<[^>]*>/g, "")).replace(/[ \t\n\f\r]+/g, " ").trim();
|
|
98
|
+
return { value: (attribute("value") ?? text).trim(), label: (attribute("label") || text).trim() };
|
|
99
|
+
});
|
|
100
|
+
if (!options.length)
|
|
101
|
+
return failure("not_select", "select works only on a native <select> element with options. For a custom dropdown, click it and then click the option.");
|
|
102
|
+
const missing = input.values.filter(value => !options.some(option => option.value === value.trim() || option.label === value.trim()));
|
|
103
|
+
if (missing.length)
|
|
104
|
+
return failure("option_not_found", `No option matches ${JSON.stringify(missing)}; nothing was selected. `
|
|
105
|
+
+ `Options (value/label): ${JSON.stringify(options.slice(0, 50).map(option => option.value === option.label ? option.value : `${option.value}/${option.label}`))}${options.length > 50 ? " …" : ""}`);
|
|
106
|
+
}
|
|
26
107
|
}
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
108
|
+
let value;
|
|
109
|
+
let snapshot;
|
|
110
|
+
let snapshotUrl;
|
|
111
|
+
let navigation;
|
|
112
|
+
let image;
|
|
113
|
+
const stopped = async (code, message) => ({ tabId: page.pageId, url: await page.url(), error: { code, message } });
|
|
114
|
+
// A stop can arrive while the reference was being checked, before anything changed.
|
|
115
|
+
if (batch?.cancelled)
|
|
116
|
+
return stopped("cancelled", "The batch was cancelled before this step acted.");
|
|
117
|
+
switch (input.action) {
|
|
118
|
+
case "start":
|
|
119
|
+
case "open": {
|
|
120
|
+
if (!input.url)
|
|
121
|
+
break;
|
|
122
|
+
// Stagehand's goto resolves without a response when the browser cancels the navigation, leaving the tab on its start
|
|
123
|
+
// page; Helium does this to a navigation made in about its first second after launch. One retry covers that.
|
|
124
|
+
const started = performance.now();
|
|
125
|
+
for (let attempt = 1;; attempt++) {
|
|
126
|
+
const response = await page.goto(input.url, { waitUntil: "domcontentloaded", timeout: Math.max(1, Math.ceil(input.pageTimeoutMs - (performance.now() - started))) });
|
|
127
|
+
if (response || !startPage.test(await page.url())) {
|
|
128
|
+
navigation = { httpStatus: response?.status() };
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
if (attempt === 2)
|
|
132
|
+
return stopped("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.");
|
|
133
|
+
}
|
|
134
|
+
// A redirect the fence refuses ends on Chrome's error page instead of throwing.
|
|
135
|
+
if (input.fenced && (await page.url()).startsWith("chrome-error://")) {
|
|
136
|
+
return stopped("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.");
|
|
137
|
+
}
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
case "back":
|
|
141
|
+
case "forward":
|
|
142
|
+
case "reload": {
|
|
143
|
+
const options = { waitUntil: "domcontentloaded", timeout: input.pageTimeoutMs };
|
|
144
|
+
const response = await (input.action === "back" ? page.goBack(options) : input.action === "forward" ? page.goForward(options) : page.reload(options));
|
|
145
|
+
// Going back to the start page would hand the model a blank tab, or an extension URL.
|
|
146
|
+
if (input.action === "back" && startPage.test(await page.url())) {
|
|
147
|
+
await page.goForward(options);
|
|
148
|
+
return stopped("no_history", "This tab has no earlier page to go back to; it stays on the current page.");
|
|
149
|
+
}
|
|
150
|
+
navigation = { httpStatus: response?.status() };
|
|
151
|
+
break;
|
|
152
|
+
}
|
|
153
|
+
case "wait":
|
|
154
|
+
if (input.selector)
|
|
155
|
+
await page.waitForSelector(input.selector, { state: input.state ?? "visible", timeout: input.pageTimeoutMs });
|
|
156
|
+
else if (input.loadState)
|
|
157
|
+
await page.waitForLoadState(input.loadState, input.pageTimeoutMs);
|
|
158
|
+
else
|
|
159
|
+
await page.waitForTimeout(input.durationMs);
|
|
160
|
+
break;
|
|
161
|
+
case "screenshot": {
|
|
162
|
+
const bytes = await page.screenshot({ type: "png", fullPage: input.fullPage ?? false, timeout: input.pageTimeoutMs });
|
|
163
|
+
let binary = "";
|
|
164
|
+
for (let at = 0; at < bytes.length; at += 0x8000)
|
|
165
|
+
binary += String.fromCharCode(...bytes.subarray(at, at + 0x8000));
|
|
166
|
+
image = btoa(binary);
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
case "snapshot": {
|
|
170
|
+
// A full result carries an XPath for every DOM node, over a megabyte on a large page: return only what is shown.
|
|
171
|
+
const [fresh, at] = await Promise.all([page.snapshot({ includeIframes: true }), page.url()]);
|
|
172
|
+
const { version, maxChars } = input.snapshot;
|
|
173
|
+
const full = fresh.formattedTree.replace(/\[(\d+-\d+)\]/g, `[${version}:$1]`);
|
|
174
|
+
const tree = full.slice(0, maxChars);
|
|
175
|
+
const refs = {};
|
|
176
|
+
for (const [, id] of tree.matchAll(/\[s\d+:(\d+-\d+)\]/g)) {
|
|
177
|
+
const xpath = fresh.xpathMap[id];
|
|
178
|
+
if (xpath)
|
|
179
|
+
refs[id] = xpath;
|
|
180
|
+
}
|
|
181
|
+
snapshot = { tree, truncated: full.length > maxChars, refs };
|
|
182
|
+
snapshotUrl = at;
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case "click":
|
|
186
|
+
await locator.click();
|
|
187
|
+
break;
|
|
188
|
+
case "fill":
|
|
189
|
+
await locator.fill(input.value);
|
|
190
|
+
break;
|
|
191
|
+
case "select": {
|
|
192
|
+
const selected = await locator.selectOption(input.values);
|
|
193
|
+
if (!selected.length)
|
|
194
|
+
return stopped("not_select", "select works only on a native <select> element. For a custom dropdown, click it and then click the option.");
|
|
195
|
+
value = selected;
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "press":
|
|
199
|
+
await page.keyPress(input.key);
|
|
200
|
+
break;
|
|
201
|
+
case "scroll":
|
|
202
|
+
await page.scroll(input.x ?? 640, input.y ?? 400, input.deltaX ?? 0, input.deltaY ?? 0);
|
|
203
|
+
break;
|
|
204
|
+
case "evaluate":
|
|
205
|
+
value = await page.evaluate(input.script);
|
|
206
|
+
break;
|
|
207
|
+
case "tab_select":
|
|
208
|
+
await context.setActivePage(page);
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
// Keep URL retrieval independent of the bounded main-thread read so blocked tabs remain reportable.
|
|
212
|
+
let timer;
|
|
213
|
+
try {
|
|
214
|
+
const [url, view] = await Promise.all([
|
|
215
|
+
page.url(),
|
|
216
|
+
Promise.race([
|
|
217
|
+
page.evaluate(`(() => {
|
|
218
|
+
const title = document.title;
|
|
219
|
+
let dialogs = [];
|
|
220
|
+
try { const answered = globalThis.__browserbaseDialogs?.splice(0); if (Array.isArray(answered)) dialogs = answered; } catch {}
|
|
221
|
+
return { title, dialogs };
|
|
222
|
+
})()`),
|
|
223
|
+
new Promise(resolve => { timer = setTimeout(() => resolve(undefined), input.readTimeoutMs); }),
|
|
224
|
+
]),
|
|
225
|
+
]);
|
|
226
|
+
return {
|
|
227
|
+
tabId: page.pageId, url, title: view?.title ?? null,
|
|
228
|
+
...(view === undefined ? { responsive: false } : {}),
|
|
229
|
+
...(view?.dialogs.length ? { dialogs: view.dialogs } : {}),
|
|
230
|
+
...(value === undefined ? {} : { value }), ...(snapshot ? { snapshot, snapshotUrl } : {}),
|
|
231
|
+
...(navigation ? { navigation } : {}), ...(image ? { image } : {}),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
clearTimeout(timer);
|
|
51
236
|
}
|
|
52
237
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
break;
|
|
60
|
-
case "click":
|
|
61
|
-
await locator.click();
|
|
62
|
-
break;
|
|
63
|
-
case "fill":
|
|
64
|
-
await locator.fill(input.value);
|
|
65
|
-
break;
|
|
66
|
-
case "select":
|
|
67
|
-
value = await locator.selectOption(input.values);
|
|
68
|
-
break;
|
|
69
|
-
case "press":
|
|
70
|
-
await page.keyPress(input.key);
|
|
71
|
-
break;
|
|
72
|
-
case "scroll":
|
|
73
|
-
await page.scroll(input.x ?? 640, input.y ?? 400, input.deltaX ?? 0, input.deltaY ?? 0);
|
|
74
|
-
break;
|
|
75
|
-
case "evaluate":
|
|
76
|
-
value = await page.evaluate(input.script);
|
|
77
|
-
break;
|
|
78
|
-
case "tab_select":
|
|
79
|
-
await context.setActivePage(page);
|
|
80
|
-
break;
|
|
81
|
-
}
|
|
82
|
-
// Keep URL retrieval independent of the bounded main-thread read so blocked tabs remain reportable.
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Reads a tab's URL, title, answered dialogs, and document identity in one request. The main-thread read is bounded, so
|
|
241
|
+
* a blocked tab is reported unresponsive instead of failing. Serialized into the worker: no outside dependencies.
|
|
242
|
+
*/
|
|
243
|
+
export async function viewOperation({ page }, input) {
|
|
83
244
|
let timer;
|
|
84
245
|
try {
|
|
85
246
|
const [url, view] = await Promise.all([
|
|
@@ -89,22 +250,48 @@ export async function pageOperation({ page, context }, input) {
|
|
|
89
250
|
const title = document.title;
|
|
90
251
|
let dialogs = [];
|
|
91
252
|
try { const answered = globalThis.__browserbaseDialogs?.splice(0); if (Array.isArray(answered)) dialogs = answered; } catch {}
|
|
92
|
-
return { title, dialogs };
|
|
93
|
-
})()`),
|
|
253
|
+
return { title, dialogs, origin: performance.timeOrigin };
|
|
254
|
+
})()`).catch(async () => ({ title: await page.title(), dialogs: [], origin: null })),
|
|
94
255
|
new Promise(resolve => { timer = setTimeout(() => resolve(undefined), input.readTimeoutMs); }),
|
|
95
256
|
]),
|
|
96
257
|
]);
|
|
97
258
|
return {
|
|
98
|
-
tabId: page.pageId, url, title: view?.title ?? null,
|
|
99
|
-
...(view === undefined ? { responsive: false } : {}),
|
|
100
|
-
...(view?.dialogs.length ? { dialogs: view.dialogs } : {}),
|
|
101
|
-
...(value === undefined ? {} : { value }), ...(snapshot ? { snapshot, snapshotUrl } : {}),
|
|
259
|
+
tabId: page.pageId, url, title: view?.title ?? null, origin: view?.origin ?? null,
|
|
260
|
+
...(view === undefined ? { responsive: false } : {}), ...(view?.dialogs.length ? { dialogs: view.dialogs } : {}),
|
|
102
261
|
};
|
|
103
262
|
}
|
|
104
263
|
finally {
|
|
105
264
|
clearTimeout(timer);
|
|
106
265
|
}
|
|
107
266
|
}
|
|
267
|
+
/**
|
|
268
|
+
* Reads a page for ask and JEV in one request: the snapshot tree, optionally the XPaths of the nodes a target can name
|
|
269
|
+
* and the viewport. Serialized into the worker: executable dependencies must stay inside this function.
|
|
270
|
+
*/
|
|
271
|
+
export async function readOperation({ page }, input) {
|
|
272
|
+
const [origin, fresh, url, title, shot] = await Promise.all([
|
|
273
|
+
page.evaluate("performance.timeOrigin").catch(() => null),
|
|
274
|
+
page.snapshot({ includeIframes: true }), page.url(), page.title(),
|
|
275
|
+
// JPEG: smaller than PNG, and every image-capable classifier takes it.
|
|
276
|
+
input.image ? page.screenshot({ type: "jpeg", quality: 70, fullPage: false, timeout: 10_000 }) : undefined,
|
|
277
|
+
]);
|
|
278
|
+
const read = { tabId: page.pageId, url, title, origin, tree: fresh.formattedTree };
|
|
279
|
+
if (input.refs) {
|
|
280
|
+
read.refs = {};
|
|
281
|
+
for (const [, id, role] of fresh.formattedTree.matchAll(/^\s*\[(\d+-\d+)\] ([^:\s]*)/gm)) {
|
|
282
|
+
const xpath = fresh.xpathMap[id];
|
|
283
|
+
if (xpath && role !== "StaticText" && role !== "InlineTextBox" && role !== "LineBreak")
|
|
284
|
+
read.refs[id] = xpath;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (shot) {
|
|
288
|
+
let binary = "";
|
|
289
|
+
for (let at = 0; at < shot.length; at += 0x8000)
|
|
290
|
+
binary += String.fromCharCode(...shot.subarray(at, at + 0x8000));
|
|
291
|
+
read.image = btoa(binary);
|
|
292
|
+
}
|
|
293
|
+
return read;
|
|
294
|
+
}
|
|
108
295
|
/** Context-only reads share one transport request; keep the same bounded title behavior for blocked tabs. */
|
|
109
296
|
export async function tabsOperation({ context }, input) {
|
|
110
297
|
return Promise.all((await context.pages()).map(async (page) => {
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { RealBrowserPage } from "./real-browser-session.ts";
|
|
2
|
+
import { type ClientGenerate } from "./session.ts";
|
|
3
|
+
/** One thing to do to one element, in the shape Stagehand's observe returns: `selector` is a snapshot ref. */
|
|
4
|
+
export interface PageAction {
|
|
5
|
+
selector: string;
|
|
6
|
+
description: string;
|
|
7
|
+
method: "click" | "fill" | "select" | "press";
|
|
8
|
+
arguments: string[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The elements an instruction is about, each with the action that would carry it out. `single` asks for the one next
|
|
12
|
+
* action, for act. A ref the outline does not have is the model's invention and is dropped.
|
|
13
|
+
*/
|
|
14
|
+
export declare function observePage(generate: ClientGenerate, page: RealBrowserPage, instruction: string, single: boolean): Promise<PageAction[]>;
|
|
15
|
+
/** What the page says in answer to an instruction, as JSON matching `schema`; without one, as `{ extraction }`. */
|
|
16
|
+
export declare function extractPage(generate: ClientGenerate, page: RealBrowserPage, instruction: string, schema: Record<string, unknown> | undefined): Promise<unknown>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { MAX_TEXT } from "./ask.js";
|
|
2
|
+
import { BrowseToolError } from "./session.js";
|
|
3
|
+
const ACTIONS_SCHEMA = {
|
|
4
|
+
type: "object", additionalProperties: false, required: ["elements"],
|
|
5
|
+
properties: {
|
|
6
|
+
elements: {
|
|
7
|
+
type: "array",
|
|
8
|
+
items: {
|
|
9
|
+
type: "object", additionalProperties: false, required: ["ref", "description", "method", "arguments"],
|
|
10
|
+
properties: {
|
|
11
|
+
ref: { type: "string", description: "The element's ref from the outline, e.g. e12." },
|
|
12
|
+
description: { type: "string", description: "What the element is, in a few words." },
|
|
13
|
+
method: { type: "string", enum: ["click", "fill", "select", "press"] },
|
|
14
|
+
arguments: { type: "array", items: { type: "string" }, description: "fill: the text. select: the option labels or values. press: the key. click: none." },
|
|
15
|
+
},
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
const OUTLINE = "The page is an outline with one element per line, as `- role \"name\" [ref=e12 states]`, indented under its container. Only an element with a ref can be acted on.";
|
|
21
|
+
/** One single-turn request for JSON matching `schema`; the host's model answers it. */
|
|
22
|
+
async function generateJson(generate, systemPrompt, text, schema) {
|
|
23
|
+
// SAFETY: a single user turn of text with a JSON Schema response format is one of the requests ClientGenerate takes;
|
|
24
|
+
// its parameter type is Stagehand's whole model-call union, which this literal does not spell out.
|
|
25
|
+
const reply = await generate({ systemPrompt, messages: [{ role: "user", content: { type: "text", text } }], responseFormat: { type: "json_schema", schema }, temperature: 0 });
|
|
26
|
+
if (reply.outputFormat !== "json_schema")
|
|
27
|
+
throw new BrowseToolError("ai_error", "The model answered in prose where JSON was asked for.");
|
|
28
|
+
return reply.structuredContent;
|
|
29
|
+
}
|
|
30
|
+
function describe(page, instruction) {
|
|
31
|
+
return `Instruction: ${instruction}\nPage title: ${page.title ?? ""}\nURL: ${page.url}`;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The elements an instruction is about, each with the action that would carry it out. `single` asks for the one next
|
|
35
|
+
* action, for act. A ref the outline does not have is the model's invention and is dropped.
|
|
36
|
+
*/
|
|
37
|
+
export async function observePage(generate, page, instruction, single) {
|
|
38
|
+
const task = single
|
|
39
|
+
? "Return the one next action that carries out the instruction, or no elements when the page offers none."
|
|
40
|
+
: "Return every element the instruction is about, each with the action a person would take on it.";
|
|
41
|
+
const reply = await generateJson(generate, `You choose elements on a web page for a browser agent. ${OUTLINE} ${task} Answer with JSON only.`, `${describe(page, instruction)}\n\nOutline:\n${page.outline}`, ACTIONS_SCHEMA);
|
|
42
|
+
const refs = new Set(page.outline.match(/\bref=e\d+/g)?.map(ref => ref.slice(4)));
|
|
43
|
+
return (reply.elements ?? []).flatMap(({ ref, description, method, arguments: args }) => {
|
|
44
|
+
if (typeof ref !== "string" || !refs.has(ref) || (method !== "click" && method !== "fill" && method !== "select" && method !== "press"))
|
|
45
|
+
return [];
|
|
46
|
+
return [{ selector: ref, description: String(description ?? ""), method, arguments: Array.isArray(args) ? args.map(String) : [] }];
|
|
47
|
+
}).slice(0, single ? 1 : undefined);
|
|
48
|
+
}
|
|
49
|
+
/** What the page says in answer to an instruction, as JSON matching `schema`; without one, as `{ extraction }`. */
|
|
50
|
+
export async function extractPage(generate, page, instruction, schema) {
|
|
51
|
+
// The text says what the page shows; the outline adds what its controls hold and whether they are checked.
|
|
52
|
+
const controls = page.outline.replace(/ \[ref=e\d+\]/g, "").replace(/\[ref=e\d+ /g, "[");
|
|
53
|
+
return generateJson(generate, "You extract information from a web page for a browser agent. Use only what the page says, and null for what it does not say. Answer with JSON only.", `${describe(page, instruction)}\n\nPage text:\n${page.text.slice(0, MAX_TEXT)}\n\nControls:\n${controls}`, schema ?? { type: "object", additionalProperties: false, required: ["extraction"], properties: { extraction: { type: "string" } } });
|
|
54
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface RealBrowserImage {
|
|
2
|
+
data: string;
|
|
3
|
+
mimeType: string;
|
|
4
|
+
}
|
|
5
|
+
/** A tool's result: its text blocks joined, and the images it carried (a screenshot). */
|
|
6
|
+
export interface RealBrowserResult {
|
|
7
|
+
text: string;
|
|
8
|
+
images: RealBrowserImage[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* One `browse mcp` process, started on the first call and again on the call after it exits. Every conversation in the
|
|
12
|
+
* host process shares it: OpenCode Browse keeps the tabs, so nothing about a conversation lives here.
|
|
13
|
+
*/
|
|
14
|
+
export declare class RealBrowserClient {
|
|
15
|
+
private readonly command;
|
|
16
|
+
private readonly client;
|
|
17
|
+
private child?;
|
|
18
|
+
private ready?;
|
|
19
|
+
private readonly pending;
|
|
20
|
+
private nextId;
|
|
21
|
+
private stderr;
|
|
22
|
+
/** `command` is the argv that runs `browse mcp`, on this machine or over SSH on the machine with the browser. */
|
|
23
|
+
constructor(command: readonly string[], client: {
|
|
24
|
+
name: string;
|
|
25
|
+
version: string;
|
|
26
|
+
});
|
|
27
|
+
/** Runs one of OpenCode Browse's tools. A tool's own failure (a refused navigation, a script error) keeps its text. */
|
|
28
|
+
call(tool: "execute" | "tabs" | "status", args: Record<string, unknown>, signal: AbortSignal): Promise<RealBrowserResult>;
|
|
29
|
+
/** Ends the process. OpenCode Browse keeps the tabs agents opened, so closing them is the session's job. */
|
|
30
|
+
close(): void;
|
|
31
|
+
private unreachable;
|
|
32
|
+
private start;
|
|
33
|
+
private send;
|
|
34
|
+
private request;
|
|
35
|
+
private receive;
|
|
36
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// The user's real browser, driven through OpenCode Browse: its MCP server (`browse mcp`) and its browser extension.
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { BrowseToolError } from "./session.js";
|
|
5
|
+
/** The newest MCP revision this client speaks; the server answers with the one it chose. */
|
|
6
|
+
const MCP_PROTOCOL = "2025-06-18";
|
|
7
|
+
/** A server silent this long is not coming: an SSH hop to a sleeping machine, or a command that waits for input. */
|
|
8
|
+
const CONNECT_TIMEOUT_MS = 20_000;
|
|
9
|
+
/**
|
|
10
|
+
* One `browse mcp` process, started on the first call and again on the call after it exits. Every conversation in the
|
|
11
|
+
* host process shares it: OpenCode Browse keeps the tabs, so nothing about a conversation lives here.
|
|
12
|
+
*/
|
|
13
|
+
export class RealBrowserClient {
|
|
14
|
+
command;
|
|
15
|
+
client;
|
|
16
|
+
child;
|
|
17
|
+
ready;
|
|
18
|
+
pending = new Map();
|
|
19
|
+
nextId = 0;
|
|
20
|
+
stderr = "";
|
|
21
|
+
/** `command` is the argv that runs `browse mcp`, on this machine or over SSH on the machine with the browser. */
|
|
22
|
+
constructor(command, client) {
|
|
23
|
+
this.command = command;
|
|
24
|
+
this.client = client;
|
|
25
|
+
}
|
|
26
|
+
/** Runs one of OpenCode Browse's tools. A tool's own failure (a refused navigation, a script error) keeps its text. */
|
|
27
|
+
async call(tool, args, signal) {
|
|
28
|
+
signal.throwIfAborted();
|
|
29
|
+
await (this.ready ??= this.start().catch(error => { this.ready = undefined; throw error; }));
|
|
30
|
+
const result = await this.request("tools/call", { name: tool, arguments: args }, signal);
|
|
31
|
+
const blocks = result.content ?? [];
|
|
32
|
+
const text = blocks.flatMap(block => block.type === "text" ? [block.text] : []).join("\n");
|
|
33
|
+
if (result.isError)
|
|
34
|
+
throw new BrowseToolError("real_browser_error", text || `OpenCode Browse's ${tool} failed without a message.`);
|
|
35
|
+
return { text, images: blocks.flatMap(block => block.type === "image" ? [{ data: block.data, mimeType: block.mimeType }] : []) };
|
|
36
|
+
}
|
|
37
|
+
/** Ends the process. OpenCode Browse keeps the tabs agents opened, so closing them is the session's job. */
|
|
38
|
+
close() {
|
|
39
|
+
this.child?.kill();
|
|
40
|
+
}
|
|
41
|
+
unreachable(why) {
|
|
42
|
+
const said = this.stderr.trim().replace(/\s+/g, " ").slice(-300);
|
|
43
|
+
return new BrowseToolError("real_browser_unreachable", `OpenCode Browse (${this.command[0]}) ${why}.${said ? ` It said: ${said}.` : ""} `
|
|
44
|
+
+ "Check that the machine with the browser is awake and that `browse status` there reports a connected extension.");
|
|
45
|
+
}
|
|
46
|
+
async start() {
|
|
47
|
+
const [file, ...args] = this.command;
|
|
48
|
+
if (!file)
|
|
49
|
+
throw new BrowseToolError("real_browser_config", "The real browser's command is empty; set it to the argv that runs `browse mcp`.");
|
|
50
|
+
this.stderr = "";
|
|
51
|
+
const child = spawn(file, args, { stdio: ["pipe", "pipe", "pipe"] });
|
|
52
|
+
this.child = child;
|
|
53
|
+
const gone = (why) => {
|
|
54
|
+
if (this.child !== child)
|
|
55
|
+
return;
|
|
56
|
+
this.child = undefined;
|
|
57
|
+
this.ready = undefined;
|
|
58
|
+
const error = this.unreachable(why);
|
|
59
|
+
for (const call of this.pending.values())
|
|
60
|
+
call.reject(error);
|
|
61
|
+
this.pending.clear();
|
|
62
|
+
};
|
|
63
|
+
child.on("error", error => gone(`could not start: ${error.message}`));
|
|
64
|
+
child.on("exit", code => gone(code === null ? "was stopped" : `exited with code ${code}`));
|
|
65
|
+
// A write to a process that just exited fails here; the exit handler already told every caller.
|
|
66
|
+
child.stdin.on("error", () => undefined);
|
|
67
|
+
child.stderr.on("data", chunk => { this.stderr = (this.stderr + String(chunk)).slice(-2000); });
|
|
68
|
+
createInterface({ input: child.stdout }).on("line", line => this.receive(child, line));
|
|
69
|
+
try {
|
|
70
|
+
await this.request("initialize", { protocolVersion: MCP_PROTOCOL, capabilities: {}, clientInfo: this.client }, AbortSignal.timeout(CONNECT_TIMEOUT_MS));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
child.kill();
|
|
74
|
+
throw error instanceof BrowseToolError ? error : this.unreachable(`did not answer within ${CONNECT_TIMEOUT_MS / 1000} s`);
|
|
75
|
+
}
|
|
76
|
+
this.send(child, { jsonrpc: "2.0", method: "notifications/initialized" });
|
|
77
|
+
}
|
|
78
|
+
send(child, message) {
|
|
79
|
+
child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
80
|
+
}
|
|
81
|
+
request(method, params, signal) {
|
|
82
|
+
const child = this.child;
|
|
83
|
+
if (!child)
|
|
84
|
+
return Promise.reject(this.unreachable("is not running"));
|
|
85
|
+
const id = ++this.nextId;
|
|
86
|
+
return new Promise((resolve, reject) => {
|
|
87
|
+
const abort = () => {
|
|
88
|
+
this.pending.delete(id);
|
|
89
|
+
this.send(child, { jsonrpc: "2.0", method: "notifications/cancelled", params: { requestId: id } });
|
|
90
|
+
reject(signal.reason);
|
|
91
|
+
};
|
|
92
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
93
|
+
this.pending.set(id, {
|
|
94
|
+
resolve: value => { signal.removeEventListener("abort", abort); resolve(value); },
|
|
95
|
+
reject: error => { signal.removeEventListener("abort", abort); reject(error); },
|
|
96
|
+
});
|
|
97
|
+
this.send(child, { jsonrpc: "2.0", id, method, params });
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
receive(child, line) {
|
|
101
|
+
let message;
|
|
102
|
+
// A wrapper such as SSH may print a banner on stdout before the server speaks.
|
|
103
|
+
try {
|
|
104
|
+
message = JSON.parse(line);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (message.method !== undefined) {
|
|
110
|
+
// The server may ask for a ping; it gets nothing else from this client.
|
|
111
|
+
if (message.id !== undefined) {
|
|
112
|
+
this.send(child, message.method === "ping"
|
|
113
|
+
? { jsonrpc: "2.0", id: message.id, result: {} }
|
|
114
|
+
: { jsonrpc: "2.0", id: message.id, error: { code: -32601, message: `${message.method} is not supported` } });
|
|
115
|
+
}
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const call = message.id === undefined ? undefined : this.pending.get(message.id);
|
|
119
|
+
if (!call)
|
|
120
|
+
return;
|
|
121
|
+
this.pending.delete(message.id);
|
|
122
|
+
if (message.error)
|
|
123
|
+
call.reject(new BrowseToolError("real_browser_error", `OpenCode Browse refused the request: ${message.error.message ?? "no message"}`));
|
|
124
|
+
else
|
|
125
|
+
call.resolve(message.result);
|
|
126
|
+
}
|
|
127
|
+
}
|