@parcha/pi-browser 0.1.0-beta.35 → 0.1.0-beta.350
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
package/dist/core/custody.js
CHANGED
|
@@ -6,11 +6,23 @@ import { startSpent } from "./usage.js";
|
|
|
6
6
|
* for the detach): a shorter wait could return while the client is still attached, and the next attach to the browser is
|
|
7
7
|
* refused until it has let go. */
|
|
8
8
|
export const DRIVER_CLOSE_MS = 25_000;
|
|
9
|
+
/** How long a "close" release lets its drivers' close run before it ends the session: a live browser
|
|
10
|
+
* answers Stagehand's close and detach in well under a second, and one ended first leaves them nothing to answer. A
|
|
11
|
+
* close that has not come back by then is not waited for, so ending the session is never held up past this. */
|
|
12
|
+
export const DRIVER_ACK_BEFORE_KILL_MS = 2_000;
|
|
13
|
+
/** Resolves once `work` settles, either way, or after `ms`, whichever is first; its timer goes with it. */
|
|
14
|
+
export async function settledWithin(work, ms) {
|
|
15
|
+
let timer;
|
|
16
|
+
try {
|
|
17
|
+
await Promise.race([work.then(() => undefined, () => undefined), new Promise((resolve) => { timer = setTimeout(resolve, ms); })]);
|
|
18
|
+
}
|
|
19
|
+
finally {
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
9
23
|
/** A close that fails is not the caller's: the session goes on or is released either way. */
|
|
10
24
|
export async function closeDriver(driver) {
|
|
11
|
-
|
|
12
|
-
await Promise.race([driver.close().catch(() => undefined), new Promise((resolve) => { timer = setTimeout(resolve, DRIVER_CLOSE_MS); })]);
|
|
13
|
-
clearTimeout(timer);
|
|
25
|
+
await settledWithin(driver.close(), DRIVER_CLOSE_MS);
|
|
14
26
|
}
|
|
15
27
|
export class BrowserFailureError extends Error {
|
|
16
28
|
failure;
|
package/dist/core/downloads.d.ts
CHANGED
|
@@ -4,6 +4,36 @@ export declare const DOWNLOADS_DIR = "downloads";
|
|
|
4
4
|
export declare const DOWNLOADS_MANIFEST = "downloads/manifest.json";
|
|
5
5
|
export declare const MAX_DOWNLOAD_BYTES: number;
|
|
6
6
|
export declare const MAX_DOWNLOAD_FILES = 50;
|
|
7
|
+
/** The workspace browser_downloads copies into: the host's own file calls on it, never a path of this machine. Every path
|
|
8
|
+
* is relative to the workspace's root, folders separated by "/", and no call follows a link, on the way to its path or
|
|
9
|
+
* at its end: a link there is refused, so a folder that another process sharing the workspace swaps for a link (a
|
|
10
|
+
* computer that mounts it) leads no call outside it. agentrun-serve's Workspace is one (its local folder walks each
|
|
11
|
+
* path by handles opened with O_NOFOLLOW). */
|
|
12
|
+
export interface DownloadsWorkspace {
|
|
13
|
+
/** The bytes of regular file `path`, or `length` of them from `offset`. Anything else there (a link, a folder, a FIFO)
|
|
14
|
+
* is refused, without waiting on it; nothing there fails with `code` "NOT_FOUND". */
|
|
15
|
+
read(path: string, range?: {
|
|
16
|
+
readonly offset?: number;
|
|
17
|
+
readonly length?: number;
|
|
18
|
+
}): Promise<Uint8Array>;
|
|
19
|
+
/** What is at `path`, never following it, or undefined when nothing is. */
|
|
20
|
+
stat(path: string): Promise<{
|
|
21
|
+
readonly kind: "file" | "dir" | "link" | "other";
|
|
22
|
+
readonly size: number;
|
|
23
|
+
readonly mtimeMs: number;
|
|
24
|
+
} | undefined>;
|
|
25
|
+
/** Folder `path` made with its parents; one already there is fine, anything else there (a link, a file) is refused. */
|
|
26
|
+
mkdir(path: string): Promise<void>;
|
|
27
|
+
/** File `path` replaced by `data` in one step. */
|
|
28
|
+
write(path: string, data: Uint8Array | string): Promise<void>;
|
|
29
|
+
/** File `path` made with `data` only when nothing is at it, in one step: true when made, false when something is
|
|
30
|
+
* already there, which is kept. */
|
|
31
|
+
writeNew(path: string, data: Uint8Array | string): Promise<boolean>;
|
|
32
|
+
/** File `path` removed; nothing there is no failure with `force`. */
|
|
33
|
+
remove(path: string, options?: {
|
|
34
|
+
readonly force?: boolean;
|
|
35
|
+
}): Promise<void>;
|
|
36
|
+
}
|
|
7
37
|
/** What a skipped download the browser is still writing says: the next call files it. */
|
|
8
38
|
export declare const STILL_DOWNLOADING = "still downloading; call browser_downloads again";
|
|
9
39
|
/** A provider's read of a file the browser was still writing (its bytes or its name moved while it was read). */
|
|
@@ -30,13 +60,17 @@ export type DownloadsResult = {
|
|
|
30
60
|
};
|
|
31
61
|
/** A name that stays inside `downloads/`: the last path segment, no control characters, not hidden, not the manifest. */
|
|
32
62
|
export declare function safeDownloadName(remote: string): string;
|
|
33
|
-
|
|
34
|
-
|
|
63
|
+
/** `run` while this call holds lock file `file` of `workspace`, made only where nothing is at its name; one older than
|
|
64
|
+
* 30 s is a dead writer's, and is removed. */
|
|
65
|
+
export declare function withLock<T>(workspace: DownloadsWorkspace, file: string, run: () => Promise<T>, what?: string): Promise<T>;
|
|
66
|
+
/** Skips what the workspace already holds; one failing file is skipped with its reason. Every file call goes through
|
|
67
|
+
* `workspace`, which follows no link: a `downloads/` that is a link, or anything but a folder, is refused before any
|
|
68
|
+
* write, and so is a manifest that is not a regular file. */
|
|
35
69
|
export declare function fetchDownloads(options: {
|
|
36
70
|
provider: Pick<BrowserProvider, "downloads">;
|
|
37
71
|
ref: LeaseRef;
|
|
38
72
|
session: string;
|
|
39
|
-
workspace:
|
|
73
|
+
workspace: DownloadsWorkspace;
|
|
40
74
|
maxBytes?: number;
|
|
41
75
|
maxFiles?: number;
|
|
42
76
|
now?: () => Date;
|
package/dist/core/downloads.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { createHash
|
|
2
|
-
import { lstat, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
3
2
|
import path from "node:path";
|
|
4
3
|
import { refusedError } from "./custody.js";
|
|
5
4
|
export const DOWNLOADS_DIR = "downloads";
|
|
@@ -9,6 +8,8 @@ export const DOWNLOADS_MANIFEST = "downloads/manifest.json";
|
|
|
9
8
|
const LOCK_FILE = ".downloads.lock";
|
|
10
9
|
export const MAX_DOWNLOAD_BYTES = 100 * 1024 * 1024;
|
|
11
10
|
export const MAX_DOWNLOAD_FILES = 50;
|
|
11
|
+
/** How much of a file one read takes, when a name already taken is compared with a download's bytes. */
|
|
12
|
+
const COMPARE_READ_BYTES = 8 * 1024 * 1024;
|
|
12
13
|
/** What a skipped download the browser is still writing says: the next call files it. */
|
|
13
14
|
export const STILL_DOWNLOADING = "still downloading; call browser_downloads again";
|
|
14
15
|
/** A provider's read of a file the browser was still writing (its bytes or its name moved while it was read). */
|
|
@@ -20,45 +21,60 @@ export class DownloadNotSettled extends Error {
|
|
|
20
21
|
export const recordingHandle = (sessionId) => `session:${sessionId}`;
|
|
21
22
|
/** A name that stays inside `downloads/`: the last path segment, no control characters, not hidden, not the manifest. */
|
|
22
23
|
export function safeDownloadName(remote) {
|
|
23
|
-
const base = (remote.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f]/g, "").replace(
|
|
24
|
+
const base = (remote.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f]/g, "").replace(/^[\s.]+/, "").trim().slice(0, 200);
|
|
24
25
|
return !base || base === "manifest.json" ? "download" : base;
|
|
25
26
|
}
|
|
26
27
|
const sameRemote = (row, session, file) => row.session === session && row.remote.name === file.name && row.remote.sizeBytes === file.sizeBytes && row.remote.modifiedAt === file.modifiedAt;
|
|
27
|
-
const
|
|
28
|
-
|
|
28
|
+
const words = (error) => (error instanceof Error ? error.message : String(error));
|
|
29
|
+
/** A regular file is at `rel`: a path a manifest row names, which anything sharing the workspace can edit, so one the
|
|
30
|
+
* workspace refuses holds no file. */
|
|
31
|
+
const isFile = (workspace, rel) => workspace.stat(rel).then((at) => at?.kind === "file", () => false);
|
|
32
|
+
/** Whether `rel` is a regular file of `size` bytes whose SHA-256 is `sha256`, read in parts. */
|
|
33
|
+
async function holds(workspace, rel, size, sha256) {
|
|
34
|
+
const at = await workspace.stat(rel);
|
|
35
|
+
if (at?.kind !== "file" || at.size !== size)
|
|
36
|
+
return false;
|
|
37
|
+
const hash = createHash("sha256");
|
|
38
|
+
for (let read = 0; read < size;) {
|
|
39
|
+
const part = await workspace.read(rel, { offset: read, length: Math.min(COMPARE_READ_BYTES, size - read) });
|
|
40
|
+
if (part.byteLength === 0)
|
|
41
|
+
return false;
|
|
42
|
+
hash.update(part);
|
|
43
|
+
read += part.byteLength;
|
|
44
|
+
}
|
|
45
|
+
return hash.digest("hex") === sha256;
|
|
46
|
+
}
|
|
29
47
|
const withRow = (rows, row) => [...rows.filter((r) => r.path !== row.path || (r.sha256 === row.sha256 && !(r.session === row.session && r.remote.name === row.remote.name))), row];
|
|
30
|
-
|
|
48
|
+
/** `run` while this call holds lock file `file` of `workspace`, made only where nothing is at its name; one older than
|
|
49
|
+
* 30 s is a dead writer's, and is removed. */
|
|
50
|
+
export async function withLock(workspace, file, run, what = DOWNLOADS_MANIFEST) {
|
|
31
51
|
for (const deadline = Date.now() + 10_000;; await new Promise((r) => setTimeout(r, 25 + Math.random() * 50))) {
|
|
32
|
-
|
|
33
|
-
await (await open(file, "wx")).close();
|
|
52
|
+
if (await workspace.writeNew(file, ""))
|
|
34
53
|
break;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
await rm(file, { force: true });
|
|
41
|
-
else if (Date.now() > deadline)
|
|
42
|
-
throw new Error(`${what} is locked by another writer`);
|
|
43
|
-
}
|
|
54
|
+
const at = await workspace.stat(file);
|
|
55
|
+
if (at !== undefined && Date.now() - at.mtimeMs > 30_000)
|
|
56
|
+
await workspace.remove(file, { force: true });
|
|
57
|
+
else if (Date.now() > deadline)
|
|
58
|
+
throw new Error(`${what} is locked by another writer`);
|
|
44
59
|
}
|
|
45
60
|
try {
|
|
46
61
|
return await run();
|
|
47
62
|
}
|
|
48
63
|
finally {
|
|
49
|
-
await
|
|
64
|
+
await workspace.remove(file, { force: true });
|
|
50
65
|
}
|
|
51
66
|
}
|
|
52
|
-
/** A manifest that is there but unreadable is refused, never replaced: its rows are the only record of earlier fetches.
|
|
53
|
-
|
|
67
|
+
/** A manifest that is there but unreadable is refused, never replaced: its rows are the only record of earlier fetches.
|
|
68
|
+
* Only a regular file is read: the workspace's read refuses a link, a folder or a FIFO, and never waits on one. */
|
|
69
|
+
async function readManifest(workspace) {
|
|
54
70
|
let raw;
|
|
55
71
|
try {
|
|
56
|
-
raw = await
|
|
72
|
+
raw = Buffer.from(await workspace.read(DOWNLOADS_MANIFEST)).toString("utf8");
|
|
57
73
|
}
|
|
58
74
|
catch (error) {
|
|
59
|
-
if (error
|
|
75
|
+
if (error?.code === "NOT_FOUND")
|
|
60
76
|
return { schema: "pi-browser.downloads.v1", files: [] };
|
|
61
|
-
throw error;
|
|
77
|
+
throw refusedError(`${DOWNLOADS_MANIFEST} cannot be read as a regular file (${words(error)}); move it, then call browser_downloads again.`);
|
|
62
78
|
}
|
|
63
79
|
let parsed = null;
|
|
64
80
|
try {
|
|
@@ -69,25 +85,28 @@ async function readManifest(file) {
|
|
|
69
85
|
return parsed;
|
|
70
86
|
throw refusedError(`${DOWNLOADS_MANIFEST} exists but is not a pi-browser downloads manifest; fix or move it, then call browser_downloads again.`);
|
|
71
87
|
}
|
|
72
|
-
/** Skips what the workspace already holds; one failing file is skipped with its reason.
|
|
88
|
+
/** Skips what the workspace already holds; one failing file is skipped with its reason. Every file call goes through
|
|
89
|
+
* `workspace`, which follows no link: a `downloads/` that is a link, or anything but a folder, is refused before any
|
|
90
|
+
* write, and so is a manifest that is not a regular file. */
|
|
73
91
|
export async function fetchDownloads(options) {
|
|
74
92
|
const { provider, ref, session, workspace } = options;
|
|
75
93
|
if (!provider.downloads)
|
|
76
94
|
throw new Error("this provider cannot list downloads");
|
|
77
95
|
const maxBytes = options.maxBytes ?? MAX_DOWNLOAD_BYTES;
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
96
|
+
try {
|
|
97
|
+
await workspace.mkdir(DOWNLOADS_DIR);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
throw refusedError(`${DOWNLOADS_DIR}/ in the workspace is not a directory the browser can copy into (${words(error)}); move it, then call browser_downloads again.`);
|
|
101
|
+
}
|
|
102
|
+
const manifest = await readManifest(workspace);
|
|
84
103
|
const result = { fetched: [], already_fetched: [], skipped: [], manifest: DOWNLOADS_MANIFEST };
|
|
85
104
|
const entry = (row) => ({ name: row.name, path: row.path, sizeBytes: row.sizeBytes, sha256: row.sha256 });
|
|
86
105
|
const remote = await provider.downloads.list(ref);
|
|
87
106
|
let attempted = 0;
|
|
88
107
|
for (const file of remote) {
|
|
89
108
|
const known = manifest.files.find((row) => sameRemote(row, session, file));
|
|
90
|
-
if (known && (await
|
|
109
|
+
if (known && (await isFile(workspace, known.path))) {
|
|
91
110
|
result.already_fetched.push(entry(known));
|
|
92
111
|
continue;
|
|
93
112
|
}
|
|
@@ -105,48 +124,53 @@ export async function fetchDownloads(options) {
|
|
|
105
124
|
result.skipped.push({ name: file.name, reason: `larger than the ${maxBytes}-byte limit` });
|
|
106
125
|
continue;
|
|
107
126
|
}
|
|
108
|
-
const part = path.join(dir, `.part-${randomBytes(6).toString("hex")}`);
|
|
109
127
|
try {
|
|
128
|
+
// The bytes are held here (at most maxBytes): nothing is written until the file is whole and its name chosen, as
|
|
129
|
+
// its name may be its digest's. Each chunk is copied into one buffer, sized by the provider's listed size, as it
|
|
130
|
+
// comes and then dropped, so the file is held once; a read longer than listed grows it (to maxBytes at most).
|
|
110
131
|
const hash = createHash("sha256");
|
|
132
|
+
let held = Buffer.allocUnsafe(Number.isSafeInteger(file.sizeBytes) && file.sizeBytes > 0 ? Math.min(file.sizeBytes, maxBytes) : 0);
|
|
111
133
|
let size = 0;
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
await out.write(chunk);
|
|
134
|
+
for await (const chunk of await provider.downloads.read(ref, file.name, maxBytes)) {
|
|
135
|
+
if (size + chunk.byteLength > maxBytes)
|
|
136
|
+
throw new Error(`larger than the ${maxBytes}-byte limit`);
|
|
137
|
+
if (size + chunk.byteLength > held.length) {
|
|
138
|
+
const grown = Buffer.allocUnsafe(Math.min(maxBytes, Math.max(held.length * 2, size + chunk.byteLength)));
|
|
139
|
+
held.copy(grown, 0, 0, size);
|
|
140
|
+
held = grown;
|
|
120
141
|
}
|
|
142
|
+
hash.update(chunk);
|
|
143
|
+
held.set(chunk, size);
|
|
144
|
+
size += chunk.byteLength;
|
|
121
145
|
}
|
|
122
|
-
|
|
123
|
-
await out.close();
|
|
124
|
-
}
|
|
146
|
+
const bytes = held.subarray(0, size);
|
|
125
147
|
const sha256 = hash.digest("hex");
|
|
126
|
-
// Naming, placing and recording are one step under the lock, so two writers never both find a name free
|
|
127
|
-
//
|
|
148
|
+
// Naming, placing and recording are one step under the lock, so two writers never both find a name free. A file is
|
|
149
|
+
// placed only where nothing is at its name (writeNew), so it never replaces other contents: a name that holds these
|
|
150
|
+
// very bytes is this file already, and one taken by other bytes gains this file's digest.
|
|
128
151
|
const wanted = safeDownloadName(file.name);
|
|
129
152
|
const ext = path.extname(wanted);
|
|
130
|
-
const row = await withLock(
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
153
|
+
const row = await withLock(workspace, LOCK_FILE, async () => {
|
|
154
|
+
const names = [wanted, ...[8, 16, 32, 64].map((digits) => `${path.basename(wanted, ext)}-${sha256.slice(0, digits)}${ext}`)];
|
|
155
|
+
let name;
|
|
156
|
+
for (const candidate of names) {
|
|
157
|
+
const rel = path.posix.join(DOWNLOADS_DIR, candidate);
|
|
158
|
+
if ((await workspace.writeNew(rel, bytes)) || (await holds(workspace, rel, size, sha256))) {
|
|
159
|
+
name = candidate;
|
|
134
160
|
break;
|
|
135
|
-
|
|
161
|
+
}
|
|
136
162
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
const
|
|
141
|
-
await
|
|
142
|
-
await rename(tmp, manifestPath);
|
|
163
|
+
if (name === undefined)
|
|
164
|
+
throw new Error(`every name for it in ${DOWNLOADS_DIR}/ holds other bytes`);
|
|
165
|
+
const placed = { name, path: path.posix.join(DOWNLOADS_DIR, name), sizeBytes: size, sha256, remote: { name: file.name, sizeBytes: file.sizeBytes, modifiedAt: file.modifiedAt }, session, fetchedAt: (options.now?.() ?? new Date()).toISOString() };
|
|
166
|
+
const latest = withRow((await readManifest(workspace)).files, placed);
|
|
167
|
+
await workspace.write(DOWNLOADS_MANIFEST, `${JSON.stringify({ schema: "pi-browser.downloads.v1", files: latest }, null, 2)}\n`);
|
|
143
168
|
return placed;
|
|
144
169
|
});
|
|
145
170
|
manifest.files = withRow(manifest.files, row);
|
|
146
171
|
result.fetched.push(entry(row));
|
|
147
172
|
}
|
|
148
173
|
catch (error) {
|
|
149
|
-
await rm(part, { force: true });
|
|
150
174
|
const reason = error instanceof DownloadNotSettled ? STILL_DOWNLOADING : error instanceof Error ? (options.redact ?? ((text) => text))(error.message).slice(0, 200) : "the read failed";
|
|
151
175
|
result.skipped.push({ name: file.name, reason });
|
|
152
176
|
}
|
|
@@ -10,7 +10,7 @@ export declare const PERSON_HAD = "This call waited while the person had the bro
|
|
|
10
10
|
export declare const PERSON_HAD_UNUSED = "This call waited while the person had the browser: they took it over through the live view and handed it back without using it, so the page is as you left it.";
|
|
11
11
|
/** The mark (in a call's result details) of an act the person's take made stale: the person drove the session through the
|
|
12
12
|
* live view while the call waited, so the snapshot its element ids came from no longer stands. Its timeline row reads
|
|
13
|
-
* neutral, in plain words (
|
|
13
|
+
* neutral, in plain words (serve's timeline), never as a failure. */
|
|
14
14
|
export declare const PAGE_CHANGED_WHILE_HELD = "page_changed_while_held";
|
|
15
15
|
/** Told to the model by such an act: nothing was done, and its next step is a snapshot. */
|
|
16
16
|
export declare const PAGE_CHANGED_FOR_MODEL = "The person changed the page while they had the browser, so this action was not done. Take a snapshot first, then act on the page as it is now.";
|
|
@@ -10,7 +10,7 @@ export const PERSON_HAD = "This call waited while the person had the browser: th
|
|
|
10
10
|
export const PERSON_HAD_UNUSED = "This call waited while the person had the browser: they took it over through the live view and handed it back without using it, so the page is as you left it.";
|
|
11
11
|
/** The mark (in a call's result details) of an act the person's take made stale: the person drove the session through the
|
|
12
12
|
* live view while the call waited, so the snapshot its element ids came from no longer stands. Its timeline row reads
|
|
13
|
-
* neutral, in plain words (
|
|
13
|
+
* neutral, in plain words (serve's timeline), never as a failure. */
|
|
14
14
|
export const PAGE_CHANGED_WHILE_HELD = "page_changed_while_held";
|
|
15
15
|
/** Told to the model by such an act: nothing was done, and its next step is a snapshot. */
|
|
16
16
|
export const PAGE_CHANGED_FOR_MODEL = "The person changed the page while they had the browser, so this action was not done. Take a snapshot first, then act on the page as it is now.";
|
package/dist/core/files.d.ts
CHANGED
|
@@ -3,9 +3,24 @@ export declare const MAX_UPLOAD_BYTES: number;
|
|
|
3
3
|
/** The media type browser_upload gives a file named `name`, by its extension; application/octet-stream for one it does
|
|
4
4
|
* not know. */
|
|
5
5
|
export declare const uploadMime: (name: string) => string;
|
|
6
|
+
/** Why `rel` is no path of a file in a workspace, or null when it is one: a relative path with no `..` segment. Where it
|
|
7
|
+
* then leads (a link on the way) is the reader's or the writer's to check. */
|
|
8
|
+
export declare function workspacePathRefusal(rel: unknown): string | null;
|
|
6
9
|
/** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
|
|
7
|
-
* not one `refuse` names (a host's private files).
|
|
8
|
-
|
|
10
|
+
* not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
|
|
11
|
+
* the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
|
|
12
|
+
* link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
|
|
13
|
+
* over the name; a reader sees the old file or the new one).
|
|
14
|
+
*
|
|
15
|
+
* On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
|
|
16
|
+
* swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
|
|
17
|
+
* Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
|
|
18
|
+
* there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
|
|
19
|
+
* removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
|
|
20
|
+
* it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
|
|
21
|
+
* rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
|
|
22
|
+
export declare function workspaceFiles(root: string, { maxBytes, refuse, procFd }?: {
|
|
9
23
|
maxBytes?: number;
|
|
10
24
|
refuse?: (real: string) => string | null;
|
|
25
|
+
procFd?: boolean;
|
|
11
26
|
}): WorkspaceFiles;
|
package/dist/core/files.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { constants } from "node:fs";
|
|
2
|
-
import { open, readlink, realpath, stat } from "node:fs/promises";
|
|
2
|
+
import { lstat, mkdir, open, readlink, realpath, rename, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { randomBytes } from "node:crypto";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
export const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
|
|
5
6
|
const MIME = {
|
|
@@ -19,17 +20,41 @@ async function openedPath(handle, checked) {
|
|
|
19
20
|
const [opened, now] = await Promise.all([handle.stat(), stat(checked).catch(() => null)]);
|
|
20
21
|
return now && opened.dev === now.dev && opened.ino === now.ino ? realpath(checked).catch(() => null) : null;
|
|
21
22
|
}
|
|
23
|
+
/** Why `rel` is no path of a file in a workspace, or null when it is one: a relative path with no `..` segment. Where it
|
|
24
|
+
* then leads (a link on the way) is the reader's or the writer's to check. */
|
|
25
|
+
export function workspacePathRefusal(rel) {
|
|
26
|
+
if (typeof rel !== "string" || !rel.trim() || rel.includes("\0"))
|
|
27
|
+
return "path must name a file in the workspace";
|
|
28
|
+
if (path.isAbsolute(rel) || path.win32.isAbsolute(rel))
|
|
29
|
+
return `${rel} is absolute; give a path relative to the workspace`;
|
|
30
|
+
if (rel.split(/[\\/]/).includes(".."))
|
|
31
|
+
return `${rel} contains '..'; give a path inside the workspace`;
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
const DIR_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
|
|
35
|
+
const errno = (error) => error?.code;
|
|
36
|
+
/** A write's refusal, carried out of the walk. */
|
|
37
|
+
class Refused extends Error {
|
|
38
|
+
}
|
|
22
39
|
/** Files under `root` only: a relative path with no `..`, inside `root` once symlinks resolve, at most `maxBytes`, and
|
|
23
|
-
* not one `refuse` names (a host's private files).
|
|
24
|
-
|
|
40
|
+
* not one `refuse` names (a host's private files). A write takes folders separated by "/" alone and follows no link on
|
|
41
|
+
* the way, the file itself included: it walks from the root one folder at a time, each opened as a folder through no
|
|
42
|
+
* link and held, makes each missing one, and replaces the file whole (a temporary file made beside it, then renamed
|
|
43
|
+
* over the name; a reader sees the old file or the new one).
|
|
44
|
+
*
|
|
45
|
+
* On Linux (`procFd`, default there) every name after the root resolves inside a folder a handle holds, so a folder
|
|
46
|
+
* swapped for a link by another process changes nothing: what is made or written is made in the folders walked.
|
|
47
|
+
* Elsewhere node can only resolve a path again, so before and after each act the folders held are checked: each still
|
|
48
|
+
* there by its path, no link, the same folder (dev and inode); else the write is refused, and the temporary file
|
|
49
|
+
* removed. What remains there is the gap between the last check and the call itself: a folder swapped for a link in
|
|
50
|
+
* it, and put back before the next check, can have that one call (a folder made, an empty temporary file made, or the
|
|
51
|
+
* rename) land through the link; the bytes are written only once the temporary file is confirmed in the folder held. */
|
|
52
|
+
export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse, procFd = process.platform === "linux" } = {}) {
|
|
25
53
|
return {
|
|
26
54
|
async resolve(rel) {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
return { refused: `${rel} is absolute; give a path relative to the workspace` };
|
|
31
|
-
if (rel.split(/[\\/]/).includes(".."))
|
|
32
|
-
return { refused: `${rel} contains '..'; give a path inside the workspace` };
|
|
55
|
+
const bad = workspacePathRefusal(rel);
|
|
56
|
+
if (bad)
|
|
57
|
+
return { refused: bad };
|
|
33
58
|
let base;
|
|
34
59
|
try {
|
|
35
60
|
base = await realpath(root);
|
|
@@ -73,5 +98,128 @@ export function workspaceFiles(root, { maxBytes = MAX_UPLOAD_BYTES, refuse } = {
|
|
|
73
98
|
await handle.close();
|
|
74
99
|
}
|
|
75
100
|
},
|
|
101
|
+
async write(rel, bytes) {
|
|
102
|
+
const bad = workspacePathRefusal(rel);
|
|
103
|
+
if (bad)
|
|
104
|
+
return { refused: bad };
|
|
105
|
+
if (rel.includes("\\"))
|
|
106
|
+
return { refused: `${rel}: folders are separated by "/", never a backslash` };
|
|
107
|
+
const parts = rel.split("/").filter((part) => part !== "" && part !== ".");
|
|
108
|
+
const name = parts.pop();
|
|
109
|
+
if (!name)
|
|
110
|
+
return { refused: "path must name a file in the workspace" };
|
|
111
|
+
let base;
|
|
112
|
+
try {
|
|
113
|
+
base = await realpath(root);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return { refused: "the workspace does not exist" };
|
|
117
|
+
}
|
|
118
|
+
const held = [];
|
|
119
|
+
const at = (dir, child) => (procFd ? `/proc/self/fd/${dir.handle.fd}/${child}` : path.join(dir.abs, child));
|
|
120
|
+
const outside = () => new Refused(`${rel} resolves outside the workspace, or a link is on the way to it, and a write follows none`);
|
|
121
|
+
// Off /proc/self/fd: every folder held is still there by its path, through no link, the same folder.
|
|
122
|
+
const confirm = async () => {
|
|
123
|
+
if (procFd)
|
|
124
|
+
return;
|
|
125
|
+
for (const dir of held.slice(1)) {
|
|
126
|
+
const now = await lstat(dir.abs).catch(() => null);
|
|
127
|
+
if (!now?.isDirectory() || now.dev !== dir.dev || now.ino !== dir.ino)
|
|
128
|
+
throw outside();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
const hold = async (handle, abs) => {
|
|
132
|
+
const info = await handle.stat().catch(async (error) => { await handle.close(); throw error; });
|
|
133
|
+
const dir = { handle, abs, dev: info.dev, ino: info.ino };
|
|
134
|
+
held.push(dir);
|
|
135
|
+
return dir;
|
|
136
|
+
};
|
|
137
|
+
const enter = async (dir, index) => {
|
|
138
|
+
const part = parts[index];
|
|
139
|
+
for (let made = false;;) {
|
|
140
|
+
try {
|
|
141
|
+
const handle = await open(at(dir, part), DIR_FLAGS);
|
|
142
|
+
const next = await hold(handle, path.join(dir.abs, part));
|
|
143
|
+
await confirm();
|
|
144
|
+
return next;
|
|
145
|
+
}
|
|
146
|
+
catch (error) {
|
|
147
|
+
if (error instanceof Refused)
|
|
148
|
+
throw error;
|
|
149
|
+
const code = errno(error);
|
|
150
|
+
if (code === "ENOENT" && !made) {
|
|
151
|
+
made = true;
|
|
152
|
+
await confirm();
|
|
153
|
+
await mkdir(at(dir, part)).catch((making) => { if (making.code !== "EEXIST")
|
|
154
|
+
throw making; });
|
|
155
|
+
await confirm();
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
const there = await lstat(at(dir, part)).catch(() => null);
|
|
159
|
+
if (code === "ELOOP" || there?.isSymbolicLink())
|
|
160
|
+
throw new Refused(`${rel}: a link is on the way to it, and a write follows none`);
|
|
161
|
+
if (code === "ENOTDIR" || there)
|
|
162
|
+
throw new Refused(`${rel}: ${parts.slice(0, index + 1).join("/")} is not a directory`);
|
|
163
|
+
throw error;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
let temp = null;
|
|
168
|
+
let tempIn = null;
|
|
169
|
+
let placed = false;
|
|
170
|
+
try {
|
|
171
|
+
let dir = await hold(await open(base, DIR_FLAGS), base);
|
|
172
|
+
for (let index = 0; index < parts.length; index++)
|
|
173
|
+
dir = await enter(dir, index);
|
|
174
|
+
const target = path.join(dir.abs, name);
|
|
175
|
+
await confirm();
|
|
176
|
+
const there = await lstat(at(dir, name)).catch(() => null);
|
|
177
|
+
await confirm();
|
|
178
|
+
if (there?.isSymbolicLink())
|
|
179
|
+
return { refused: `${rel} is a link, and a write follows none` };
|
|
180
|
+
if (there && !there.isFile())
|
|
181
|
+
return { refused: `${rel} is not a regular file` };
|
|
182
|
+
const vetoed = refuse?.(target);
|
|
183
|
+
if (vetoed)
|
|
184
|
+
return { refused: `${rel}: ${vetoed}` };
|
|
185
|
+
// Not built from the name, as serve's workspace writes are not: a name the folder takes may leave no room for more.
|
|
186
|
+
const tempName = `.workspace-${randomBytes(8).toString("hex")}.tmp`;
|
|
187
|
+
const handle = await open(at(dir, tempName), constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o666).catch(() => null);
|
|
188
|
+
if (!handle)
|
|
189
|
+
return { refused: `${rel} cannot be written` };
|
|
190
|
+
temp = tempName;
|
|
191
|
+
tempIn = dir;
|
|
192
|
+
try {
|
|
193
|
+
// The file just made is the one at its name in the folder held, before any byte is written to it.
|
|
194
|
+
await confirm();
|
|
195
|
+
const [made, named] = await Promise.all([handle.stat(), lstat(at(dir, tempName)).catch(() => null)]);
|
|
196
|
+
if (!named || named.dev !== made.dev || named.ino !== made.ino)
|
|
197
|
+
throw outside();
|
|
198
|
+
await confirm();
|
|
199
|
+
await handle.writeFile(bytes);
|
|
200
|
+
await handle.sync();
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
await handle.close();
|
|
204
|
+
}
|
|
205
|
+
await confirm();
|
|
206
|
+
// A rename replaces whatever is at the name, a link swapped in included, and never writes through it; one that
|
|
207
|
+
// resolves through a folder swapped since the check finds no temporary file there, and fails.
|
|
208
|
+
await rename(at(dir, tempName), at(dir, name));
|
|
209
|
+
placed = true;
|
|
210
|
+
await dir.handle.sync();
|
|
211
|
+
return { path: [...parts, name].join("/") };
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
if (error instanceof Refused)
|
|
215
|
+
return { refused: error.message };
|
|
216
|
+
return { refused: `${rel} cannot be written` };
|
|
217
|
+
}
|
|
218
|
+
finally {
|
|
219
|
+
if (!placed && temp && tempIn)
|
|
220
|
+
await rm(at(tempIn, temp), { force: true }).catch(() => undefined);
|
|
221
|
+
await Promise.all(held.map((dir) => dir.handle.close().catch(() => undefined)));
|
|
222
|
+
}
|
|
223
|
+
},
|
|
76
224
|
};
|
|
77
225
|
}
|
package/dist/core/host.d.ts
CHANGED
|
@@ -92,12 +92,8 @@ export type AttachTarget = {
|
|
|
92
92
|
extensionCdpUrl?: string;
|
|
93
93
|
};
|
|
94
94
|
export type ProviderCaps = {
|
|
95
|
-
|
|
96
|
-
maxLifetimeS: number;
|
|
97
|
-
survivesDisconnect: boolean;
|
|
98
|
-
releaseIsAsync: boolean;
|
|
95
|
+
/** The provider can open a session on a saved sign-in (`SessionSpec.profile`); without it such a session is refused. */
|
|
99
96
|
profiles: boolean;
|
|
100
|
-
extension: "uploaded-per-launch" | "preinstalled" | "loaded-locally";
|
|
101
97
|
/** Every session attaches to the same browser (an endpoint the host named), so two at once would drive the same pages. */
|
|
102
98
|
sharedBrowser?: boolean;
|
|
103
99
|
/** The session settings this provider applies; a setting left out is applied. */
|
|
@@ -140,13 +136,6 @@ export type RemoteFile = {
|
|
|
140
136
|
/** What a session vault may keep of this provider's sessions. Absent: nothing (a browser the package cannot read, or one the host shares). */
|
|
141
137
|
export type ProviderVault = {
|
|
142
138
|
kind: "cdp";
|
|
143
|
-
} | {
|
|
144
|
-
kind: "context";
|
|
145
|
-
provider: "browserbase" | "kernel";
|
|
146
|
-
/** True when this provider writes the context ids it makes to a clear file: a vault refuses such a provider, so an id never lands outside it. */
|
|
147
|
-
contextIdsInClear: boolean;
|
|
148
|
-
/** The context or profile this session runs on, or null. A capability: it goes to the host's vault only. */
|
|
149
|
-
contextOf(ref: LeaseRef): string | null;
|
|
150
139
|
};
|
|
151
140
|
export interface BrowserProvider {
|
|
152
141
|
readonly name: string;
|
|
@@ -173,7 +162,8 @@ export interface BrowserProvider {
|
|
|
173
162
|
read(ref: LeaseRef, name: string, maxBytes: number): Promise<AsyncIterable<Uint8Array>>;
|
|
174
163
|
};
|
|
175
164
|
}
|
|
176
|
-
/** The host owns the file boundary for `browser_upload`: a path the model names is resolved
|
|
165
|
+
/** The host owns the file boundary for `browser_upload` and a screenshot's `save_as`: a path the model names is resolved
|
|
166
|
+
* or written here, or refused. */
|
|
177
167
|
export interface WorkspaceFiles {
|
|
178
168
|
resolve(rel: string): Promise<{
|
|
179
169
|
bytes: Uint8Array;
|
|
@@ -182,6 +172,13 @@ export interface WorkspaceFiles {
|
|
|
182
172
|
} | {
|
|
183
173
|
refused: string;
|
|
184
174
|
}>;
|
|
175
|
+
/** File `rel` made or replaced with `bytes`, its parent directories made, as the host's own file-write tool writes one;
|
|
176
|
+
* `path` is where it went, relative to the workspace. Absent: the host saves no screenshot. */
|
|
177
|
+
write?(rel: string, bytes: Uint8Array): Promise<{
|
|
178
|
+
path: string;
|
|
179
|
+
} | {
|
|
180
|
+
refused: string;
|
|
181
|
+
}>;
|
|
185
182
|
}
|
|
186
183
|
export type HandoffOutcome = "done" | "cancelled" | "expired";
|
|
187
184
|
/** Hands the live browser to a person and reports how it ended. Polled by id, so a restarted process resumes the wait;
|
|
@@ -308,6 +305,10 @@ export type SessionsState = {
|
|
|
308
305
|
/** Told to the model on its next browser call, then cleared. */
|
|
309
306
|
notice: string | null;
|
|
310
307
|
};
|
|
308
|
+
/** `owed`: sessions besides the row's own that a release by its tag sent a stop to (or is about to), and that no raced
|
|
309
|
+
* call has told yet; each stays until a status read confirms its stop and it is told. `made`: when the provider made each
|
|
310
|
+
* session its tag lookup found (LeaseRef.madeAt), by id, saved before any stop is sent to it, until it is told: a stopped
|
|
311
|
+
* session is listed by no later lookup, and a raced call hands its host this time. */
|
|
311
312
|
export type InventoryRow = {
|
|
312
313
|
tag: string;
|
|
313
314
|
conversationId: number;
|
|
@@ -315,6 +316,8 @@ export type InventoryRow = {
|
|
|
315
316
|
provider: string;
|
|
316
317
|
resourceId: string | null;
|
|
317
318
|
state: SessionRecord["state"];
|
|
319
|
+
owed?: string[];
|
|
320
|
+
made?: Record<string, string>;
|
|
318
321
|
};
|
|
319
322
|
export type SessionRow = {
|
|
320
323
|
conversationId: number;
|
|
@@ -353,7 +356,9 @@ export type PriceTable = {
|
|
|
353
356
|
};
|
|
354
357
|
/** One charge of a session's time, as its record bills it: `seconds` and `usd` since the session's last charge, through `at`,
|
|
355
358
|
* or, `final`, at its release, topped up to the provider's minimum. `state` says whether `usd` is a price (`priced`) or
|
|
356
|
-
* the time went unpriced (`unpriced`, `invalid`: `usd` is 0 and is no charge).
|
|
359
|
+
* the time went unpriced (`unpriced`, `invalid`: `usd` is 0 and is no charge). `overbookedS`: an earlier charge billed
|
|
360
|
+
* the session through a later time than this one's `at` (a charge taken while its release was under way, the release
|
|
361
|
+
* confirmed before it), by that many seconds; this one bills none of it again. Absent: none. */
|
|
357
362
|
export type SessionCharge = {
|
|
358
363
|
conversationId: number;
|
|
359
364
|
tag: string;
|
|
@@ -363,6 +368,7 @@ export type SessionCharge = {
|
|
|
363
368
|
usd: number;
|
|
364
369
|
final: boolean;
|
|
365
370
|
state: PriceState;
|
|
371
|
+
overbookedS?: number;
|
|
366
372
|
};
|
|
367
373
|
/** Browserbase list prices as of 2026-10-06: the Developer overage rate, one-minute minimum. */
|
|
368
374
|
export declare const LIST_PRICES: PriceTable;
|