@parcha/pi-browser 0.1.0-beta.35 → 0.1.0-beta.36
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 +12 -0
- package/README.md +17 -22
- package/dist/core/driving-guard.d.ts +1 -1
- package/dist/core/driving-guard.js +1 -1
- package/dist/core/host.d.ts +1 -12
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/tools.js +4 -1
- 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/durable.d.ts +5 -0
- package/dist/durable.js +24 -5
- package/dist/index.d.ts +1 -0
- package/dist/index.js +3 -0
- 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.js +1 -1
- 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 +2 -15
- 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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
|
|
2
2
|
* profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
|
|
3
3
|
* while the old session is still being released) waits for the release; anyone else is refused. */
|
|
4
4
|
export declare function claimWriter(key: string, name: string, tag: string, owner: string, signal?: AbortSignal): Promise<void>;
|
|
@@ -7,17 +7,3 @@ export declare function claimWriter(key: string, name: string, tag: string, owne
|
|
|
7
7
|
export declare function noteWriter(tag: string, running: (signal: AbortSignal) => Promise<boolean>, settle?: () => Promise<void>): void;
|
|
8
8
|
export declare function freeWriter(tag: string): void;
|
|
9
9
|
export declare function isWriter(tag: string): boolean;
|
|
10
|
-
/** Context ids are not secrets, and Browserbase has no way to look a context up by name, so the name to id map is the host's.
|
|
11
|
-
* `resolve` returns the name's context, calling `make` only when there is none, and no two callers may both make one. */
|
|
12
|
-
export type ProfileStore = {
|
|
13
|
-
resolve(key: string, make: (signal: AbortSignal) => Promise<string>): Promise<string>;
|
|
14
|
-
/** True when the store writes the ids it holds to a clear file (the default one does). A session vault refuses a provider whose store does. */
|
|
15
|
-
readonly clear?: boolean;
|
|
16
|
-
};
|
|
17
|
-
/** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
|
|
18
|
-
export declare function memoryProfileStore(): ProfileStore;
|
|
19
|
-
/** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
|
|
20
|
-
* not this format, or cannot be read, is never overwritten. */
|
|
21
|
-
export declare function fileProfileStore(file?: string, options?: {
|
|
22
|
-
makeLimitMs?: number;
|
|
23
|
-
}): ProfileStore;
|
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
import { randomBytes } from "node:crypto";
|
|
2
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
3
|
-
import os from "node:os";
|
|
4
|
-
import path from "node:path";
|
|
5
1
|
import { refusedError } from "../core/custody.js";
|
|
6
|
-
import { withLock } from "../core/downloads.js";
|
|
7
2
|
import { profileHoldings } from "./shared.js";
|
|
8
3
|
const writers = profileHoldings.writers;
|
|
9
4
|
const WAIT_MS = 20_000;
|
|
@@ -31,7 +26,7 @@ async function waitFor(work, signal, ms) {
|
|
|
31
26
|
signal?.removeEventListener("abort", abort);
|
|
32
27
|
}
|
|
33
28
|
}
|
|
34
|
-
/**
|
|
29
|
+
/** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
|
|
35
30
|
* profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
|
|
36
31
|
* while the old session is still being released) waits for the release; anyone else is refused. */
|
|
37
32
|
export async function claimWriter(key, name, tag, owner, signal) {
|
|
@@ -74,61 +69,3 @@ export function isWriter(tag) {
|
|
|
74
69
|
return true;
|
|
75
70
|
return false;
|
|
76
71
|
}
|
|
77
|
-
/** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
|
|
78
|
-
export function memoryProfileStore() {
|
|
79
|
-
const ids = new Map();
|
|
80
|
-
return { clear: false, resolve: (key, make) => { let known = ids.get(key); if (!known) {
|
|
81
|
-
known = make(AbortSignal.timeout(20_000));
|
|
82
|
-
ids.set(key, known);
|
|
83
|
-
known.catch(() => ids.delete(key));
|
|
84
|
-
} return known; } };
|
|
85
|
-
}
|
|
86
|
-
const SCHEMA = "pi-browser.profiles.v1";
|
|
87
|
-
const defaultProfilesFile = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "pi-browser", "profiles.json");
|
|
88
|
-
const notOurs = (file) => new Error(`the profiles file ${path.basename(file)} is not a pi-browser profiles file, so it was left as it is`);
|
|
89
|
-
async function readProfiles(file) {
|
|
90
|
-
let text;
|
|
91
|
-
try {
|
|
92
|
-
text = await readFile(file, "utf8");
|
|
93
|
-
}
|
|
94
|
-
catch (error) {
|
|
95
|
-
if (error.code === "ENOENT")
|
|
96
|
-
return { schema: SCHEMA, contexts: {} };
|
|
97
|
-
throw error;
|
|
98
|
-
}
|
|
99
|
-
try {
|
|
100
|
-
const parsed = JSON.parse(text);
|
|
101
|
-
const contexts = parsed?.contexts;
|
|
102
|
-
if (parsed?.schema === SCHEMA && contexts && typeof contexts === "object" && !Array.isArray(contexts) && Object.values(contexts).every((id) => typeof id === "string" && id !== ""))
|
|
103
|
-
return parsed;
|
|
104
|
-
}
|
|
105
|
-
catch { /* not JSON */ }
|
|
106
|
-
throw notOurs(file);
|
|
107
|
-
}
|
|
108
|
-
/** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
|
|
109
|
-
* not this format, or cannot be read, is never overwritten. */
|
|
110
|
-
export function fileProfileStore(file = defaultProfilesFile(), options = {}) {
|
|
111
|
-
// The lock is taken over once it is 30 s old (core/downloads.ts's rule), so `make` must end well before: a slower one is cut here, never left
|
|
112
|
-
// to run past the lock that protects it.
|
|
113
|
-
const makeLimitMs = options.makeLimitMs ?? 20_000;
|
|
114
|
-
return {
|
|
115
|
-
clear: true,
|
|
116
|
-
async resolve(key, make) {
|
|
117
|
-
await mkdir(path.dirname(file), { recursive: true });
|
|
118
|
-
return withLock(`${file}.lock`, async () => {
|
|
119
|
-
const current = await readProfiles(file);
|
|
120
|
-
const known = current.contexts[key];
|
|
121
|
-
if (known)
|
|
122
|
-
return known;
|
|
123
|
-
const limit = AbortSignal.timeout(makeLimitMs);
|
|
124
|
-
// Listening before `make` does, so the cut's own words are what the caller hears.
|
|
125
|
-
const cut = new Promise((_, reject) => limit.addEventListener("abort", () => reject(new Error(`making the profile's context took longer than ${makeLimitMs} ms, so it was cut before the profiles file's lock could be taken over`)), { once: true }));
|
|
126
|
-
const id = await Promise.race([make(limit), cut]);
|
|
127
|
-
const next = `${file}.${randomBytes(4).toString("hex")}.tmp`;
|
|
128
|
-
await writeFile(next, `${JSON.stringify({ schema: SCHEMA, contexts: { ...current.contexts, [key]: id } }, null, 2)}\n`);
|
|
129
|
-
await rename(next, file);
|
|
130
|
-
return id;
|
|
131
|
-
}, "the profiles file");
|
|
132
|
-
},
|
|
133
|
-
};
|
|
134
|
-
}
|
|
@@ -1,50 +1,5 @@
|
|
|
1
|
-
import type { ResourceStatus } from "../core/lease.js";
|
|
2
|
-
import type { CdpSession } from "./cdp-call.js";
|
|
3
1
|
export declare const nonEmpty: (v: unknown) => string;
|
|
4
|
-
/**
|
|
5
|
-
export declare const tagValue: (v: string) => string;
|
|
6
|
-
export declare function assertTag(tag: string): void;
|
|
7
|
-
export declare function extensionArchive(): string;
|
|
8
|
-
export declare const accountKey: (origin: string, apiKey: string) => string;
|
|
9
|
-
export declare const defaultSleep: (ms: number) => Promise<void>;
|
|
10
|
-
export declare const DEFAULT_CONFIRM: {
|
|
11
|
-
polls: number;
|
|
12
|
-
intervalMs: number;
|
|
13
|
-
};
|
|
14
|
-
/** The work itself goes on when `signal` fires: another caller may be waiting for it. */
|
|
15
|
-
export declare function untilAborted<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
|
|
16
|
-
/** One upload per process and account; a failed upload is forgotten so the next create tries again. */
|
|
17
|
-
export declare function uploadOnce<T>(uploads: Map<string, Promise<T>>, account: string, upload: () => Promise<T>): Promise<T>;
|
|
18
|
-
/** The request is asked twice at most; released means the provider says the session is no longer running, not that the
|
|
19
|
-
* request was sent. `request` answers "gone" when the provider no longer knows the session. */
|
|
20
|
-
export declare function releaseAndConfirm(o: {
|
|
21
|
-
request: () => Promise<"gone" | void>;
|
|
22
|
-
status: () => Promise<ResourceStatus>;
|
|
23
|
-
forget: () => void | Promise<void>;
|
|
24
|
-
confirm: {
|
|
25
|
-
polls: number;
|
|
26
|
-
intervalMs: number;
|
|
27
|
-
};
|
|
28
|
-
sleep: (ms: number) => Promise<void>;
|
|
29
|
-
stillRunning: string;
|
|
30
|
-
}): Promise<void>;
|
|
31
|
-
export declare const browserbaseHoldings: {
|
|
32
|
-
connectUrls: Map<string, string>;
|
|
33
|
-
settings: Map<string, Pick<CdpSession, "close" | "open">>;
|
|
34
|
-
opening: Map<string, Promise<void>>;
|
|
35
|
-
uploads: Map<string, Promise<string>>;
|
|
36
|
-
boundDials: Map<string, string>;
|
|
37
|
-
};
|
|
38
|
-
export declare const kernelHoldings: {
|
|
39
|
-
cdpUrls: Map<string, string>;
|
|
40
|
-
liveUrls: Map<string, string>;
|
|
41
|
-
uploads: Map<string, Promise<{
|
|
42
|
-
id: string;
|
|
43
|
-
} | {
|
|
44
|
-
name: string;
|
|
45
|
-
}>>;
|
|
46
|
-
};
|
|
47
|
-
/** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
|
|
2
|
+
/** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
|
|
48
3
|
export declare const profileHoldings: {
|
|
49
4
|
writers: Map<string, {
|
|
50
5
|
tag: string;
|
|
@@ -53,4 +8,3 @@ export declare const profileHoldings: {
|
|
|
53
8
|
settle?: () => Promise<void>;
|
|
54
9
|
}>;
|
|
55
10
|
};
|
|
56
|
-
export declare function resetProviderHoldings(): void;
|
package/dist/providers/shared.js
CHANGED
|
@@ -1,86 +1,5 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
|
-
import path from "node:path";
|
|
3
|
-
import { fileURLToPath } from "node:url";
|
|
4
1
|
export const nonEmpty = (v) => String(v ?? "").trim();
|
|
5
|
-
/**
|
|
6
|
-
export const tagValue = (v) => String(v || "").replace(/[^A-Za-z0-9._:-]+/g, "_").slice(0, 60) || "unknown";
|
|
7
|
-
export function assertTag(tag) {
|
|
8
|
-
if (!/^[A-Za-z0-9_.-]+$/.test(tag))
|
|
9
|
-
throw new Error("a session tag is [A-Za-z0-9_.-]");
|
|
10
|
-
}
|
|
11
|
-
export function extensionArchive() {
|
|
12
|
-
return nonEmpty(process.env.STAGEHAND_EXTENSION_ARCHIVE_PATH) || path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "assets", "stagehand-extension.zip");
|
|
13
|
-
}
|
|
14
|
-
export const accountKey = (origin, apiKey) => `${origin}|${createHash("sha256").update(apiKey).digest("hex").slice(0, 16)}`;
|
|
15
|
-
export const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
16
|
-
export const DEFAULT_CONFIRM = { polls: 6, intervalMs: 500 };
|
|
17
|
-
/** The work itself goes on when `signal` fires: another caller may be waiting for it. */
|
|
18
|
-
export function untilAborted(work, signal) {
|
|
19
|
-
if (!signal)
|
|
20
|
-
return work;
|
|
21
|
-
return new Promise((resolve, reject) => {
|
|
22
|
-
const abort = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
|
|
23
|
-
// The outcome is taken first, so a failure after the caller left is handled, never unhandled.
|
|
24
|
-
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
25
|
-
if (signal.aborted)
|
|
26
|
-
return abort();
|
|
27
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
28
|
-
});
|
|
29
|
-
}
|
|
30
|
-
/** One upload per process and account; a failed upload is forgotten so the next create tries again. */
|
|
31
|
-
export function uploadOnce(uploads, account, upload) {
|
|
32
|
-
let up = uploads.get(account);
|
|
33
|
-
if (!up) {
|
|
34
|
-
up = upload();
|
|
35
|
-
uploads.set(account, up);
|
|
36
|
-
up.catch(() => uploads.delete(account));
|
|
37
|
-
}
|
|
38
|
-
return up;
|
|
39
|
-
}
|
|
40
|
-
/** The request is asked twice at most; released means the provider says the session is no longer running, not that the
|
|
41
|
-
* request was sent. `request` answers "gone" when the provider no longer knows the session. */
|
|
42
|
-
export async function releaseAndConfirm(o) {
|
|
43
|
-
let failure;
|
|
44
|
-
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
45
|
-
try {
|
|
46
|
-
if ((await o.request()) === "gone")
|
|
47
|
-
return o.forget();
|
|
48
|
-
failure = undefined;
|
|
49
|
-
break;
|
|
50
|
-
}
|
|
51
|
-
catch (error) {
|
|
52
|
-
failure = error;
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
for (let poll = 0;; poll += 1) {
|
|
56
|
-
const now = await o.status();
|
|
57
|
-
if (now !== "running" && now !== "pending")
|
|
58
|
-
return o.forget();
|
|
59
|
-
if (poll >= o.confirm.polls)
|
|
60
|
-
throw failure ?? new Error(o.stillRunning);
|
|
61
|
-
await o.sleep(o.confirm.intervalMs);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
// Process-wide on purpose: a provider built later (custody builds one for the release) must still close the attach socket,
|
|
65
|
-
// drop the dial binding and reuse the account's upload. The URLs carry tokens and are never written anywhere.
|
|
66
|
-
export const browserbaseHoldings = {
|
|
67
|
-
connectUrls: new Map(),
|
|
68
|
-
settings: new Map(),
|
|
69
|
-
opening: new Map(),
|
|
70
|
-
uploads: new Map(),
|
|
71
|
-
boundDials: new Map(),
|
|
72
|
-
};
|
|
73
|
-
export const kernelHoldings = {
|
|
74
|
-
cdpUrls: new Map(),
|
|
75
|
-
liveUrls: new Map(),
|
|
76
|
-
uploads: new Map(),
|
|
77
|
-
};
|
|
78
|
-
/** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
|
|
2
|
+
/** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
|
|
79
3
|
export const profileHoldings = {
|
|
80
4
|
writers: new Map(),
|
|
81
5
|
};
|
|
82
|
-
export function resetProviderHoldings() {
|
|
83
|
-
for (const holdings of [browserbaseHoldings, kernelHoldings, profileHoldings])
|
|
84
|
-
for (const map of Object.values(holdings))
|
|
85
|
-
map.clear();
|
|
86
|
-
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to.
|
|
6
6
|
import { cp, readFile, writeFile } from "node:fs/promises";
|
|
7
7
|
import path from "node:path";
|
|
8
|
-
import { cdpCall } from "
|
|
8
|
+
import { cdpCall } from "../core/cdp-call.js";
|
|
9
9
|
import { extensionDirectory, extensionOrigin } from "./chrome-args.js";
|
|
10
10
|
export const COPY = "stagehand-extension";
|
|
11
11
|
/** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
|
|
@@ -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.36",
|
|
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"
|
|
@@ -87,14 +78,10 @@
|
|
|
87
78
|
"zod": "~4.6.6"
|
|
88
79
|
},
|
|
89
80
|
"peerDependencies": {
|
|
90
|
-
"@browserbasehq/sdk": ">=2.20.0 <3",
|
|
91
81
|
"@earendil-works/chord": "1.5.0",
|
|
92
82
|
"@earendil-works/pi-durable": "1.5.0"
|
|
93
83
|
},
|
|
94
84
|
"peerDependenciesMeta": {
|
|
95
|
-
"@browserbasehq/sdk": {
|
|
96
|
-
"optional": true
|
|
97
|
-
},
|
|
98
85
|
"@earendil-works/chord": {
|
|
99
86
|
"optional": true
|
|
100
87
|
},
|