@parcha/pi-browser 0.1.0-beta.35 → 0.1.0-beta.351
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 +162 -0
- package/NOTICE +6 -1
- package/README.md +65 -39
- package/dist/core/contract.js +4 -1
- package/dist/core/custody.d.ts +6 -0
- package/dist/core/custody.js +15 -3
- package/dist/core/downloads.d.ts +37 -3
- package/dist/core/downloads.js +81 -57
- package/dist/core/driving-guard.d.ts +1 -1
- package/dist/core/driving-guard.js +1 -1
- package/dist/core/files.d.ts +17 -2
- package/dist/core/files.js +157 -9
- package/dist/core/host.d.ts +20 -14
- 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/tools.d.ts +23 -1
- package/dist/core/tools.js +46 -4
- package/dist/core/usage.d.ts +4 -1
- package/dist/core/usage.js +5 -2
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/driver/cdp.js +3 -3
- package/dist/driver/page-driver.js +7 -3
- package/dist/driver/stagehand.d.ts +3 -1
- package/dist/driver/stagehand.js +4 -2
- package/dist/durable/store.d.ts +14 -3
- package/dist/durable/store.js +204 -51
- package/dist/durable.d.ts +31 -4
- package/dist/durable.js +61 -16
- package/dist/index.d.ts +3 -2
- package/dist/index.js +5 -2
- package/dist/live-view/index.d.ts +3 -1
- package/dist/live-view/index.js +4 -0
- package/dist/live-view/protocol.d.ts +1 -1
- package/dist/live-view/server.d.ts +30 -0
- package/dist/live-view/server.js +152 -25
- package/dist/providers/cdp.js +2 -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 +14 -1
- package/dist/providers/worker-extension.js +69 -3
- package/dist/testing/backend.d.ts +4 -3
- package/dist/testing/backend.js +6 -5
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/page.d.ts +3 -12
- package/dist/vendor/browser-use-pi/page.js +6 -19
- package/package.json +8 -21
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -138
- package/dist/providers/browserbase.js +0 -294
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
|
@@ -2,19 +2,85 @@
|
|
|
2
2
|
// connect to nothing but the extension's own files and the browser's DevTools socket. Run code executes in that worker with
|
|
3
3
|
// the extension's host permissions, so the browser itself refuses what the observer can only watch. A copy, because the
|
|
4
4
|
// manifest is Stagehand's bytes and a directory shared by every lease cannot name this lease's socket; created before the
|
|
5
|
-
// browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to.
|
|
5
|
+
// browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to. The
|
|
6
|
+
// copy's worker also carries one rewrite, so a process that dies inside a run can be reattached at once (endBatchesOnRelease).
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
6
8
|
import { cp, readFile, writeFile } from "node:fs/promises";
|
|
7
9
|
import path from "node:path";
|
|
8
|
-
import {
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { cdpCall } from "../core/cdp-call.js";
|
|
12
|
+
import { BrowserFailureError } from "../core/custody.js";
|
|
13
|
+
import { browserFailure } from "../core/failures.js";
|
|
9
14
|
import { extensionDirectory, extensionOrigin } from "./chrome-args.js";
|
|
10
15
|
export const COPY = "stagehand-extension";
|
|
11
16
|
/** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
|
|
12
17
|
export const STAGEHAND_EXTENSION = "Stagehand Runtime";
|
|
13
18
|
const LOAD_MS = 20_000;
|
|
14
|
-
/**
|
|
19
|
+
/** The Stagehand release the rewrite below was written against; a test holds it to the installed one, so a bump re-reads it. */
|
|
20
|
+
export const REWRITE_FOR = "4.4.0";
|
|
21
|
+
const WORKER = "service-worker.js";
|
|
22
|
+
/** The first line of a rewritten worker, so the copy a browser runs can be told from Stagehand's own. */
|
|
23
|
+
export const REWRITE_MARK = "// pi-browser: a released client's callback batches end with it (see NOTICE in this directory).\n";
|
|
24
|
+
export const COPY_NOTICE = `This directory is a copy of the extension in @browserbasehq/stagehand ${REWRITE_FOR} (dist/extension), under
|
|
25
|
+
Stagehand's MIT license (LICENSE, beside this file). @parcha/pi-browser changed two files in it:
|
|
26
|
+
- manifest.json: a content security policy limiting the extension's connections to its own files and one browser's
|
|
27
|
+
DevTools socket.
|
|
28
|
+
- ${WORKER}: when the extension releases a client that went away, it now aborts that client's running callback batches,
|
|
29
|
+
rather than leaving each to run until its own timeout.
|
|
30
|
+
`;
|
|
31
|
+
// Stagehand's extension keeps a dead client's callback batch running until the batch's own timeout, and holds the next client's
|
|
32
|
+
// stagehand.init behind it: releasing the client (ClientLifecycle.lost, then RPCClient.releaseClient) does not reach the batch's
|
|
33
|
+
// AbortController (createCallbackBatchController), while disposing the instance waits for every request in flight, the batch
|
|
34
|
+
// among them, and init queues behind that disposal. A process that dies inside a run is reattached only after its last batch's
|
|
35
|
+
// deadline (60 s by default), as long as Stagehand's own init deadline. The rewrite has releaseClient abort the running batches.
|
|
36
|
+
// That alone frees init (lines in Stagehand 4.4.0's dist/extension/service-worker.js): run() races the callback against its
|
|
37
|
+
// abort (:14696), so it rejects at once; only the outer callback_batch request holds the instance (:13368), the commands a batch
|
|
38
|
+
// sends taking none; its error reply throws, the client being gone (:13224), and its finally still releases the instance. One
|
|
39
|
+
// client is attached at a time and the router serves whichever it is, so only the dead client's batches are running when its
|
|
40
|
+
// release comes. Delete this rewrite once Stagehand ships the same change (upstream issue to be linked here).
|
|
41
|
+
const EDITS = [
|
|
42
|
+
{ name: "the batch registry",
|
|
43
|
+
find: "function createCallbackBatchController(router) {\n",
|
|
44
|
+
to: "function createCallbackBatchController(router) {\n\tconst active = new Set();\n" },
|
|
45
|
+
{ name: "a batch's start",
|
|
46
|
+
find: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n",
|
|
47
|
+
to: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n\t\tactive.add(controller);\n" },
|
|
48
|
+
{ name: "a batch's end",
|
|
49
|
+
find: "\t\t\tclearTimeout(timeoutId);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n",
|
|
50
|
+
to: "\t\t\tclearTimeout(timeoutId);\n\t\t\tactive.delete(controller);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n" },
|
|
51
|
+
{ name: "the batch controller's interface",
|
|
52
|
+
find: "\treturn { run };\n}\nfunction createCallbackContextFacade(",
|
|
53
|
+
to: "\treturn {\n\t\trun,\n\t\tabortAll(reason) {\n\t\t\tfor (const controller of active) controller.abort(reason);\n\t\t}\n\t};\n}\nfunction createCallbackContextFacade(" },
|
|
54
|
+
{ name: "the client's release",
|
|
55
|
+
find: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n",
|
|
56
|
+
to: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n\t\tthis.router.callbackBatchController.abortAll(/* @__PURE__ */ new Error(\"Stagehand client disconnected\"));\n" },
|
|
57
|
+
];
|
|
58
|
+
/** Stagehand's package root (the module it exports is dist/index.mjs). */
|
|
59
|
+
const stagehandRoot = () => path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "..");
|
|
60
|
+
/** The Stagehand version installed beside this package. */
|
|
61
|
+
export const installedStagehand = () => JSON.parse(readFileSync(path.join(stagehandRoot(), "package.json"), "utf8")).version;
|
|
62
|
+
/** Stagehand's extension worker with the rewrite above. Each place it changes must appear exactly once: a worker that has moved
|
|
63
|
+
* any of them is refused whole, naming the place and the installed Stagehand (`installed`), and never rewritten in part. A
|
|
64
|
+
* refusal fails the local Chrome launch with that error (copyExtension runs before Chrome starts, and the cdp provider removes
|
|
65
|
+
* what the launch made): a launch never goes ahead on a copy without the rewrite, nor on Stagehand's own directory. */
|
|
66
|
+
export function endBatchesOnRelease(worker, installed = installedStagehand()) {
|
|
67
|
+
for (const edit of EDITS) {
|
|
68
|
+
const at = worker.indexOf(edit.find);
|
|
69
|
+
if (at >= 0 && worker.indexOf(edit.find, at + 1) < 0)
|
|
70
|
+
continue;
|
|
71
|
+
throw new BrowserFailureError(browserFailure("browser_unavailable", `Stagehand's extension worker (${WORKER}, Stagehand ${installed}) has ${at < 0 ? "no" : "more than one"} match for ${edit.name}, which pi-browser rewrites so a gone client's callback batches end with it; the rewrite was written against Stagehand ${REWRITE_FOR}. No browser was started.`));
|
|
72
|
+
}
|
|
73
|
+
return REWRITE_MARK + EDITS.reduce((text, edit) => text.replace(edit.find, () => edit.to), worker);
|
|
74
|
+
}
|
|
75
|
+
/** `<into>/stagehand-extension`, a copy of Stagehand's extension directory, its worker rewritten (above), with Stagehand's LICENSE
|
|
76
|
+
* and a NOTICE naming what changed. The worker is rewritten before anything is copied, so a refused one leaves no copy. */
|
|
15
77
|
export async function copyExtension(into, source = extensionDirectory()) {
|
|
78
|
+
const worker = endBatchesOnRelease(await readFile(path.join(source, WORKER), "utf8"));
|
|
16
79
|
const copy = path.join(into, COPY);
|
|
17
80
|
await cp(source, copy, { recursive: true, dereference: true });
|
|
81
|
+
await writeFile(path.join(copy, WORKER), worker);
|
|
82
|
+
await cp(path.join(stagehandRoot(), "LICENSE"), path.join(copy, "LICENSE"));
|
|
83
|
+
await writeFile(path.join(copy, "NOTICE"), COPY_NOTICE);
|
|
18
84
|
return copy;
|
|
19
85
|
}
|
|
20
86
|
/** The policy for the extension's pages and worker: its own files, and the browser's DevTools socket by its whole URL path. A
|
|
@@ -60,7 +60,7 @@ export type FakeBackendOptions = {
|
|
|
60
60
|
fullPageHeight?: number;
|
|
61
61
|
/** What `locate` finds, by the snapshot ID or the CSS selector a caller gives: one box or several (a selector that matches more than one). Anything else matches nothing. */
|
|
62
62
|
elements?: Record<string, FakeBox | FakeBox[]>;
|
|
63
|
-
/** Device pixels per CSS pixel; a screenshot is this many times larger
|
|
63
|
+
/** Device pixels per CSS pixel; a screenshot is this many times larger, times the `scale` it asks for. */
|
|
64
64
|
deviceScale?: number;
|
|
65
65
|
};
|
|
66
66
|
export type FakeBox = {
|
|
@@ -73,7 +73,7 @@ export type FakeScreenshotOptions = {
|
|
|
73
73
|
fullPage?: boolean;
|
|
74
74
|
type?: "png" | "jpeg";
|
|
75
75
|
quality?: number;
|
|
76
|
-
scale?:
|
|
76
|
+
scale?: number;
|
|
77
77
|
clip?: FakeBox;
|
|
78
78
|
};
|
|
79
79
|
/** A PNG or JPEG whose header declares `width` x `height`: enough for a reader that decodes the header, not a picture. */
|
|
@@ -208,7 +208,8 @@ export declare class FakeDriverFace {
|
|
|
208
208
|
}): Promise<unknown>;
|
|
209
209
|
/** No `dispatched` row: a read of the URL is not a read of the page. */
|
|
210
210
|
url(id: string): Promise<string>;
|
|
211
|
-
/** Header-only image of the viewport (or full page) times the device scale
|
|
211
|
+
/** Header-only image of the viewport (or full page) times the device scale and the asked scale, rounded as Chrome
|
|
212
|
+
* rounds; each capture is a dispatched row. */
|
|
212
213
|
screenshot(id: string, options?: FakeScreenshotOptions): Promise<{
|
|
213
214
|
data: string;
|
|
214
215
|
mimeType: string;
|
package/dist/testing/backend.js
CHANGED
|
@@ -35,7 +35,7 @@ export function fakeImage(type, width, height) {
|
|
|
35
35
|
ihdr[9] = 2;
|
|
36
36
|
return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IEND", Buffer.alloc(0))]);
|
|
37
37
|
}
|
|
38
|
-
const DEFAULT_CAPS = {
|
|
38
|
+
const DEFAULT_CAPS = { profiles: false };
|
|
39
39
|
export class FakeBackend {
|
|
40
40
|
sentinels;
|
|
41
41
|
pages;
|
|
@@ -369,13 +369,14 @@ export class FakeDriverFace {
|
|
|
369
369
|
await this.b.before("driver.url");
|
|
370
370
|
return this.session(id).url;
|
|
371
371
|
}
|
|
372
|
-
/** Header-only image of the viewport (or full page) times the device scale
|
|
372
|
+
/** Header-only image of the viewport (or full page) times the device scale and the asked scale, rounded as Chrome
|
|
373
|
+
* rounds; each capture is a dispatched row. */
|
|
373
374
|
async screenshot(id, options = {}) {
|
|
374
375
|
await this.call(id, "screenshot", "screenshot", { options });
|
|
375
376
|
const { viewport = { width: 1288, height: 711 }, fullPageHeight = 8319, deviceScale = 1 } = this.b.opts;
|
|
376
|
-
const factor = options.scale
|
|
377
|
-
const width = (options.clip ? options.clip.width : viewport.width) * factor;
|
|
378
|
-
const height = (options.clip ? options.clip.height : options.fullPage ? fullPageHeight : viewport.height) * factor;
|
|
377
|
+
const factor = deviceScale * (options.scale ?? 1);
|
|
378
|
+
const width = Math.round((options.clip ? options.clip.width : viewport.width) * factor);
|
|
379
|
+
const height = Math.round((options.clip ? options.clip.height : options.fullPage ? fullPageHeight : viewport.height) * factor);
|
|
379
380
|
const type = options.type ?? "jpeg";
|
|
380
381
|
await this.b.after("driver.screenshot");
|
|
381
382
|
return { data: fakeImage(type, width, height).toString("base64"), mimeType: `image/${type}`, width, height };
|
package/dist/vault-session.d.ts
CHANGED
|
@@ -28,23 +28,20 @@ export declare function vaultRuntime(options: VaultOptions, track: (secret: stri
|
|
|
28
28
|
}): VaultRuntime | null;
|
|
29
29
|
/** Waits, up to `ms`, for a person to stop driving a session: a capture reads only once they have handed back. True when the gate is free. */
|
|
30
30
|
export declare function untilQuiet(gate: DrivingGate | null, ms?: number): Promise<boolean>;
|
|
31
|
-
/** `vaulted`: this session was created under the host's vault plan
|
|
32
|
-
* started with no target cannot be given one later, because its provider holds no context for it. `fresh`: nothing was kept, so a new context was made and its id is
|
|
33
|
-
* given to the vault right after the create (a restart then still finds it). */
|
|
31
|
+
/** `vaulted`: this session was created under the host's vault plan, with a target. */
|
|
34
32
|
export type RestorePlan = {
|
|
35
33
|
spec: SessionSpec;
|
|
36
34
|
afterAttach: ((target: AttachTarget) => Promise<void>) | null;
|
|
37
35
|
vaulted: boolean;
|
|
38
|
-
fresh: boolean;
|
|
39
36
|
/** Set when the vault may hold a saved sign-in this session did not take (the read failed, or what it holds could not be used here): this session is NOT captured, so it
|
|
40
37
|
* can never replace what is saved. The text is the warning given once at the first capture. */
|
|
41
38
|
holdBack?: string;
|
|
42
39
|
};
|
|
43
|
-
/** What the create does with the vault:
|
|
44
|
-
*
|
|
40
|
+
/** What the create does with the vault: a step that runs after the browser is attached and before the driver is (a local Chrome's cookies and local storage).
|
|
41
|
+
* The spec is the one given, and the record the adapter stores is made from it. */
|
|
45
42
|
export declare function planRestore(rt: VaultRuntime | null, target: VaultTarget | undefined, provider: BrowserProvider, spec: SessionSpec): Promise<RestorePlan>;
|
|
46
43
|
export type CaptureOptions = {
|
|
47
|
-
/** Whether the session was created under the vault plan (RestorePlan.vaulted).
|
|
44
|
+
/** Whether the session was created under the vault plan (RestorePlan.vaulted). */
|
|
48
45
|
vaulted: boolean;
|
|
49
46
|
/** The session's driving gate, read when the capture runs: a person who begins driving while the browser is being read voids that read. */
|
|
50
47
|
gate?: () => DrivingGate | null;
|
package/dist/vault-session.js
CHANGED
|
@@ -1,13 +1,11 @@
|
|
|
1
1
|
// How an adapter uses a host's session vault (core/vault.ts): restore a kept sign-in when a session is created, before the driver attaches, and capture
|
|
2
|
-
// it when the session is released or a person hands it back.
|
|
3
|
-
//
|
|
2
|
+
// it when the session is released or a person hands it back. Only a local Chrome's state is kept (its cookies and local storage, over CDP). The state
|
|
3
|
+
// stays in memory and crosses only the host's port: nothing here logs a value. A restore or capture that fails never fails the browser: the session
|
|
4
4
|
// starts signed out, or ends without a fresh capture, and a process warning says which, with no value in it.
|
|
5
|
-
import { randomBytes } from "node:crypto";
|
|
6
5
|
import { BrowserFailureError } from "./core/custody.js";
|
|
7
6
|
import { browserFailure } from "./core/failures.js";
|
|
8
|
-
import { MIN_REDACTED_VALUE_LENGTH } from "./core/redact.js";
|
|
9
7
|
import { keptFor } from "./core/driving.js";
|
|
10
|
-
import { clampSessionCookieAgeMs,
|
|
8
|
+
import { clampSessionCookieAgeMs, vaultTarget } from "./core/vault.js";
|
|
11
9
|
import { captureCdpState, connectCdp, restoreCdpState } from "./providers/cdp-session.js";
|
|
12
10
|
/** `null` when the host gave no vault. A bad age cap throws here, so a host learns at setup. */
|
|
13
11
|
export function vaultRuntime(options, track, warn, now = () => new Date(), limits = {}) {
|
|
@@ -37,21 +35,12 @@ async function within(work, ms, onTimeout = () => { }) {
|
|
|
37
35
|
}
|
|
38
36
|
}
|
|
39
37
|
const refused = (message) => new BrowserFailureError(browserFailure("refused", message));
|
|
40
|
-
/** A secret too short for the redactor to scrub is not used as one: the redactor ignores values under its minimum, so it would leak. */
|
|
41
|
-
function trackSecret(rt, secret, what) {
|
|
42
|
-
if (secret.length < MIN_REDACTED_VALUE_LENGTH) {
|
|
43
|
-
rt.warn(`the session vault's ${what} is too short for the redactor to scrub, so it is not used`);
|
|
44
|
-
return false;
|
|
45
|
-
}
|
|
46
|
-
rt.track(secret);
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
38
|
const HELD_FAILED = "the vault could not be read at the start, so a saved sign-in may exist under this key and is left untouched: this session's sign-in is not captured";
|
|
50
39
|
const HELD_UNUSED = "the vault holds a saved sign-in this session could not use, and it is left untouched: this session's sign-in is not captured";
|
|
51
|
-
/** What the create does with the vault:
|
|
52
|
-
*
|
|
40
|
+
/** What the create does with the vault: a step that runs after the browser is attached and before the driver is (a local Chrome's cookies and local storage).
|
|
41
|
+
* The spec is the one given, and the record the adapter stores is made from it. */
|
|
53
42
|
export async function planRestore(rt, target, provider, spec) {
|
|
54
|
-
const plain = { spec, afterAttach: null, vaulted: false
|
|
43
|
+
const plain = { spec, afterAttach: null, vaulted: false };
|
|
55
44
|
if (!rt || !target)
|
|
56
45
|
return plain;
|
|
57
46
|
let checked;
|
|
@@ -66,8 +55,6 @@ export async function planRestore(rt, target, provider, spec) {
|
|
|
66
55
|
rt.warn("this browser provider cannot keep a session in a vault (a Chrome attached by endpoint is offered only when the host sets ownBrowser: true), so nothing was restored or will be captured");
|
|
67
56
|
return plain;
|
|
68
57
|
}
|
|
69
|
-
if (vault.kind === "context" && vault.contextIdsInClear)
|
|
70
|
-
throw refused("browser vault: this provider writes its context ids to a clear file, so a vault cannot use it. Give it a profile store that keeps ids in memory (memoryProfileStore). No session was started.");
|
|
71
58
|
// A vault that stops answering never holds the session back: it starts signed out.
|
|
72
59
|
let kept = null;
|
|
73
60
|
let holdBack;
|
|
@@ -78,40 +65,17 @@ export async function planRestore(rt, target, provider, spec) {
|
|
|
78
65
|
holdBack = HELD_FAILED;
|
|
79
66
|
rt.warn(`the session vault could not restore (${kindOf(error)}); the session starts signed out`);
|
|
80
67
|
}
|
|
81
|
-
if (vault.kind === "context") {
|
|
82
|
-
if (kept && (kept.kind !== "provider-context" || kept.provider !== vault.provider)) {
|
|
83
|
-
rt.warn(`the vault holds a ${kept.kind} state this ${vault.provider} provider cannot use; it was ignored`);
|
|
84
|
-
kept = null;
|
|
85
|
-
holdBack = HELD_UNUSED;
|
|
86
|
-
}
|
|
87
|
-
// A context is a whole browser profile: it comes back only for a request that covers every origin it was saved for, never for some of them.
|
|
88
|
-
if (kept?.kind === "provider-context" && !coversEveryOrigin(checked.origins, kept.origins)) {
|
|
89
|
-
rt.warn("the vault holds a context whose saved origins this request does not cover every origin of (or records none); it was not restored");
|
|
90
|
-
kept = null;
|
|
91
|
-
holdBack = HELD_UNUSED;
|
|
92
|
-
}
|
|
93
|
-
if (kept?.kind === "provider-context" && !trackSecret(rt, kept.contextId, "context id")) {
|
|
94
|
-
kept = null;
|
|
95
|
-
holdBack = HELD_UNUSED;
|
|
96
|
-
}
|
|
97
|
-
if (kept?.kind === "provider-context")
|
|
98
|
-
return { spec: vault.provider === "browserbase" ? { ...spec, contextId: kept.contextId, profile: undefined } : { ...spec, profile: { name: kept.contextId, save: true } }, afterAttach: null, vaulted: true, fresh: false };
|
|
99
|
-
// A saved sign-in may exist that this session did not take: nothing persists for it, and it is never captured.
|
|
100
|
-
if (holdBack)
|
|
101
|
-
return { spec, afterAttach: null, vaulted: true, fresh: false, holdBack };
|
|
102
|
-
// Nothing kept: a context that persists is made for this session, its id held in memory and given to the vault right after the create.
|
|
103
|
-
return { spec: { ...spec, contextId: undefined, profile: { name: `vault-${randomBytes(9).toString("hex")}`, save: true } }, afterAttach: null, vaulted: true, fresh: true };
|
|
104
|
-
}
|
|
105
68
|
if (!kept)
|
|
106
69
|
return { ...plain, vaulted: true, ...(holdBack ? { holdBack } : {}) };
|
|
107
|
-
|
|
108
|
-
|
|
70
|
+
// A host's vault may hold a state of a kind this package does not keep (a hosted vendor's context, from before): left untouched, never replaced.
|
|
71
|
+
const kind = kept.kind;
|
|
72
|
+
if (kind !== "cdp") {
|
|
73
|
+
rt.warn(`the vault holds a ${typeof kind === "string" ? kind.slice(0, 40) : "different"} state a local Chrome cannot use; it was ignored`);
|
|
109
74
|
return { ...plain, vaulted: true, holdBack: HELD_UNUSED };
|
|
110
75
|
}
|
|
111
76
|
return {
|
|
112
77
|
spec,
|
|
113
78
|
vaulted: true,
|
|
114
|
-
fresh: false,
|
|
115
79
|
afterAttach: async (attached) => {
|
|
116
80
|
let link;
|
|
117
81
|
try {
|
|
@@ -148,13 +112,6 @@ export function captureFor(rt, target, provider, ref, options = { vaulted: true
|
|
|
148
112
|
}
|
|
149
113
|
return;
|
|
150
114
|
}
|
|
151
|
-
if (vault.kind === "context" && !options.vaulted) {
|
|
152
|
-
if (!warnedLate) {
|
|
153
|
-
warnedLate = true;
|
|
154
|
-
rt.warn("this session started with no vault target, so its provider holds no saved context for it: its sign-in cannot be kept. Set the target before the session starts");
|
|
155
|
-
}
|
|
156
|
-
return;
|
|
157
|
-
}
|
|
158
115
|
const stop = new AbortController();
|
|
159
116
|
let link;
|
|
160
117
|
// Numbered when it starts: an older capture that is still reading when a newer one of the same key begins writes nothing.
|
|
@@ -168,38 +125,26 @@ export function captureFor(rt, target, provider, ref, options = { vaulted: true
|
|
|
168
125
|
if ((rt.latest.get(key) ?? 0) < attempt)
|
|
169
126
|
rt.latest.set(key, attempt);
|
|
170
127
|
const capturedAt = rt.now();
|
|
128
|
+
const gate = options.gate?.() ?? null;
|
|
129
|
+
let interrupted = false;
|
|
171
130
|
let state;
|
|
172
|
-
if (
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
131
|
+
const off = gate?.onChange((now) => { if (now === "person")
|
|
132
|
+
interrupted = true; });
|
|
133
|
+
try {
|
|
134
|
+
const attached = await provider.attach(ref, stop.signal);
|
|
135
|
+
link = await connectCdp(attached.sdkCdpUrl);
|
|
136
|
+
if (stop.signal.aborted) {
|
|
137
|
+
link.close();
|
|
176
138
|
return;
|
|
177
139
|
}
|
|
178
|
-
|
|
179
|
-
return;
|
|
180
|
-
state = { kind: "provider-context", capturedAt: capturedAt.toISOString(), provider: vault.provider, contextId: id, origins: [...checked.origins] };
|
|
140
|
+
state = await captureCdpState(link, checked.origins, capturedAt);
|
|
181
141
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
const attached = await provider.attach(ref, stop.signal);
|
|
189
|
-
link = await connectCdp(attached.sdkCdpUrl);
|
|
190
|
-
if (stop.signal.aborted) {
|
|
191
|
-
link.close();
|
|
192
|
-
return;
|
|
193
|
-
}
|
|
194
|
-
state = await captureCdpState(link, checked.origins, capturedAt);
|
|
195
|
-
}
|
|
196
|
-
finally {
|
|
197
|
-
off?.();
|
|
198
|
-
}
|
|
199
|
-
if (interrupted || (gate && keptFor(gate) === "person_driving")) {
|
|
200
|
-
rt.warn("a person began driving while the session was being read, so that capture was discarded; the last capture stands");
|
|
201
|
-
return;
|
|
202
|
-
}
|
|
142
|
+
finally {
|
|
143
|
+
off?.();
|
|
144
|
+
}
|
|
145
|
+
if (interrupted || (gate && keptFor(gate) === "person_driving")) {
|
|
146
|
+
rt.warn("a person began driving while the session was being read, so that capture was discarded; the last capture stands");
|
|
147
|
+
return;
|
|
203
148
|
}
|
|
204
149
|
// Nothing is written once the deadline has passed or a newer capture of this key has begun: an older read never replaces a newer one.
|
|
205
150
|
if (stop.signal.aborted || rt.latest.get(key) !== attempt)
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type ScreenshotOptions } from "../../core/images.js";
|
|
1
2
|
import type { CDP } from "./cdp.js";
|
|
2
3
|
/** The schemes a page is sent to: the web and the blank page, never a file of this machine or the browser's own pages. */
|
|
3
4
|
export declare const NAVIGABLE: RegExp;
|
|
@@ -23,16 +24,6 @@ export declare class Page {
|
|
|
23
24
|
}): Promise<void>;
|
|
24
25
|
clickAt(x: number, y: number): Promise<void>;
|
|
25
26
|
moveTo(x: number, y: number): Promise<void>;
|
|
26
|
-
/**
|
|
27
|
-
screenshot(options?:
|
|
28
|
-
type?: "png" | "jpeg";
|
|
29
|
-
quality?: number;
|
|
30
|
-
fullPage?: boolean;
|
|
31
|
-
clip?: {
|
|
32
|
-
x: number;
|
|
33
|
-
y: number;
|
|
34
|
-
width: number;
|
|
35
|
-
height: number;
|
|
36
|
-
};
|
|
37
|
-
}): Promise<string>;
|
|
27
|
+
/** The driver's options as core/images.ts captureParams makes them CDP's, on the page's layout as it is now. */
|
|
28
|
+
screenshot(options?: ScreenshotOptions): Promise<string>;
|
|
38
29
|
}
|
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// e7007f219b10fa2c2baae1bf3e2f902a5a2706fd, src/page.ts. MIT License, Copyright (c) 2026 Browser Use contributors; the
|
|
3
3
|
// license's full text is in this package's NOTICE, and UPSTREAM.json beside this file records the source.
|
|
4
4
|
// Changes: the Page class only (no Tabs, no snapshot of its own: ax.ts's is the driver's); goto refuses a scheme other
|
|
5
|
-
// than http, https and about:blank; screenshot takes the driver's format, quality, clip
|
|
6
|
-
// CDP params and results.
|
|
5
|
+
// than http, https and about:blank; screenshot takes the driver's options (format, quality, clip, full page and scale),
|
|
6
|
+
// sent as core/images.ts captureParams makes them; untyped CDP params and results.
|
|
7
7
|
import { setTimeout as delay } from "node:timers/promises";
|
|
8
|
+
import { captureParams } from "../../core/images.js";
|
|
8
9
|
const contextLost = /Execution context was destroyed|Cannot find context|Cannot find default execution context/;
|
|
9
10
|
/** The schemes a page is sent to: the web and the blank page, never a file of this machine or the browser's own pages. */
|
|
10
11
|
export const NAVIGABLE = /^(https?:\/\/|about:blank$)/i;
|
|
@@ -89,24 +90,10 @@ export class Page {
|
|
|
89
90
|
throw new Error("Coordinates must be finite.");
|
|
90
91
|
await this.cdp("Input.dispatchMouseEvent", { type: "mouseMoved", x, y });
|
|
91
92
|
}
|
|
92
|
-
/**
|
|
93
|
+
/** The driver's options as core/images.ts captureParams makes them CDP's, on the page's layout as it is now. */
|
|
93
94
|
async screenshot(options = {}) {
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
if (options.clip) {
|
|
97
|
-
const scroll = await this.evaluate(() => ({ x: scrollX, y: scrollY })).catch(() => ({ x: 0, y: 0 }));
|
|
98
|
-
clip = { ...options.clip, x: options.clip.x + scroll.x, y: options.clip.y + scroll.y, scale: 1 };
|
|
99
|
-
}
|
|
100
|
-
else if (options.fullPage) {
|
|
101
|
-
const { cssContentSize } = await this.cdp("Page.getLayoutMetrics");
|
|
102
|
-
clip = { x: 0, y: 0, width: Math.ceil(cssContentSize.width), height: Math.ceil(cssContentSize.height), scale: 1 };
|
|
103
|
-
}
|
|
104
|
-
const { data } = await this.cdp("Page.captureScreenshot", {
|
|
105
|
-
format: type,
|
|
106
|
-
...(type === "jpeg" && options.quality !== undefined ? { quality: Math.round(options.quality) } : {}),
|
|
107
|
-
...(options.fullPage && !options.clip ? { captureBeyondViewport: true } : {}),
|
|
108
|
-
...(clip ? { clip } : {}),
|
|
109
|
-
});
|
|
95
|
+
const layout = await this.cdp("Page.getLayoutMetrics");
|
|
96
|
+
const { data } = await this.cdp("Page.captureScreenshot", captureParams(options, layout));
|
|
110
97
|
return data;
|
|
111
98
|
}
|
|
112
99
|
}
|
package/package.json
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/pi-browser",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.351",
|
|
4
4
|
"description": "Your agent gets its own browser, and you can take over and hand it back.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-durable",
|
|
7
7
|
"browser",
|
|
8
|
-
"stagehand"
|
|
9
|
-
"browserbase"
|
|
8
|
+
"stagehand"
|
|
10
9
|
],
|
|
11
10
|
"type": "module",
|
|
12
11
|
"license": "Apache-2.0",
|
|
@@ -27,10 +26,6 @@
|
|
|
27
26
|
"types": "./dist/live-view/index.d.ts",
|
|
28
27
|
"import": "./dist/live-view/index.js"
|
|
29
28
|
},
|
|
30
|
-
"./providers/browserbase": {
|
|
31
|
-
"types": "./dist/providers/browserbase.d.ts",
|
|
32
|
-
"import": "./dist/providers/browserbase.js"
|
|
33
|
-
},
|
|
34
29
|
"./providers/cdp": {
|
|
35
30
|
"types": "./dist/providers/cdp.d.ts",
|
|
36
31
|
"import": "./dist/providers/cdp.js"
|
|
@@ -43,10 +38,6 @@
|
|
|
43
38
|
"types": "./dist/providers/chrome-args.d.ts",
|
|
44
39
|
"import": "./dist/providers/chrome-args.js"
|
|
45
40
|
},
|
|
46
|
-
"./providers/kernel": {
|
|
47
|
-
"types": "./dist/providers/kernel.d.ts",
|
|
48
|
-
"import": "./dist/providers/kernel.js"
|
|
49
|
-
},
|
|
50
41
|
"./driver/stagehand": {
|
|
51
42
|
"types": "./dist/driver/stagehand.d.ts",
|
|
52
43
|
"import": "./dist/driver/stagehand.js"
|
|
@@ -79,7 +70,7 @@
|
|
|
79
70
|
"verify:tarball": "node scripts/verify-tarball.mjs"
|
|
80
71
|
},
|
|
81
72
|
"dependencies": {
|
|
82
|
-
"@browserbasehq/stagehand": "
|
|
73
|
+
"@browserbasehq/stagehand": "4.4.0",
|
|
83
74
|
"node-html-markdown": "^2.0.0",
|
|
84
75
|
"node-html-parser": "^6.1.13",
|
|
85
76
|
"typebox": "1.3.27",
|
|
@@ -87,14 +78,10 @@
|
|
|
87
78
|
"zod": "~4.6.6"
|
|
88
79
|
},
|
|
89
80
|
"peerDependencies": {
|
|
90
|
-
"@
|
|
91
|
-
"@earendil-works/
|
|
92
|
-
"@earendil-works/pi-durable": "1.5.0"
|
|
81
|
+
"@earendil-works/chord": "1.5.2",
|
|
82
|
+
"@earendil-works/pi-durable": "1.5.2"
|
|
93
83
|
},
|
|
94
84
|
"peerDependenciesMeta": {
|
|
95
|
-
"@browserbasehq/sdk": {
|
|
96
|
-
"optional": true
|
|
97
|
-
},
|
|
98
85
|
"@earendil-works/chord": {
|
|
99
86
|
"optional": true
|
|
100
87
|
},
|
|
@@ -103,9 +90,9 @@
|
|
|
103
90
|
}
|
|
104
91
|
},
|
|
105
92
|
"devDependencies": {
|
|
106
|
-
"@earendil-works/chord": "1.5.
|
|
107
|
-
"@earendil-works/pi-ai": "1.5.
|
|
108
|
-
"@earendil-works/pi-durable": "1.5.
|
|
93
|
+
"@earendil-works/chord": "1.5.2",
|
|
94
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
95
|
+
"@earendil-works/pi-durable": "1.5.2"
|
|
109
96
|
},
|
|
110
97
|
"repository": {
|
|
111
98
|
"type": "git",
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
|
|
2
|
-
export declare function rewriteConnectUrl(connectUrl: string, connectBaseUrl: string | undefined | null): string;
|
|
3
|
-
/** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
|
|
4
|
-
* --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
|
|
5
|
-
export declare function browserbaseNoProxyHosts(env: NodeJS.ProcessEnv): string[];
|
|
6
|
-
export declare function applyBrowserbaseNoProxy(env?: NodeJS.ProcessEnv): string[];
|
|
7
|
-
/** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
|
|
8
|
-
* it. */
|
|
9
|
-
export declare function bindConnectDial(connectUrl: string, connectBaseUrl: string | null): void;
|
|
10
|
-
export declare function unbindConnectDial(connectUrl: string): void;
|
|
11
|
-
export declare function connectDialUrl(url: string): string;
|
|
12
|
-
export declare function installWebSocketWrapper(): void;
|
|
@@ -1,95 +0,0 @@
|
|
|
1
|
-
import { browserbaseHoldings } from "./shared.js";
|
|
2
|
-
/** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
|
|
3
|
-
export function rewriteConnectUrl(connectUrl, connectBaseUrl) {
|
|
4
|
-
if (!connectUrl || !connectBaseUrl)
|
|
5
|
-
return connectUrl;
|
|
6
|
-
try {
|
|
7
|
-
const target = new URL(connectBaseUrl);
|
|
8
|
-
const u = new URL(connectUrl);
|
|
9
|
-
if (!/(?:^|\.)browserbase\.com$/i.test(u.hostname))
|
|
10
|
-
return connectUrl;
|
|
11
|
-
u.protocol = target.protocol;
|
|
12
|
-
u.host = target.host;
|
|
13
|
-
u.pathname = target.pathname.replace(/\/$/, "") + u.pathname;
|
|
14
|
-
return u.toString();
|
|
15
|
-
}
|
|
16
|
-
catch {
|
|
17
|
-
return connectUrl;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
20
|
-
/** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
|
|
21
|
-
* --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
|
|
22
|
-
export function browserbaseNoProxyHosts(env) {
|
|
23
|
-
const hosts = new Set();
|
|
24
|
-
for (const key of ["BROWSERBASE_BASE_URL", "BROWSERBASE_CONNECT_BASE_URL"]) {
|
|
25
|
-
const raw = String(env[key] || "").trim();
|
|
26
|
-
if (!raw)
|
|
27
|
-
continue;
|
|
28
|
-
try {
|
|
29
|
-
hosts.add(new URL(raw).hostname);
|
|
30
|
-
}
|
|
31
|
-
catch { }
|
|
32
|
-
}
|
|
33
|
-
if (!String(env.BROWSERBASE_CONNECT_BASE_URL || "").trim())
|
|
34
|
-
hosts.add(".browserbase.com");
|
|
35
|
-
return [...hosts];
|
|
36
|
-
}
|
|
37
|
-
export function applyBrowserbaseNoProxy(env = process.env) {
|
|
38
|
-
const hosts = browserbaseNoProxyHosts(env);
|
|
39
|
-
if (!hosts.length)
|
|
40
|
-
return hosts;
|
|
41
|
-
for (const target of env === process.env ? [env] : [env, process.env]) {
|
|
42
|
-
for (const key of ["NO_PROXY", "no_proxy"]) {
|
|
43
|
-
const merged = String(target[key] || "").split(",").map((h) => h.trim()).filter(Boolean);
|
|
44
|
-
for (const h of hosts)
|
|
45
|
-
if (!merged.includes(h))
|
|
46
|
-
merged.push(h);
|
|
47
|
-
target[key] = merged.join(",");
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
return hosts;
|
|
51
|
-
}
|
|
52
|
-
/** The driver keeps the raw connect URL (the extension in the cloud browser dials it back and reaches only
|
|
53
|
-
* Browserbase); this process's socket dials the proxy, so the rewrite happens at dial time, never in a record. */
|
|
54
|
-
/** Per-socket targets, so two providers with different proxies never send one's signed URL to the other's proxy. */
|
|
55
|
-
const { boundDials } = browserbaseHoldings;
|
|
56
|
-
/** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
|
|
57
|
-
* it. */
|
|
58
|
-
export function bindConnectDial(connectUrl, connectBaseUrl) {
|
|
59
|
-
const target = connectBaseUrl?.trim() ?? "";
|
|
60
|
-
const bound = boundDials.get(connectUrl);
|
|
61
|
-
if (bound !== undefined && bound !== target)
|
|
62
|
-
throw new Error("this Browserbase session is already attached through another credential proxy");
|
|
63
|
-
boundDials.set(connectUrl, target);
|
|
64
|
-
}
|
|
65
|
-
export function unbindConnectDial(connectUrl) {
|
|
66
|
-
boundDials.delete(connectUrl);
|
|
67
|
-
if (![...boundDials.values()].some(Boolean))
|
|
68
|
-
restoreWebSocket();
|
|
69
|
-
}
|
|
70
|
-
export function connectDialUrl(url) {
|
|
71
|
-
const bound = boundDials.get(url);
|
|
72
|
-
if (bound !== undefined)
|
|
73
|
-
return bound ? rewriteConnectUrl(url, bound) : url;
|
|
74
|
-
return url;
|
|
75
|
-
}
|
|
76
|
-
/** Wraps the process WebSocket only while a session is bound to a proxy; the native one returns with the last binding. A wrapper
|
|
77
|
-
* installed on top cannot be removed, so ours stays under it and, with no bindings, passes every URL through. */
|
|
78
|
-
let wrapped = null;
|
|
79
|
-
export function installWebSocketWrapper() {
|
|
80
|
-
if (typeof globalThis.WebSocket !== "function" || (wrapped && globalThis.WebSocket === wrapped.wrapper))
|
|
81
|
-
return;
|
|
82
|
-
const original = globalThis.WebSocket;
|
|
83
|
-
const wrapper = function (url, protocols) { return new original(connectDialUrl(String(url)), protocols); };
|
|
84
|
-
wrapper.prototype = original.prototype;
|
|
85
|
-
for (const k of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"])
|
|
86
|
-
wrapper[k] = original[k];
|
|
87
|
-
globalThis.WebSocket = wrapper;
|
|
88
|
-
wrapped = { original, wrapper };
|
|
89
|
-
}
|
|
90
|
-
function restoreWebSocket() {
|
|
91
|
-
if (!wrapped || globalThis.WebSocket !== wrapped.wrapper)
|
|
92
|
-
return;
|
|
93
|
-
globalThis.WebSocket = wrapped.original;
|
|
94
|
-
wrapped = null;
|
|
95
|
-
}
|