@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.301
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/CHANGELOG.md +239 -0
- package/NOTICE +39 -4
- package/README.md +125 -236
- package/dist/core/contract.d.ts +17 -5
- package/dist/core/contract.js +36 -33
- package/dist/core/custody.d.ts +19 -2
- package/dist/core/custody.js +28 -6
- package/dist/core/downloads.d.ts +44 -3
- package/dist/core/downloads.js +94 -58
- package/dist/core/driving-guard.d.ts +20 -0
- package/dist/core/driving-guard.js +190 -23
- package/dist/core/driving.d.ts +56 -2
- package/dist/core/driving.js +189 -10
- package/dist/core/effects.d.ts +80 -6
- package/dist/core/effects.js +374 -41
- package/dist/core/evidence.d.ts +1 -1
- package/dist/core/failures.d.ts +15 -1
- package/dist/core/failures.js +7 -0
- package/dist/core/files.d.ts +20 -2
- package/dist/core/files.js +161 -10
- package/dist/core/host.d.ts +29 -77
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/lease.d.ts +2 -1
- package/dist/core/page-scan.d.ts +81 -2
- package/dist/core/page-scan.js +487 -13
- package/dist/core/public-fetch.d.ts +70 -9
- package/dist/core/public-fetch.js +348 -51
- package/dist/core/read-page-worker.js +5 -4
- package/dist/core/read-page.d.ts +23 -8
- package/dist/core/read-page.js +64 -20
- package/dist/core/redact.d.ts +0 -2
- package/dist/core/redact.js +0 -32
- package/dist/core/session-control.d.ts +0 -2
- package/dist/core/session-control.js +0 -5
- package/dist/core/tools.d.ts +46 -1
- package/dist/core/tools.js +88 -12
- package/dist/core/usage.d.ts +4 -3
- package/dist/core/usage.js +5 -4
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/core/web.d.ts +2 -111
- package/dist/core/web.js +0 -443
- package/dist/driver/cdp.d.ts +6 -0
- package/dist/driver/cdp.js +245 -0
- package/dist/driver/page-driver.js +110 -7
- package/dist/driver/sealed.d.ts +4 -12
- package/dist/driver/sealed.js +23 -37
- package/dist/driver/stagehand.d.ts +12 -15
- package/dist/driver/stagehand.js +21 -17
- package/dist/durable/result.d.ts +1 -2
- package/dist/durable/result.js +2 -2
- package/dist/durable/store.d.ts +17 -3
- package/dist/durable/store.js +231 -64
- package/dist/durable.d.ts +50 -17
- package/dist/durable.js +107 -106
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -3
- package/dist/live-view/index.d.ts +4 -1
- package/dist/live-view/index.js +5 -0
- package/dist/live-view/protocol.d.ts +39 -7
- package/dist/live-view/protocol.js +2 -0
- package/dist/live-view/provider.d.ts +2 -2
- package/dist/live-view/provider.js +2 -2
- package/dist/live-view/server.d.ts +55 -2
- package/dist/live-view/server.js +282 -35
- package/dist/live-view/stream.js +16 -3
- package/dist/live-view/viewer.js +106 -13
- package/dist/providers/cdp.d.ts +0 -1
- package/dist/providers/cdp.js +35 -13
- package/dist/providers/chrome-args.d.ts +3 -0
- package/dist/providers/chrome-args.js +13 -2
- package/dist/providers/profiles.d.ts +1 -15
- package/dist/providers/profiles.js +1 -64
- package/dist/providers/shared.d.ts +1 -47
- package/dist/providers/shared.js +1 -82
- package/dist/providers/worker-extension.d.ts +20 -1
- package/dist/providers/worker-extension.js +86 -7
- package/dist/testing/backend.d.ts +6 -24
- package/dist/testing/backend.js +7 -30
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
- package/dist/vendor/browser-use-pi/ax.js +642 -0
- package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
- package/dist/vendor/browser-use-pi/cdp.js +106 -0
- package/dist/vendor/browser-use-pi/page.d.ts +29 -0
- package/dist/vendor/browser-use-pi/page.js +99 -0
- package/package.json +15 -46
- package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
- package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
- package/dist/coding-agent-local.d.ts +0 -12
- package/dist/coding-agent-local.js +0 -72
- package/dist/coding-agent.d.ts +0 -134
- package/dist/coding-agent.js +0 -640
- package/dist/core/sites.d.ts +0 -33
- package/dist/core/sites.js +0 -104
- package/dist/driver/extension-worker.d.ts +0 -9
- package/dist/driver/extension-worker.js +0 -185
- package/dist/durable/web.d.ts +0 -47
- package/dist/durable/web.js +0 -41
- package/dist/providers/assigned.d.ts +0 -18
- package/dist/providers/assigned.js +0 -75
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -169
- package/dist/providers/browserbase.js +0 -319
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- package/dist/recorder/credential.d.ts +0 -9
- package/dist/recorder/credential.js +0 -49
- package/dist/recorder/follow.d.ts +0 -36
- package/dist/recorder/follow.js +0 -163
- package/dist/recorder/frames.d.ts +0 -87
- package/dist/recorder/frames.js +0 -377
- package/dist/recorder/index.d.ts +0 -4
- package/dist/recorder/index.js +0 -7
- package/dist/recorder/jpeg.d.ts +0 -8
- package/dist/recorder/jpeg.js +0 -70
- package/dist/recorder/track.d.ts +0 -107
- package/dist/recorder/track.js +0 -280
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
- package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { refusedError } from "../core/custody.js";
|
|
2
|
+
import { openDial } from "../core/dial.js";
|
|
3
|
+
import { AxHelpers, UnknownIdError } from "../vendor/browser-use-pi/ax.js";
|
|
4
|
+
import { CDP, CDPConnectionClosedError } from "../vendor/browser-use-pi/cdp.js";
|
|
5
|
+
import { Page } from "../vendor/browser-use-pi/page.js";
|
|
6
|
+
import { NAVIGATED_SNAPSHOT_ERROR, NO_HYDRATED_SNAPSHOT_ERROR, STALE_SNAPSHOT_ID_ERROR } from "../core/failures.js";
|
|
7
|
+
/** The package's stale-snapshot words, as the Stagehand driver says them: plain errors, so a failure reads them as a stale snapshot. */
|
|
8
|
+
const stale = (message) => new Error(message);
|
|
9
|
+
const staleSnapshotIdError = (id) => STALE_SNAPSHOT_ID_ERROR.replace("${id}", id);
|
|
10
|
+
/** What `run` with code is told on this browser. */
|
|
11
|
+
export const CDP_CODE_REFUSED = 'run code is not available on this browser (the agent\'s browser computer): send actions instead, each an op with a snapshot id and a value, for example {"actions":[{"op":"click","id":"0-42"}]}, and navigate with {"actions":[{"op":"goto","url":"https://example.com"}]}. Read the page with browser_read.';
|
|
12
|
+
/** How long one CDP command may take before the action is said to be unanswered. */
|
|
13
|
+
const COMMAND_MS = 30_000;
|
|
14
|
+
/**
|
|
15
|
+
* One element's box once it is scrolled into view, in CSS pixels from the top page's viewport corner, or how many a
|
|
16
|
+
* selector matches. An element in a same-origin iframe (an id from the snapshot) gets each enclosing frame's
|
|
17
|
+
* content-box offset added, and the viewport is the top page's, as the screenshot's clip is.
|
|
18
|
+
*/
|
|
19
|
+
const LOCATE_JS = `function(selector){
|
|
20
|
+
let top = (this && this.ownerDocument ? this.ownerDocument : document).defaultView;
|
|
21
|
+
while (top.frameElement) top = top.parent;
|
|
22
|
+
const viewport = { width: top.innerWidth, height: top.innerHeight };
|
|
23
|
+
const found = selector === null ? null : selector === undefined ? this : document.querySelectorAll(selector);
|
|
24
|
+
if (found === null) return { viewport };
|
|
25
|
+
const list = found instanceof NodeList ? [...found] : [found.nodeType === 1 ? found : found.parentElement];
|
|
26
|
+
if (list.length !== 1 || !list[0]) return { viewport, matches: list.filter(Boolean).length };
|
|
27
|
+
list[0].scrollIntoView({ block: 'center', inline: 'center' });
|
|
28
|
+
const r = list[0].getBoundingClientRect();
|
|
29
|
+
let x = r.x, y = r.y;
|
|
30
|
+
for (let w = list[0].ownerDocument.defaultView; w && w.frameElement; w = w.parent) {
|
|
31
|
+
const f = w.frameElement, fr = f.getBoundingClientRect(), cs = getComputedStyle(f);
|
|
32
|
+
x += fr.x + f.clientLeft + parseFloat(cs.paddingLeft);
|
|
33
|
+
y += fr.y + f.clientTop + parseFloat(cs.paddingTop);
|
|
34
|
+
}
|
|
35
|
+
return { viewport, matches: 1, box: { x, y, width: r.width, height: r.height } };
|
|
36
|
+
}`;
|
|
37
|
+
/** The browser's tabs, in the browser's order (DevTools' own pages left out). */
|
|
38
|
+
async function tabsOf(cdp) {
|
|
39
|
+
const { targetInfos } = await cdp.send("Target.getTargets");
|
|
40
|
+
return targetInfos.filter((t) => t.type === "page" && !t.url.startsWith("devtools://"));
|
|
41
|
+
}
|
|
42
|
+
/** A blank tab opened for the driver, when the browser has none. */
|
|
43
|
+
async function blankTab(cdp) {
|
|
44
|
+
return (await cdp.send("Target.createTarget", { url: "about:blank" })).targetId;
|
|
45
|
+
}
|
|
46
|
+
/** The raw-CDP page driver: snapshot ids and actions only. */
|
|
47
|
+
export function cdpDriver() {
|
|
48
|
+
return async (target, signal) => {
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
const cdp = await CDP.open(openDial(target), COMMAND_MS);
|
|
51
|
+
let page;
|
|
52
|
+
/** Every tab the driver has seen, so one that appears later is known as new. */
|
|
53
|
+
const seen = new Set();
|
|
54
|
+
/** The tab that opened each tab the driver followed, to go back to when that one closes. */
|
|
55
|
+
const openers = new Map();
|
|
56
|
+
/** Whether the last run moved to another tab (movedTab). */
|
|
57
|
+
let movedTab = false;
|
|
58
|
+
try {
|
|
59
|
+
const tabs = await tabsOf(cdp);
|
|
60
|
+
for (const t of tabs)
|
|
61
|
+
seen.add(t.targetId);
|
|
62
|
+
// The browser's first tab, or a blank one opened for the driver when it has none.
|
|
63
|
+
page = await Page.attach(cdp, tabs[0]?.targetId ?? (await blankTab(cdp)));
|
|
64
|
+
seen.add(page.targetId);
|
|
65
|
+
}
|
|
66
|
+
catch (error) {
|
|
67
|
+
cdp.close();
|
|
68
|
+
throw error;
|
|
69
|
+
}
|
|
70
|
+
const ax = new AxHelpers(() => page, () => cdp);
|
|
71
|
+
/**
|
|
72
|
+
* Drives the tab the driven tab opened (a popup, or a link that opens a new tab), or, when the driven tab has closed,
|
|
73
|
+
* the tab that opened it (else the browser's last, else a blank one). The old tab's snapshot ids are dropped, so an
|
|
74
|
+
* action by id fails as a stale snapshot until the next snapshot. Answers the line that says so, or nothing when
|
|
75
|
+
* the driven tab stays.
|
|
76
|
+
*/
|
|
77
|
+
const follow = async () => {
|
|
78
|
+
const tabs = await tabsOf(cdp);
|
|
79
|
+
const opened = tabs.filter((t) => !seen.has(t.targetId) && t.openerId === page.targetId).at(-1);
|
|
80
|
+
for (const t of tabs)
|
|
81
|
+
seen.add(t.targetId);
|
|
82
|
+
let next = opened?.targetId;
|
|
83
|
+
if (!next && !tabs.some((t) => t.targetId === page.targetId)) {
|
|
84
|
+
const back = openers.get(page.targetId);
|
|
85
|
+
next = tabs.find((t) => t.targetId === back)?.targetId ?? tabs.at(-1)?.targetId ?? (await blankTab(cdp));
|
|
86
|
+
seen.add(next);
|
|
87
|
+
}
|
|
88
|
+
if (!next)
|
|
89
|
+
return undefined;
|
|
90
|
+
const old = page;
|
|
91
|
+
page = await Page.attach(cdp, next);
|
|
92
|
+
if (opened)
|
|
93
|
+
openers.set(next, old.targetId);
|
|
94
|
+
ax.forget();
|
|
95
|
+
await cdp.send("Target.detachFromTarget", { sessionId: old.sessionId }).catch(() => undefined);
|
|
96
|
+
await ax.settle({ capMs: 3000 }).catch(() => undefined);
|
|
97
|
+
const { targetInfo } = await cdp.send("Target.getTargetInfo", { targetId: next });
|
|
98
|
+
const now = opened ? "the page opened a new tab; now driving it" : "the tab closed; now driving another";
|
|
99
|
+
return `[tab] ${now}: ${targetInfo.url}.`;
|
|
100
|
+
};
|
|
101
|
+
/** The latest snapshot's ids hold: there is one, the page still shows its document, and every id is in it. */
|
|
102
|
+
const check = async (actions, checked = false) => {
|
|
103
|
+
if (actions.every((a) => a.op === "goto"))
|
|
104
|
+
return;
|
|
105
|
+
if (!ax.hydrated || !ax.taken)
|
|
106
|
+
throw stale(NO_HYDRATED_SNAPSHOT_ERROR);
|
|
107
|
+
if (!checked) {
|
|
108
|
+
// A probe the page can't answer is a navigated page; a dropped connection is said as one, not as a stale snapshot.
|
|
109
|
+
const now = await ax.probe().catch((error) => {
|
|
110
|
+
if (error instanceof CDPConnectionClosedError)
|
|
111
|
+
throw error;
|
|
112
|
+
return undefined;
|
|
113
|
+
});
|
|
114
|
+
if (!now || now.doc !== ax.taken.doc)
|
|
115
|
+
throw stale(NAVIGATED_SNAPSHOT_ERROR);
|
|
116
|
+
}
|
|
117
|
+
for (const action of actions) {
|
|
118
|
+
if (action.op === "goto")
|
|
119
|
+
break; // what follows a goto is on the next page: its ids are checked when it runs
|
|
120
|
+
try {
|
|
121
|
+
ax.nodeOf(action.id);
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
throw stale(staleSnapshotIdError(action.id));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
const runOne = async (action) => {
|
|
129
|
+
switch (action.op) {
|
|
130
|
+
case "goto": {
|
|
131
|
+
const before = await ax.probe().catch(() => undefined);
|
|
132
|
+
await page.goto(action.url);
|
|
133
|
+
// The page's ids were the old document's: the next action by id fails as a stale snapshot.
|
|
134
|
+
ax.forget();
|
|
135
|
+
const settled = await ax.settle({ capMs: 3000 });
|
|
136
|
+
return `[ok] goto ${action.url} -> ${await ax.change(before, settled.probe)}`;
|
|
137
|
+
}
|
|
138
|
+
case "click":
|
|
139
|
+
return ax.click(action.id);
|
|
140
|
+
case "hover":
|
|
141
|
+
return ax.hover(action.id);
|
|
142
|
+
case "fill":
|
|
143
|
+
return ax.fill(action.id, action.value);
|
|
144
|
+
case "type":
|
|
145
|
+
return ax.type(action.id, action.text, action.delay);
|
|
146
|
+
case "press":
|
|
147
|
+
return ax.press(action.id, action.key);
|
|
148
|
+
case "select":
|
|
149
|
+
return ax.select(action.id, action.values);
|
|
150
|
+
default:
|
|
151
|
+
throw refusedError(`run takes the ops goto, click, hover, fill, type, press and select, not ${JSON.stringify(action.op)}`);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
return {
|
|
155
|
+
// A snapshot is of the tab the agent is on now: a tab the page opened since, or the one left when it closed.
|
|
156
|
+
snapshot: async (options = {}) => {
|
|
157
|
+
const moved = await follow();
|
|
158
|
+
const shot = await ax.snapshot(options.includeIframes === undefined ? {} : { includeIframes: options.includeIframes });
|
|
159
|
+
return moved ? `${moved}\n${shot}` : shot;
|
|
160
|
+
},
|
|
161
|
+
run: async ({ code, actions, checked, rest: after = 0 }) => {
|
|
162
|
+
movedTab = false;
|
|
163
|
+
if (code !== undefined)
|
|
164
|
+
throw refusedError(CDP_CODE_REFUSED);
|
|
165
|
+
if (!actions?.length)
|
|
166
|
+
throw refusedError("run requires exactly one of code or actions");
|
|
167
|
+
await check(actions, checked === true);
|
|
168
|
+
const lines = [];
|
|
169
|
+
for (const [i, action] of actions.entries()) {
|
|
170
|
+
try {
|
|
171
|
+
lines.push(await runOne(action));
|
|
172
|
+
}
|
|
173
|
+
catch (error) {
|
|
174
|
+
// An id after a goto in the same run names nothing of the new page: a stale snapshot.
|
|
175
|
+
if (error instanceof UnknownIdError)
|
|
176
|
+
throw stale(staleSnapshotIdError(error.id));
|
|
177
|
+
if (!lines.length)
|
|
178
|
+
throw error;
|
|
179
|
+
// What ran is said with what failed: the actions before it took effect.
|
|
180
|
+
throw new Error(`${lines.join("\n")}\n${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
181
|
+
}
|
|
182
|
+
// An action that opened a tab (or closed this one) moves the driver there; the rest name the old tab's ids.
|
|
183
|
+
// The action already took effect, so a failure to look is not its failure.
|
|
184
|
+
const moved = await follow().catch(() => undefined);
|
|
185
|
+
if (moved) {
|
|
186
|
+
movedTab = true;
|
|
187
|
+
lines.push(`${moved} Take a snapshot before acting by id.`);
|
|
188
|
+
// This run's actions after this one, and the batch's that the guard would send after them.
|
|
189
|
+
const rest = actions.length - i - 1 + after;
|
|
190
|
+
if (rest)
|
|
191
|
+
lines.push(`[stopped] ${rest} more action${rest === 1 ? "" : "s"} not run: they name the old tab's snapshot ids.`);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
return lines.join("\n");
|
|
196
|
+
},
|
|
197
|
+
movedTab: () => movedTab,
|
|
198
|
+
checkActions: (actions) => check(actions),
|
|
199
|
+
url: async () => {
|
|
200
|
+
const { targetInfo } = await cdp.send("Target.getTargetInfo", { targetId: page.targetId });
|
|
201
|
+
return targetInfo.url;
|
|
202
|
+
},
|
|
203
|
+
forgetSnapshots: () => ax.forget(),
|
|
204
|
+
locate: async (place) => {
|
|
205
|
+
if (place?.id !== undefined) {
|
|
206
|
+
let node;
|
|
207
|
+
try {
|
|
208
|
+
node = ax.nodeOf(place.id);
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
throw stale(ax.hydrated ? staleSnapshotIdError(place.id) : NO_HYDRATED_SNAPSHOT_ERROR);
|
|
212
|
+
}
|
|
213
|
+
const { object } = await page.cdp("DOM.resolveNode", { backendNodeId: node });
|
|
214
|
+
if (!object.objectId)
|
|
215
|
+
return { viewport: await page.evaluate(() => ({ width: innerWidth, height: innerHeight })), matches: 0 };
|
|
216
|
+
try {
|
|
217
|
+
const answer = await page.cdp("Runtime.callFunctionOn", { objectId: object.objectId, functionDeclaration: LOCATE_JS, arguments: [{ value: undefined }], returnByValue: true });
|
|
218
|
+
return answer.result.value;
|
|
219
|
+
}
|
|
220
|
+
finally {
|
|
221
|
+
await page.cdp("Runtime.releaseObject", { objectId: object.objectId }).catch(() => { });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
const selector = place?.selector ?? null;
|
|
225
|
+
return page.evaluate(`(${LOCATE_JS}).call(document, ${JSON.stringify(selector)})`);
|
|
226
|
+
},
|
|
227
|
+
screenshot: async (options) => {
|
|
228
|
+
const data = await page.screenshot(options);
|
|
229
|
+
return { data, mimeType: options.type === "jpeg" ? "image/jpeg" : "image/png" };
|
|
230
|
+
},
|
|
231
|
+
// One evaluate reads all four, so they are one document's.
|
|
232
|
+
page: () => page.evaluate(() => ({
|
|
233
|
+
url: location.href,
|
|
234
|
+
title: document.title,
|
|
235
|
+
text: document.body ? document.body.innerText : "",
|
|
236
|
+
html: document.documentElement ? document.documentElement.outerHTML : "",
|
|
237
|
+
})),
|
|
238
|
+
// The browser keeps running: custody releases it through the provider.
|
|
239
|
+
close: async () => {
|
|
240
|
+
await cdp.send("Target.detachFromTarget", { sessionId: page.sessionId }).catch(() => undefined);
|
|
241
|
+
cdp.close();
|
|
242
|
+
},
|
|
243
|
+
};
|
|
244
|
+
};
|
|
245
|
+
}
|
|
@@ -68,6 +68,8 @@ function bounded(stagehand, deadlines) {
|
|
|
68
68
|
browser: overriding(stagehand.browser, { context: overriding(context, { activePage: async () => { const active = await context.activePage(); return active ? page(active) : active; } }) }),
|
|
69
69
|
});
|
|
70
70
|
}
|
|
71
|
+
/** How long a page has to say which document it shows before it is taken not to know. */
|
|
72
|
+
const DOCUMENT_MS = 5_000;
|
|
71
73
|
/** `batchMs` bounds every run batch; the page calls' own deadlines are fixed but for tests. */
|
|
72
74
|
export function pageDriver(stagehand, deadlines) {
|
|
73
75
|
const host = bounded(stagehand, { snapshotMs: SNAPSHOT_MS, screenshotMs: SCREENSHOT_MS, ...deadlines });
|
|
@@ -82,9 +84,104 @@ export function pageDriver(stagehand, deadlines) {
|
|
|
82
84
|
// In a batch of its own, which the browser runs once the new document is its page's.
|
|
83
85
|
const newDocument = async () => stagehand.experimentalBatch(async (batch, input) => { await batch.page.waitForLoadState("domcontentloaded", input.ms); }, { ms: NEW_DOCUMENT_MS }, { page: await active(), timeout: NEW_DOCUMENT_MS + 1_000 });
|
|
84
86
|
const reads = documentReads(facade, newDocument);
|
|
87
|
+
const kept = () => facade.snapshotsByPage;
|
|
88
|
+
/** The document a page shows, by its own performance.timeOrigin: new on every navigation to a new document and on a
|
|
89
|
+
* reload, the same across a #hash change or history.pushState/replaceState (Chrome's per-document loaderId, which
|
|
90
|
+
* neither Stagehand's page nor a batch's page can be asked for). Null when the page does not say. */
|
|
91
|
+
const documentOf = async (page) => {
|
|
92
|
+
let timer;
|
|
93
|
+
try {
|
|
94
|
+
const late = new Promise((resolve) => { timer = setTimeout(() => resolve(null), DOCUMENT_MS); });
|
|
95
|
+
const origin = await Promise.race([Promise.resolve(page.evaluate("performance.timeOrigin")).catch(() => null), late]);
|
|
96
|
+
return typeof origin === "number" ? origin : null;
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
/** By page, the document each snapshot was taken on (read once the snapshot is), and that snapshot's ids, to know it is
|
|
106
|
+
* still the facade's. Read beside the snapshot, never holding it up: a batch awaits it. */
|
|
107
|
+
const snapshotDocuments = new Map();
|
|
108
|
+
/** An action after the first of a batch checked as one (driving-guard): run by the facade with the snapshot taken as at
|
|
109
|
+
* the page's address now, for this action only, so an address the batch's own earlier actions moved is not a stale
|
|
110
|
+
* snapshot; then the snapshot's own address again, so a later call on the moved page is told to snapshot again. */
|
|
111
|
+
const afterChecked = async (actions) => {
|
|
112
|
+
const page = await active();
|
|
113
|
+
const snapshot = kept().get(page.pageId);
|
|
114
|
+
// Only on the snapshot's own document: an earlier action that loaded a new one (a link to another page, a reload)
|
|
115
|
+
// leaves the snapshot's ids pointing at nothing of this page's, so the batch stops before this action, as stale.
|
|
116
|
+
if (snapshot) {
|
|
117
|
+
const taken = snapshotDocuments.get(page.pageId);
|
|
118
|
+
const was = taken && taken.xpathById === snapshot.xpathById ? await taken.document : null;
|
|
119
|
+
const document = was === null ? null : await documentOf(page);
|
|
120
|
+
if (was === null || document !== was)
|
|
121
|
+
throw new Error(NAVIGATED_SNAPSHOT_ERROR);
|
|
122
|
+
}
|
|
123
|
+
const now = snapshot ? await page.url() : undefined;
|
|
124
|
+
if (!snapshot || now === snapshot.url)
|
|
125
|
+
return facade.runActions(actions);
|
|
126
|
+
kept().set(page.pageId, { ...snapshot, url: now });
|
|
127
|
+
try {
|
|
128
|
+
return await facade.runActions(actions);
|
|
129
|
+
}
|
|
130
|
+
finally {
|
|
131
|
+
const current = kept().get(page.pageId);
|
|
132
|
+
if (current && current.xpathById === snapshot.xpathById)
|
|
133
|
+
kept().set(page.pageId, { ...current, url: snapshot.url });
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
/** A batch with a goto: the actions one at a time, a goto through the facade's page (http, https or about:blank only), each
|
|
137
|
+
* other action by its id as the facade runs it, so an id after a goto meets the new page and fails as a stale snapshot. */
|
|
138
|
+
const withGoto = async (actions, checked) => {
|
|
139
|
+
if (!actions.some((action) => action.op === "goto"))
|
|
140
|
+
return checked ? afterChecked(actions) : facade.runActions(actions);
|
|
141
|
+
let completed = 0;
|
|
142
|
+
let url = "";
|
|
143
|
+
for (const action of actions) {
|
|
144
|
+
if (action.op === "goto") {
|
|
145
|
+
if (!/^(https?:\/\/|about:blank$)/i.test(action.url))
|
|
146
|
+
throw new Error(`goto takes an http or https URL (or about:blank), not ${JSON.stringify(action.url.slice(0, 100))}`);
|
|
147
|
+
url = await facade.run(`await page.goto(${JSON.stringify(action.url)}); return page.url();`);
|
|
148
|
+
}
|
|
149
|
+
else
|
|
150
|
+
url = (await facade.runActions([action])).url;
|
|
151
|
+
completed++;
|
|
152
|
+
}
|
|
153
|
+
return { completed, url };
|
|
154
|
+
};
|
|
85
155
|
return {
|
|
86
|
-
snapshot: (snapshotOptions) =>
|
|
87
|
-
|
|
156
|
+
snapshot: async (snapshotOptions) => {
|
|
157
|
+
const tree = await reads.snapshot(snapshotOptions);
|
|
158
|
+
const page = await active().catch(() => null);
|
|
159
|
+
const taken = page ? kept().get(page.pageId) : undefined;
|
|
160
|
+
if (page && taken)
|
|
161
|
+
snapshotDocuments.set(page.pageId, { xpathById: taken.xpathById, document: documentOf(page) });
|
|
162
|
+
return tree;
|
|
163
|
+
},
|
|
164
|
+
run: (input) => input.actions !== undefined ? withGoto(input.actions, input.checked === true) : facade.run(input.code ?? ""),
|
|
165
|
+
// As the facade's own batch checks a run's actions before it sends any (runActionsNow): the active page's snapshot,
|
|
166
|
+
// the page still at its address, and every id in it. Read from the facade's snapshots, as forgetSnapshots does. A
|
|
167
|
+
// batch of gotos alone names no id, so it needs no snapshot, as the raw-CDP driver's check holds too.
|
|
168
|
+
checkActions: async (actions) => {
|
|
169
|
+
if (actions.every((action) => action.op === "goto"))
|
|
170
|
+
return;
|
|
171
|
+
const page = await active();
|
|
172
|
+
const snapshot = facade.snapshotsByPage.get(page.pageId);
|
|
173
|
+
if (!snapshot)
|
|
174
|
+
throw new Error(NO_HYDRATED_SNAPSHOT_ERROR);
|
|
175
|
+
if ((await page.url()) !== snapshot.url)
|
|
176
|
+
throw new Error(NAVIGATED_SNAPSHOT_ERROR);
|
|
177
|
+
for (const action of actions) {
|
|
178
|
+
// What follows a goto is on the next page: its ids are checked when it runs.
|
|
179
|
+
if (action.op === "goto")
|
|
180
|
+
break;
|
|
181
|
+
if (!snapshot.xpathById[action.id])
|
|
182
|
+
throw new Error(staleSnapshotIdError(action.id));
|
|
183
|
+
}
|
|
184
|
+
},
|
|
88
185
|
url: async () => documentUrl(stagehand, await active()),
|
|
89
186
|
// The facade keeps each page's last snapshot's ids for its own actions; with none, an action by id fails NO_HYDRATED (a stale snapshot).
|
|
90
187
|
forgetSnapshots: () => { facade.snapshotsByPage.clear(); },
|
|
@@ -108,12 +205,16 @@ export function pageDriver(stagehand, deadlines) {
|
|
|
108
205
|
selector = target.selector;
|
|
109
206
|
return await facade.run(locateCode(selector));
|
|
110
207
|
}),
|
|
208
|
+
// Stagehand's page.screenshot scales to its device's pixels or to one per CSS pixel, and only a clip: a scale below 1
|
|
209
|
+
// is a clip (the viewport's, when none is asked) at one image pixel per CSS pixel, which is no smaller than that on a
|
|
210
|
+
// display of one device pixel per CSS pixel. A full page it does not scale (captureWithinBudget takes the viewport).
|
|
111
211
|
screenshot: async ({ type = "png", quality, fullPage, scale, clip }) => {
|
|
212
|
+
const css = scale !== undefined && scale < 1;
|
|
112
213
|
// A clip is read from the viewport's corner, and the browser's own is from the document's: the scroll offset is added.
|
|
113
|
-
const
|
|
214
|
+
const view = clip || (css && !fullPage) ? await facade.run(`return await page.evaluate("({ x: scrollX, y: scrollY, width: innerWidth, height: innerHeight })");`) : null;
|
|
215
|
+
const region = view && (clip ? { ...clip, x: clip.x + view.x, y: clip.y + view.y } : view);
|
|
114
216
|
const bytes = await (await active()).screenshot({
|
|
115
|
-
type, ...(fullPage === undefined ? {} : { fullPage }), ...(
|
|
116
|
-
...(clip && origin ? { clip: { ...clip, x: clip.x + origin.x, y: clip.y + origin.y } } : {}),
|
|
217
|
+
type, ...(region ? { clip: region } : fullPage === undefined ? {} : { fullPage }), ...(css ? { scale: "css" } : {}),
|
|
117
218
|
// CDP takes a quality for jpeg only, and only as an integer.
|
|
118
219
|
...(type === "jpeg" && quality !== undefined ? { quality: Math.round(quality) } : {}),
|
|
119
220
|
});
|
|
@@ -122,7 +223,9 @@ export function pageDriver(stagehand, deadlines) {
|
|
|
122
223
|
page: () => reads.page(),
|
|
123
224
|
// An upload is effectful: past its deadline it fails as unanswered, and the page tools tell it as possibly applied.
|
|
124
225
|
setInputFiles: async (selector, file) => { await withinDeadline((await active()).locator(selector).setInputFiles({ name: file.name, mimeType: file.mimeType, buffer: file.buffer }), uploadMs, "locator.setInputFiles"); },
|
|
125
|
-
// Stagehand
|
|
126
|
-
|
|
226
|
+
// Stagehand 4.4 lets one client attach to a browser at a time, and its close leaves this client attached: disconnect closes
|
|
227
|
+
// the instance (waiting 10 s at most), detaches the client and closes the socket, so the next attach is allowed. The
|
|
228
|
+
// browser keeps running; the browser's own close would end it.
|
|
229
|
+
close: () => stagehand.browser.disconnect(),
|
|
127
230
|
};
|
|
128
231
|
}
|
package/dist/driver/sealed.d.ts
CHANGED
|
@@ -1,16 +1,8 @@
|
|
|
1
|
-
/** What Stagehand's extension answers an init while another is still running in it. */
|
|
2
|
-
export declare const INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
|
|
3
|
-
/** Stagehand's own init deadline: an init the extension is still running has ended by then. */
|
|
4
|
-
export declare const IN_FLIGHT_INIT_MS = 60000;
|
|
5
|
-
/** The extension refused an init because another is still running in it (its JSON-RPC error, as Stagehand's cause). */
|
|
6
|
-
export declare const initInProgress: (error: unknown) => boolean;
|
|
7
1
|
/** A failed attach step names where it went: Stagehand reports a failed open as "[object Object]", and the socket's error
|
|
8
2
|
* has no address. */
|
|
9
3
|
export declare const attachStep: (host: string) => <T>(step: Promise<T>) => Promise<T>;
|
|
10
|
-
/** A cancelled call never starts
|
|
4
|
+
/** A cancelled call never starts a step of its own, however the wait ended. */
|
|
11
5
|
export declare function throwIfCancelled(signal?: AbortSignal): void;
|
|
12
|
-
/**
|
|
13
|
-
*
|
|
14
|
-
|
|
15
|
-
* busy, retryable. */
|
|
16
|
-
export declare function createSealed<S>(create: () => Promise<S>, waitForThatInit: () => Promise<unknown>, host: string, signal?: AbortSignal): Promise<S>;
|
|
6
|
+
/** `step`, or the cancel when `signal` ends first: the call stops at once, and a step that still succeeds later is handed to
|
|
7
|
+
* `release` (Stagehand's own steps take no signal, and one left attached would refuse the next attach). */
|
|
8
|
+
export declare function untilCancelled<T>(step: Promise<T>, signal: AbortSignal | undefined, release: (late: T) => unknown): Promise<T>;
|
package/dist/driver/sealed.js
CHANGED
|
@@ -1,47 +1,33 @@
|
|
|
1
|
-
// The steps of attaching a sealed Stagehand that can fail on their own: naming where a failed step went, stopping a
|
|
2
|
-
// cancelled attach
|
|
3
|
-
import { BrowserFailureError } from "../core/custody.js";
|
|
4
|
-
import { browserFailure } from "../core/failures.js";
|
|
5
|
-
/** What Stagehand's extension answers an init while another is still running in it. */
|
|
6
|
-
export const INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
|
|
7
|
-
/** Stagehand's own init deadline: an init the extension is still running has ended by then. */
|
|
8
|
-
export const IN_FLIGHT_INIT_MS = 60_000;
|
|
9
|
-
/** The extension refused an init because another is still running in it (its JSON-RPC error, as Stagehand's cause). */
|
|
10
|
-
export const initInProgress = (error) => {
|
|
11
|
-
const cause = error?.cause;
|
|
12
|
-
return !!cause && typeof cause === "object" && typeof cause.code === "number" && cause.message === INIT_IN_PROGRESS;
|
|
13
|
-
};
|
|
1
|
+
// The steps of attaching a sealed Stagehand that can fail on their own: naming where a failed step went, and stopping a
|
|
2
|
+
// cancelled attach without leaving anything attached to the browser.
|
|
14
3
|
/** A failed attach step names where it went: Stagehand reports a failed open as "[object Object]", and the socket's error
|
|
15
4
|
* has no address. */
|
|
16
5
|
export const attachStep = (host) => (step) => step.catch((error) => {
|
|
17
6
|
throw new Error(`attaching to the browser at ${host} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
18
7
|
});
|
|
19
|
-
|
|
8
|
+
const cancelled = (signal) => signal.reason instanceof Error ? signal.reason : Object.assign(new Error("the attach was cancelled"), { name: "AbortError" });
|
|
9
|
+
/** A cancelled call never starts a step of its own, however the wait ended. */
|
|
20
10
|
export function throwIfCancelled(signal) {
|
|
21
11
|
if (signal?.aborted)
|
|
22
|
-
throw signal
|
|
12
|
+
throw cancelled(signal);
|
|
23
13
|
}
|
|
24
|
-
/**
|
|
25
|
-
*
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
catch (error) {
|
|
33
|
-
if (!initInProgress(error))
|
|
34
|
-
throw error;
|
|
35
|
-
}
|
|
36
|
-
throwIfCancelled(signal);
|
|
37
|
-
await waitForThatInit();
|
|
38
|
-
throwIfCancelled(signal);
|
|
39
|
-
try {
|
|
40
|
-
return await create();
|
|
41
|
-
}
|
|
42
|
-
catch (again) {
|
|
43
|
-
if (!initInProgress(again))
|
|
44
|
-
throw again;
|
|
45
|
-
throw new BrowserFailureError(browserFailure("browser_unavailable", `The browser at ${host} is still finishing an earlier connection after ${IN_FLIGHT_INIT_MS / 1_000} s. Call again in a moment, or call browser_relaunch for a fresh session.`, { retryable: true }));
|
|
14
|
+
/** `step`, or the cancel when `signal` ends first: the call stops at once, and a step that still succeeds later is handed to
|
|
15
|
+
* `release` (Stagehand's own steps take no signal, and one left attached would refuse the next attach). */
|
|
16
|
+
export function untilCancelled(step, signal, release) {
|
|
17
|
+
if (!signal)
|
|
18
|
+
return step;
|
|
19
|
+
if (signal.aborted) {
|
|
20
|
+
step.then((late) => release(late), () => undefined).catch(() => undefined);
|
|
21
|
+
return Promise.reject(cancelled(signal));
|
|
46
22
|
}
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
let over = false;
|
|
25
|
+
const onAbort = () => { over = true; reject(cancelled(signal)); };
|
|
26
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
27
|
+
step.then((value) => { signal.removeEventListener("abort", onAbort); if (over)
|
|
28
|
+
Promise.resolve().then(() => release(value)).catch(() => undefined);
|
|
29
|
+
else
|
|
30
|
+
resolve(value); }, (error) => { signal.removeEventListener("abort", onAbort); if (!over)
|
|
31
|
+
reject(error); });
|
|
32
|
+
});
|
|
47
33
|
}
|
|
@@ -1,12 +1,7 @@
|
|
|
1
1
|
import { type DriverFactory } from "../core/custody.js";
|
|
2
2
|
import type { PageDriver } from "../core/tools.js";
|
|
3
|
-
/** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
|
|
4
|
-
export declare const STAGEHAND_TELEMETRY: {
|
|
5
|
-
readonly traces: {
|
|
6
|
-
readonly endpoint: "http://127.0.0.1:9/v1/traces";
|
|
7
|
-
};
|
|
8
|
-
};
|
|
9
3
|
export declare const STAGEHAND_INFERENCE_REFUSED = "Stagehand inference is off in this harness: act, extract and observe are unavailable. Drive the page with run code or snapshot IDs.";
|
|
4
|
+
/** No telemetry is given, and Stagehand 4.4 starts its trace exporter only for an endpoint it is given: no span is sent. */
|
|
10
5
|
export declare const SEALED_STAGEHAND: {
|
|
11
6
|
readonly logging: {
|
|
12
7
|
readonly level: "off";
|
|
@@ -15,13 +10,15 @@ export declare const SEALED_STAGEHAND: {
|
|
|
15
10
|
readonly model: {
|
|
16
11
|
readonly generate: () => Promise<never>;
|
|
17
12
|
};
|
|
18
|
-
readonly telemetry: {
|
|
19
|
-
readonly traces: {
|
|
20
|
-
readonly endpoint: "http://127.0.0.1:9/v1/traces";
|
|
21
|
-
};
|
|
22
|
-
};
|
|
23
13
|
};
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
14
|
+
type StagehandModule = Pick<typeof import("@browserbasehq/stagehand"), "localBrowser" | "Stagehand">;
|
|
15
|
+
/** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
|
|
16
|
+
export declare const DEFAULT_BATCH_TIMEOUT_MS = 60000;
|
|
17
|
+
/** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
|
|
18
|
+
* client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
|
|
19
|
+
* the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
|
|
20
|
+
* for tests: the Stagehand module the driver uses. */
|
|
21
|
+
export declare function stagehandDriver(internals?: {
|
|
22
|
+
stagehand?: () => Promise<StagehandModule>;
|
|
23
|
+
}): DriverFactory<PageDriver>;
|
|
24
|
+
export {};
|
package/dist/driver/stagehand.js
CHANGED
|
@@ -1,28 +1,32 @@
|
|
|
1
|
-
import { INERT_TRACE_ENDPOINT } from "../core/effects.js";
|
|
2
|
-
import { installedExtension } from "./extension-worker.js";
|
|
3
1
|
import { pageDriver } from "./page-driver.js";
|
|
4
|
-
import { attachStep,
|
|
5
|
-
/** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
|
|
6
|
-
export const STAGEHAND_TELEMETRY = { traces: { endpoint: INERT_TRACE_ENDPOINT } };
|
|
2
|
+
import { attachStep, throwIfCancelled, untilCancelled } from "./sealed.js";
|
|
7
3
|
export const STAGEHAND_INFERENCE_REFUSED = "Stagehand inference is off in this harness: act, extract and observe are unavailable. Drive the page with run code or snapshot IDs.";
|
|
4
|
+
/** No telemetry is given, and Stagehand 4.4 starts its trace exporter only for an endpoint it is given: no span is sent. */
|
|
8
5
|
export const SEALED_STAGEHAND = {
|
|
9
6
|
logging: { level: "off" },
|
|
10
7
|
cache: false,
|
|
11
8
|
model: { generate: async () => { throw new Error(STAGEHAND_INFERENCE_REFUSED); } },
|
|
12
|
-
telemetry: STAGEHAND_TELEMETRY,
|
|
13
9
|
};
|
|
14
|
-
/**
|
|
15
|
-
export const
|
|
16
|
-
/** The batch deadline comes from `DriverOptions`; a caller that passes none gets
|
|
17
|
-
|
|
10
|
+
/** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
|
|
11
|
+
export const DEFAULT_BATCH_TIMEOUT_MS = 60_000;
|
|
12
|
+
/** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
|
|
13
|
+
* client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
|
|
14
|
+
* the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
|
|
15
|
+
* for tests: the Stagehand module the driver uses. */
|
|
16
|
+
export function stagehandDriver(internals = {}) {
|
|
18
17
|
return async (target, signal, options) => {
|
|
19
|
-
const { localBrowser, Stagehand } = await import("@browserbasehq/stagehand");
|
|
18
|
+
const { localBrowser, Stagehand } = await (internals.stagehand ?? (() => import("@browserbasehq/stagehand")))();
|
|
20
19
|
const host = new URL(target.dial?.url ?? target.sdkCdpUrl).host;
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
20
|
+
throwIfCancelled(signal);
|
|
21
|
+
const connecting = localBrowser.connect({ cdpUrl: target.sdkCdpUrl, ...(target.extensionCdpUrl ? { extensionCdpUrl: target.extensionCdpUrl } : {}) });
|
|
22
|
+
const browser = await untilCancelled(attachStep(host)(connecting), signal, (late) => late.disconnect());
|
|
23
|
+
try {
|
|
24
|
+
const stagehand = await untilCancelled(Stagehand.create({ browser, ...SEALED_STAGEHAND }), signal, () => undefined);
|
|
25
|
+
return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS });
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
await browser.disconnect().catch(() => undefined);
|
|
29
|
+
throw error;
|
|
30
|
+
}
|
|
27
31
|
};
|
|
28
32
|
}
|
package/dist/durable/result.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { ToolOutput } from "../core/custody.js";
|
|
2
|
-
/**
|
|
2
|
+
/** A tool result's blocks as pi-durable reads them: its `output`. */
|
|
3
3
|
export declare const forModel: (content: ToolOutput["content"]) => {
|
|
4
|
-
content: ToolOutput["content"];
|
|
5
4
|
output: ToolOutput["content"];
|
|
6
5
|
};
|
package/dist/durable/result.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export const forModel = (content) => ({
|
|
1
|
+
/** A tool result's blocks as pi-durable reads them: its `output`. */
|
|
2
|
+
export const forModel = (content) => ({ output: content });
|