@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
package/dist/core/read-page.js
CHANGED
|
@@ -1,61 +1,93 @@
|
|
|
1
1
|
// A fetched HTML page read as its title, its text and its links, without ever holding the event loop. The host's tools
|
|
2
2
|
// run in the run's own process, so a read that holds the loop holds the run's heartbeat with it, and a run whose
|
|
3
3
|
// heartbeat lapses is fenced: go.dev/dl, 3.15 MB of tables, held it past 240 s in one markdown conversion. So one linear
|
|
4
|
-
// pass drops the blocks that hold no readable text
|
|
4
|
+
// pass drops the blocks that hold no readable text, and another the elements the page hides from everyone (page-scan.ts:
|
|
5
|
+
// a help pop-up until its link is clicked is not the page's text); what is left is cut at READ_MAX_CHARS (the page is
|
|
5
6
|
// then `truncated`, and `html_chars` is its whole length); and a worker thread converts that to markdown, in pieces
|
|
6
7
|
// small enough that the converter stays linear (page-markdown.ts), within a deadline. A worker that has not answered by
|
|
7
8
|
// then, or that fails, is stopped, and the text is the page's plain text, read on the loop in steps that yield it
|
|
8
|
-
// (`converted: "text"`)
|
|
9
|
-
//
|
|
9
|
+
// (`converted: "text"`); a worker that ran out of memory is not: the read is refused (PageReadOutOfMemory), since what
|
|
10
|
+
// filled the worker's heap would fill the run's own. The links resolved are bounded (READ_LINKS_MAX and
|
|
11
|
+
// READ_LINKS_MAX_CHARS, page-scan.ts). browser_read's markdown (htmlMarkdown) goes through the same worker, which drops,
|
|
12
|
+
// picks and cuts the live page's HTML itself, since that HTML has no bound; its fallback is the browser's own text.
|
|
10
13
|
import { setImmediate as yieldToLoop } from "node:timers/promises";
|
|
11
14
|
import { Worker } from "node:worker_threads";
|
|
12
15
|
import { decodeEntities } from "./entities.js";
|
|
13
|
-
import { cutHtml, InertDrop, PageScan } from "./page-scan.js";
|
|
16
|
+
import { cutHtml, HiddenDrop, InertDrop, pageHidingOf, PageScan } from "./page-scan.js";
|
|
17
|
+
export { READ_LINKS_MAX, READ_LINKS_MAX_CHARS } from "./page-scan.js";
|
|
14
18
|
/** The most of a page's HTML that is read, counted once its script, style, svg, noscript and template blocks and its
|
|
15
19
|
* comments are dropped. A million characters of go.dev/dl converts in about 0.8 s on a busy 48-core host and gives
|
|
16
20
|
* 590,000 characters of markdown, ten times the 60,000 one web_fetch answer carries. */
|
|
17
21
|
export const READ_MAX_CHARS = 1_000_000;
|
|
18
22
|
/** How long the worker has for the markdown by default: six times what READ_MAX_CHARS of tables took. */
|
|
19
23
|
export const READ_DEADLINE_MS = 5_000;
|
|
24
|
+
/** The worker's heap by default, in MB (`heapMb`). */
|
|
25
|
+
export const READ_WORKER_HEAP_MB = 1024;
|
|
26
|
+
/** The least heap a worker is given, in MB: one of a few MB fails while it starts, and takes its whole process down. */
|
|
27
|
+
const WORKER_HEAP_MIN_MB = 16;
|
|
20
28
|
/** `n` with its digits in groups of three ("3,154,060"): Intl's first use costs tens of milliseconds on the loop. */
|
|
21
29
|
export const thousands = (n) => String(n).replace(/\B(?=(\d{3})+$)/g, ",");
|
|
22
30
|
/** How much of the page one step of the plain-text scan reads before it yields the loop. */
|
|
23
31
|
const STEP_CHARS = 32_768;
|
|
32
|
+
/** The worker ran out of its heap (Node's ERR_WORKER_OUT_OF_MEMORY). */
|
|
33
|
+
const OUT_OF_MEMORY = Symbol("out of memory");
|
|
34
|
+
/** readPage's refusal of a page whose read filled the worker's heap: it is not read again on the caller's thread. */
|
|
35
|
+
export class PageReadOutOfMemory extends Error {
|
|
36
|
+
heapMb;
|
|
37
|
+
name = "PageReadOutOfMemory";
|
|
38
|
+
code = "PAGE_READ_OUT_OF_MEMORY";
|
|
39
|
+
constructor(heapMb) {
|
|
40
|
+
super(`the page was not read: reading it filled the reader's ${heapMb} MB heap`);
|
|
41
|
+
this.heapMb = heapMb;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
24
44
|
/**
|
|
25
45
|
* An HTML page's title, its text as markdown, and the absolute http(s) URLs it links to (resolved against its
|
|
26
46
|
* `<base href>` or `url`), each once, in page order. The event loop is never held for longer than one linear step of a
|
|
27
|
-
* bounded part of the page (see the file's head and PageRead). Rejects
|
|
47
|
+
* bounded part of the page (see the file's head and PageRead). Rejects with `signal`'s reason, or with
|
|
48
|
+
* PageReadOutOfMemory when the worker ran out of memory (the page is then not read on this thread).
|
|
28
49
|
*/
|
|
29
|
-
export async function readPage(html, url, { deadlineMs = READ_DEADLINE_MS, signal } = {}) {
|
|
50
|
+
export async function readPage(html, url, { deadlineMs = READ_DEADLINE_MS, heapMb = READ_WORKER_HEAP_MB, signal } = {}) {
|
|
30
51
|
signal?.throwIfAborted();
|
|
31
|
-
|
|
52
|
+
// What the page hides from everyone who reads it (a help pop-up until its link is clicked, a closed dialog) is not
|
|
53
|
+
// its text: what its own live style elements declare is read from those the inert drop took out.
|
|
54
|
+
const inert = new InertDrop(html);
|
|
55
|
+
await stepsOnLoop(inert, signal);
|
|
56
|
+
const kept = await dropHiddenOnLoop(inert.result(), pageHidingOf(inert.styles()), signal);
|
|
32
57
|
const read = cutHtml(kept, READ_MAX_CHARS);
|
|
33
58
|
const cut = read.length < kept.length ? { truncated: true, html_chars: html.length } : {};
|
|
34
59
|
await yieldToLoop();
|
|
35
60
|
signal?.throwIfAborted();
|
|
36
|
-
const markdown = await inWorker({ html: read, url }, deadlineMs, signal);
|
|
61
|
+
const markdown = await inWorker({ html: read, url }, deadlineMs, heapMb, signal);
|
|
62
|
+
if (markdown === OUT_OF_MEMORY)
|
|
63
|
+
throw new PageReadOutOfMemory(Math.max(WORKER_HEAP_MIN_MB, heapMb));
|
|
37
64
|
if (markdown)
|
|
38
|
-
return { title: markdown.title ?? "", text: markdown.text, links: markdown.links ?? [], converted: "markdown", ...cut };
|
|
65
|
+
return { title: markdown.title ?? "", text: markdown.text, links: markdown.links ?? [], ...(markdown.links_truncated ? { links_truncated: true } : {}), converted: "markdown", ...cut };
|
|
39
66
|
return { ...(await plainRead(read, url, signal)), converted: "text", ...cut };
|
|
40
67
|
}
|
|
41
68
|
/**
|
|
42
69
|
* `html`'s markdown, made in the worker within `deadlineMs` (default READ_DEADLINE_MS): of its first article, else its
|
|
43
70
|
* main, else its body element when `main` (mainOf), once its inert blocks are dropped, cut at READ_MAX_CHARS (then
|
|
44
|
-
* `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed
|
|
45
|
-
* could not start. The event loop does no more than hand the worker the page. Rejects only
|
|
71
|
+
* `truncated`, and `html_chars` is the page's whole length). Null when the worker has not answered in time, failed (ran
|
|
72
|
+
* out of memory included), or could not start. The event loop does no more than hand the worker the page. Rejects only
|
|
73
|
+
* with `signal`'s reason.
|
|
46
74
|
*/
|
|
47
|
-
export async function htmlMarkdown(html, { main = false, deadlineMs = READ_DEADLINE_MS, signal } = {}) {
|
|
75
|
+
export async function htmlMarkdown(html, { main = false, deadlineMs = READ_DEADLINE_MS, heapMb = READ_WORKER_HEAP_MB, signal } = {}) {
|
|
48
76
|
signal?.throwIfAborted();
|
|
49
|
-
const answer = await inWorker({ html, main, max: READ_MAX_CHARS }, deadlineMs, signal);
|
|
50
|
-
|
|
77
|
+
const answer = await inWorker({ html, main, max: READ_MAX_CHARS }, deadlineMs, heapMb, signal);
|
|
78
|
+
// Out of memory too: the caller's fallback is the browser's own text, never this HTML read on its thread.
|
|
79
|
+
if (!answer || answer === OUT_OF_MEMORY)
|
|
80
|
+
return null;
|
|
81
|
+
return { text: answer.text, ...(answer.truncated ? { truncated: true, html_chars: answer.html_chars } : {}) };
|
|
51
82
|
}
|
|
52
|
-
/** The worker's answer to `job`,
|
|
53
|
-
|
|
83
|
+
/** The worker's answer to `job`, OUT_OF_MEMORY when it ran out of its `heapMb` heap, or null when it has not answered
|
|
84
|
+
* within `deadlineMs`, failed otherwise, or could not start. */
|
|
85
|
+
function inWorker(job, deadlineMs, heapMb, signal) {
|
|
54
86
|
return new Promise((resolve, reject) => {
|
|
55
87
|
let worker;
|
|
56
88
|
// execArgv: none of the host's own flags (a test runner's --import, say) reach the worker.
|
|
57
89
|
try {
|
|
58
|
-
worker = new Worker(new URL("./read-page-worker.js", import.meta.url), { workerData: job, execArgv: [], resourceLimits: { maxOldGenerationSizeMb:
|
|
90
|
+
worker = new Worker(new URL("./read-page-worker.js", import.meta.url), { workerData: job, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: Math.max(WORKER_HEAP_MIN_MB, heapMb) } });
|
|
59
91
|
}
|
|
60
92
|
catch {
|
|
61
93
|
resolve(null);
|
|
@@ -71,17 +103,28 @@ function inWorker(job, deadlineMs, signal) {
|
|
|
71
103
|
const timer = setTimeout(() => settle(() => resolve(null)), deadlineMs);
|
|
72
104
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
73
105
|
worker.once("message", (answer) => settle(() => resolve(typeof answer?.text === "string" ? answer : null)));
|
|
74
|
-
worker.once("error", () => settle(() => resolve(null)));
|
|
106
|
+
worker.once("error", (error) => settle(() => resolve(error?.code === "ERR_WORKER_OUT_OF_MEMORY" ? OUT_OF_MEMORY : null)));
|
|
75
107
|
worker.once("exit", () => settle(() => resolve(null)));
|
|
76
108
|
});
|
|
77
109
|
}
|
|
78
110
|
/** `html` without its inert blocks (InertDrop), STEP_CHARS at a time with the loop yielded between steps. */
|
|
79
111
|
export async function dropOnLoop(html, signal) {
|
|
80
112
|
const drop = new InertDrop(html);
|
|
81
|
-
|
|
113
|
+
await stepsOnLoop(drop, signal);
|
|
114
|
+
return drop.result();
|
|
115
|
+
}
|
|
116
|
+
/** Runs `pass` STEP_CHARS at a time, the loop yielded between steps, to its end. */
|
|
117
|
+
async function stepsOnLoop(pass, signal) {
|
|
118
|
+
while (!pass.step(STEP_CHARS)) {
|
|
82
119
|
await yieldToLoop();
|
|
83
120
|
signal?.throwIfAborted();
|
|
84
121
|
}
|
|
122
|
+
}
|
|
123
|
+
/** `html` without the elements it hides from everyone (HiddenDrop), with `page` what its own live styles declare
|
|
124
|
+
* (pageHidingOf), STEP_CHARS at a time with the loop yielded between steps. */
|
|
125
|
+
async function dropHiddenOnLoop(html, page, signal) {
|
|
126
|
+
const drop = new HiddenDrop(html, page, decodeEntities);
|
|
127
|
+
await stepsOnLoop(drop, signal);
|
|
85
128
|
return drop.result();
|
|
86
129
|
}
|
|
87
130
|
/** `html`'s plain text, title and links, scanned STEP_CHARS at a time with the loop yielded between steps. */
|
|
@@ -92,5 +135,6 @@ async function plainRead(html, url, signal) {
|
|
|
92
135
|
await yieldToLoop();
|
|
93
136
|
signal?.throwIfAborted();
|
|
94
137
|
}
|
|
95
|
-
|
|
138
|
+
const { title, text, links, linksCut } = scan.result();
|
|
139
|
+
return { title, text, links, ...(linksCut ? { links_truncated: true } : {}) };
|
|
96
140
|
}
|
package/dist/core/tools.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type BrowserDriver, type CustodyPort, type ToolOutput } from "./custody.js";
|
|
2
2
|
import { type EvidenceSink } from "./evidence.js";
|
|
3
3
|
import type { Decisions } from "./decisions.js";
|
|
4
|
+
import { type DownloadsWorkspace } from "./downloads.js";
|
|
4
5
|
import type { WorkspaceFiles } from "./host.js";
|
|
5
6
|
import { type RepeatGuard } from "./guard.js";
|
|
6
7
|
import { type Locate } from "./clip.js";
|
|
@@ -92,7 +93,7 @@ export type ToolCall = {
|
|
|
92
93
|
redact: Redact;
|
|
93
94
|
evidence: EvidenceSink;
|
|
94
95
|
classifyPage?: Decisions["classifyPage"];
|
|
95
|
-
workspace?:
|
|
96
|
+
workspace?: DownloadsWorkspace;
|
|
96
97
|
files?: WorkspaceFiles;
|
|
97
98
|
};
|
|
98
99
|
export type ToolImpl<D extends BrowserDriver = BrowserDriver, A = unknown> = (args: A, port: CustodyPort<D>, call: ToolCall) => Promise<ToolOutput>;
|
|
@@ -118,6 +119,7 @@ export type BrowserToolArgs = {
|
|
|
118
119
|
};
|
|
119
120
|
id?: string;
|
|
120
121
|
selector?: string;
|
|
122
|
+
save_as?: string;
|
|
121
123
|
};
|
|
122
124
|
browser_read: {
|
|
123
125
|
what?: (typeof WHATS)[number];
|
|
@@ -157,6 +159,26 @@ type Lost = {
|
|
|
157
159
|
/** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
|
|
158
160
|
* them): they were not sent, so the model may send them again. */
|
|
159
161
|
export declare const lostRequests: (lost: readonly Lost[]) => string;
|
|
162
|
+
/** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
|
|
163
|
+
* (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
|
|
164
|
+
* or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
|
|
165
|
+
* capture as it was asked (a JPEG unless type says png, which is refused). */
|
|
166
|
+
export declare function savePlanOf(given: unknown, type: "png" | "jpeg" | undefined): {
|
|
167
|
+
path: string;
|
|
168
|
+
format: "png" | "jpeg";
|
|
169
|
+
} | {
|
|
170
|
+
refused: string;
|
|
171
|
+
};
|
|
172
|
+
/** What became of a screenshot's save_as: saved at `path`, or not, with the reason in a word and in a sentence. */
|
|
173
|
+
export type SaveOutcome = {
|
|
174
|
+
path: string;
|
|
175
|
+
saved: true;
|
|
176
|
+
} | {
|
|
177
|
+
path: string;
|
|
178
|
+
saved: false;
|
|
179
|
+
reason: "format_changed" | "refused";
|
|
180
|
+
message: string;
|
|
181
|
+
};
|
|
160
182
|
export declare function pageTools({ guards, reconnect: timings, readDeadlineMs }?: {
|
|
161
183
|
/** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
|
|
162
184
|
guards?: Map<number, RepeatGuard>;
|
package/dist/core/tools.js
CHANGED
|
@@ -3,6 +3,7 @@ import { BrowserFailureError, FenceRefusal, refusedError, loadedNoPage, passedTh
|
|
|
3
3
|
import { defaultInline } from "./evidence.js";
|
|
4
4
|
import { fetchDownloads } from "./downloads.js";
|
|
5
5
|
import { asPartial, browserFailure, classifyBrowserError, partialOf, transportFactOf } from "./failures.js";
|
|
6
|
+
import { workspacePathRefusal } from "./files.js";
|
|
6
7
|
import { createRepeatGuard } from "./guard.js";
|
|
7
8
|
import { regionOf } from "./clip.js";
|
|
8
9
|
import { captureWithinBudget } from "./images.js";
|
|
@@ -69,6 +70,35 @@ const lostOf = (error) => (error !== null && typeof error === "object" ? (error[
|
|
|
69
70
|
/** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
|
|
70
71
|
* them): they were not sent, so the model may send them again. */
|
|
71
72
|
export const lostRequests = (lost) => `The browser lost ${lost.length === 1 ? "a request" : `${lost.length} requests`} your page made before ${lost.length === 1 ? "the request" : "they"} left the browser: ${lost.map((r) => `${r.method} ${r.url}`).join(", ")}. Chrome's network service restarted while ${lost.length === 1 ? "it was" : "they were"} on ${lost.length === 1 ? "its" : "their"} way, so ${lost.length === 1 ? "the request was" : "the requests were"} not sent. Make ${lost.length === 1 ? "it" : "them"} again if you still need ${lost.length === 1 ? "it" : "them"}.`;
|
|
73
|
+
/** Where a screenshot's `save_as` saves it and in which format, or why it is refused: a path relative to the workspace
|
|
74
|
+
* (workspacePathRefusal), its folders separated by "/" alone (as computer_screenshot's save_as), naming a .png, .jpg
|
|
75
|
+
* or .jpeg file, whose format agrees with `type` when it is given. A .png name asks for a PNG; a .jpg name leaves the
|
|
76
|
+
* capture as it was asked (a JPEG unless type says png, which is refused). */
|
|
77
|
+
export function savePlanOf(given, type) {
|
|
78
|
+
const bad = workspacePathRefusal(given);
|
|
79
|
+
if (bad)
|
|
80
|
+
return { refused: `save_as: ${bad}` };
|
|
81
|
+
// One separator, so the path the run's gate reads is the path written: a backslash is refused, never read as a "/".
|
|
82
|
+
if (given.includes("\\"))
|
|
83
|
+
return { refused: `save_as separates folders with "/", never a backslash: not ${JSON.stringify(given)}` };
|
|
84
|
+
const path = given.split("/").filter((part) => part !== "" && part !== ".").join("/");
|
|
85
|
+
const format = /\.png$/i.test(path) ? "png" : /\.jpe?g$/i.test(path) ? "jpeg" : null;
|
|
86
|
+
if (!format || /(^|\/)\.(png|jpe?g)$/i.test(path))
|
|
87
|
+
return { refused: `save_as names a .png, .jpg or .jpeg file: not ${JSON.stringify(given)}` };
|
|
88
|
+
if (type !== undefined && type !== format)
|
|
89
|
+
return { refused: `save_as ${JSON.stringify(given)} names a ${format === "png" ? "PNG" : "JPEG"} file, and type asks for ${type === "png" ? "a PNG" : "a JPEG"}: give a name that matches type, or leave type out` };
|
|
90
|
+
return { path, format };
|
|
91
|
+
}
|
|
92
|
+
/** The capture's own bytes (the ones filed as evidence) written at the plan's path through the host's write, unless the
|
|
93
|
+
* capture came back in another format than the name says (a PNG over the size budget is retaken as a JPEG): a file
|
|
94
|
+
* whose bytes are not what its name says is never written. */
|
|
95
|
+
async function saveCapture(plan, taken, bytes, write) {
|
|
96
|
+
if (taken !== plan.format) {
|
|
97
|
+
return { path: plan.path, saved: false, reason: "format_changed", message: `the ${plan.format === "png" ? "PNG" : "JPEG"} was over the size budget and was taken as a ${taken === "png" ? "PNG" : "JPEG"}, so it was not saved as ${plan.path}; save a .${taken === "png" ? "png" : "jpg"} name, or capture a smaller region (clip, id or selector)` };
|
|
98
|
+
}
|
|
99
|
+
const out = await write(plan.path, bytes).catch((error) => ({ refused: `${plan.path} could not be written: ${error?.message ?? String(error)}` }));
|
|
100
|
+
return "refused" in out ? { path: plan.path, saved: false, reason: "refused", message: out.refused } : { path: out.path, saved: true };
|
|
101
|
+
}
|
|
72
102
|
/** A read of a browser that has loaded no page yet: it is fresh, and the next step is to navigate, to the replaced
|
|
73
103
|
* session's last page when there is one. */
|
|
74
104
|
function freshBrowser(replaced) {
|
|
@@ -412,8 +442,16 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
412
442
|
});
|
|
413
443
|
},
|
|
414
444
|
screenshot: (args, port, call) => {
|
|
415
|
-
const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, ...
|
|
445
|
+
const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, save_as: saveAs, ...asks } = args ?? {};
|
|
416
446
|
const ask = typeof asked === "string" && asked.trim() ? asked.trim() : undefined;
|
|
447
|
+
// A save_as is checked before any browser call, so a refused one captures and files nothing.
|
|
448
|
+
const plan = saveAs === undefined ? undefined : savePlanOf(saveAs, asks.type);
|
|
449
|
+
if (plan && "refused" in plan)
|
|
450
|
+
return Promise.resolve(text(browserFailure("refused", plan.refused), true));
|
|
451
|
+
const write = call.files?.write?.bind(call.files);
|
|
452
|
+
if (plan && !write)
|
|
453
|
+
return Promise.resolve(text(browserFailure("refused", "This host gives the browser no workspace to save a screenshot into."), true));
|
|
454
|
+
const requested = plan?.format === "png" ? { ...asks, type: "png" } : asks;
|
|
417
455
|
return perform("screenshot", args ?? {}, port, call, "read", async (s, news) => {
|
|
418
456
|
// A region goes through the same capture as the whole page, so whatever guards a capture guards a clipped one.
|
|
419
457
|
const region = await regionOf({ clip: wantedClip, id: wantedId, selector: wantedSelector, fullPage: requested.fullPage }, s.driver.locate?.bind(s.driver));
|
|
@@ -421,10 +459,14 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
421
459
|
const url = pageUrl(call, await s.driver.url());
|
|
422
460
|
const receipt = await file(s, call, { tool: "screenshot", args: region ? { ...requested, clip: region.clip, ...region.of } : requested, status: "ok", facts: { final_url: url }, body: Buffer.from(shot.data, "base64"), ext: shot.size.type === "png" ? "png" : "jpg" });
|
|
423
461
|
const first = shot.adjusted?.first;
|
|
424
|
-
const
|
|
425
|
-
const
|
|
462
|
+
const over = shot.adjusted?.why === "long_edge" ? "was over the 2,000 px long edge budget" : shot.adjusted?.why === "base64_bytes" ? "was over the size budget" : "could not be measured";
|
|
463
|
+
const taken = shot.options.clip ? "the clip" : shot.options.fullPage ? "the full page" : "the viewport";
|
|
464
|
+
const scaled = shot.options.scale !== undefined && shot.options.scale < 1 ? ", scaled down" : "";
|
|
465
|
+
const adjusted = shot.adjusted && `adjusted: the first capture${first ? ` (${first.width}x${first.height})` : ""} ${over}; this is ${taken} at ${shot.size.width}x${shot.size.height}${scaled}`;
|
|
466
|
+
const saved = plan && write ? await saveCapture(plan, shot.size.type, Buffer.from(shot.data, "base64"), write) : undefined;
|
|
467
|
+
const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted, saved && (saved.saved ? `saved: ${saved.path}` : `not saved: ${saved.message}`)].filter(Boolean).join("\n");
|
|
426
468
|
const media = { kind: "screenshot", path: receipt.bodyPath, mime: shot.mimeType, bytes: Buffer.from(shot.data, "base64").byteLength, width: shot.size.width, height: shot.size.height, ...(region ? { clip: region.clip, ...region.of } : {}), ...(ask ? { ask } : {}) };
|
|
427
|
-
return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media } };
|
|
469
|
+
return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, media, ...(saved ? { save_as: saved } : {}) } };
|
|
428
470
|
});
|
|
429
471
|
},
|
|
430
472
|
browser_read: (args, port, call) => {
|
package/dist/core/usage.d.ts
CHANGED
|
@@ -11,9 +11,12 @@ type Spent = SessionRecord["spent"];
|
|
|
11
11
|
export declare const startSpent: (createdAt: string) => Spent;
|
|
12
12
|
/** The record after a charge, with its list-priced dollars: the ones it already held plus this charge's when the price was the list's. `after` is what `sessionCharge` returned. */
|
|
13
13
|
export declare function withEstimate(before: Spent, after: Spent, listPriced: boolean): Spent;
|
|
14
|
-
/** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing.
|
|
14
|
+
/** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. A
|
|
15
|
+
* charge through an `at` before the record's `chargedThrough` bills no time (an earlier charge billed past it), and says
|
|
16
|
+
* by how much in `overbookedS`. */
|
|
15
17
|
export declare function sessionCharge(spent: Spent, at: string, prices: PriceTable, state?: PriceState, final?: boolean): {
|
|
16
18
|
spent: Spent;
|
|
17
19
|
usage: ToolUsage;
|
|
20
|
+
overbookedS?: number;
|
|
18
21
|
};
|
|
19
22
|
export {};
|
package/dist/core/usage.js
CHANGED
|
@@ -27,7 +27,9 @@ export function withEstimate(before, after, listPriced) {
|
|
|
27
27
|
const estimated = Math.round(((before.estimatedUsd ?? 0) + (listPriced ? added : 0)) * PICO) / PICO;
|
|
28
28
|
return estimated > 0 ? { ...after, estimatedUsd: estimated } : after;
|
|
29
29
|
}
|
|
30
|
-
/** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing.
|
|
30
|
+
/** `final` (the release) tops up to the provider's minimum and marks the record, so a retried release adds nothing. A
|
|
31
|
+
* charge through an `at` before the record's `chargedThrough` bills no time (an earlier charge billed past it), and says
|
|
32
|
+
* by how much in `overbookedS`. */
|
|
31
33
|
export function sessionCharge(spent, at, prices, state = "priced", final = false) {
|
|
32
34
|
if (spent.final)
|
|
33
35
|
return { spent, usage: toolUsage(0, state === "invalid" ? "invalid" : prices.sessionUsdPerHour === null || state !== "priced" ? "unpriced" : "priced") };
|
|
@@ -35,6 +37,7 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
|
|
|
35
37
|
// 59.99999999999999 s.
|
|
36
38
|
const before = Math.round(spent.seconds * 1000);
|
|
37
39
|
const elapsed = Math.max(0, Date.parse(at) - Date.parse(spent.chargedThrough));
|
|
40
|
+
const overbooked = Math.max(0, Date.parse(spent.chargedThrough) - Date.parse(at));
|
|
38
41
|
const charged = elapsed + (final ? Math.max(0, Math.round(prices.sessionMinimumS * 1000) - (before + elapsed)) : 0);
|
|
39
42
|
const price = prices.sessionUsdPerHour;
|
|
40
43
|
const priced = price !== null && state === "priced";
|
|
@@ -44,5 +47,5 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
|
|
|
44
47
|
const picos = Number(owed / HOUR_MS);
|
|
45
48
|
const carry = Number(owed % HOUR_MS);
|
|
46
49
|
const gap = priced ? "priced" : state === "invalid" ? "invalid" : "unpriced";
|
|
47
|
-
return { spent: { seconds: (before + charged) / 1000, usd: (Math.round(spent.usd * PICO) + picos) / PICO, chargedThrough: elapsed > 0 ? at : spent.chargedThrough, ...(final ? { final: true } : {}), ...(carry ? { carry } : {}) }, usage: toolUsage(picos / PICO, gap) };
|
|
50
|
+
return { spent: { seconds: (before + charged) / 1000, usd: (Math.round(spent.usd * PICO) + picos) / PICO, chargedThrough: elapsed > 0 ? at : spent.chargedThrough, ...(final ? { final: true } : {}), ...(carry ? { carry } : {}) }, usage: toolUsage(picos / PICO, gap), ...(overbooked > 0 ? { overbookedS: overbooked / 1000 } : {}) };
|
|
48
51
|
}
|
package/dist/core/vault.d.ts
CHANGED
|
@@ -19,17 +19,7 @@ export type CapturedState = {
|
|
|
19
19
|
/** Only cookies the allowed origins would be sent (see `cookieKept`). Partitioned cookies are not kept. */
|
|
20
20
|
cookies: VaultCookie[];
|
|
21
21
|
localStorage: Record<string, Record<string, string>>;
|
|
22
|
-
}
|
|
23
|
-
/** `origins`: the origins the context was captured for. A context holds a whole browser profile, so it is restored only for a request that covers EVERY one of them (`coversEveryOrigin`); one that records none is refused. */
|
|
24
|
-
| {
|
|
25
|
-
kind: "provider-context";
|
|
26
|
-
capturedAt: string;
|
|
27
|
-
provider: "browserbase" | "kernel";
|
|
28
|
-
contextId: string;
|
|
29
|
-
origins?: string[];
|
|
30
22
|
};
|
|
31
|
-
/** Whether `requested` includes every origin in `saved` (as scheme://host[:port], any order): a provider context is all-or-nothing, so a request for some of its origins would bring back the others' sign-ins. */
|
|
32
|
-
export declare function coversEveryOrigin(requested: readonly string[], saved: readonly string[] | undefined): boolean;
|
|
33
23
|
export interface SessionVaultPort {
|
|
34
24
|
/** At release and at the end of a handoff, and, for a context a new session made, right after the create (so a restart still finds it). The host supplied the origins; nothing outside them was captured.
|
|
35
25
|
* A capture has a deadline (20 s) after which nothing more is read or written, but a write already handed to this port cannot be recalled: ignore one whose `capturedAt` is older than the one you hold. */
|
package/dist/core/vault.js
CHANGED
|
@@ -11,19 +11,6 @@ export function clampSessionCookieAgeMs(requested) {
|
|
|
11
11
|
throw new RangeError("the session-cookie age cap is a positive number of milliseconds");
|
|
12
12
|
return Math.min(requested, MAX_SESSION_COOKIE_AGE_MS);
|
|
13
13
|
}
|
|
14
|
-
/** Whether `requested` includes every origin in `saved` (as scheme://host[:port], any order): a provider context is all-or-nothing, so a request for some of its origins would bring back the others' sign-ins. */
|
|
15
|
-
export function coversEveryOrigin(requested, saved) {
|
|
16
|
-
if (!saved || saved.length === 0)
|
|
17
|
-
return false;
|
|
18
|
-
const origin = (value) => { try {
|
|
19
|
-
return new URL(value).origin;
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
return null;
|
|
23
|
-
} };
|
|
24
|
-
const have = new Set(requested.map(origin));
|
|
25
|
-
return saved.every((value) => { const o = origin(value); return o !== null && have.has(o); });
|
|
26
|
-
}
|
|
27
14
|
const SESSION_KEY = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
28
15
|
/** The host's allowed origins, each `scheme://host[:port]` of http or https, normalised and de-duplicated; anything else is refused. */
|
|
29
16
|
export function vaultOrigins(origins) {
|
package/dist/driver/cdp.js
CHANGED
|
@@ -224,9 +224,9 @@ export function cdpDriver() {
|
|
|
224
224
|
const selector = place?.selector ?? null;
|
|
225
225
|
return page.evaluate(`(${LOCATE_JS}).call(document, ${JSON.stringify(selector)})`);
|
|
226
226
|
},
|
|
227
|
-
screenshot: async (
|
|
228
|
-
const data = await page.screenshot(
|
|
229
|
-
return { data, mimeType: type === "jpeg" ? "image/jpeg" : "image/png" };
|
|
227
|
+
screenshot: async (options) => {
|
|
228
|
+
const data = await page.screenshot(options);
|
|
229
|
+
return { data, mimeType: options.type === "jpeg" ? "image/jpeg" : "image/png" };
|
|
230
230
|
},
|
|
231
231
|
// One evaluate reads all four, so they are one document's.
|
|
232
232
|
page: () => page.evaluate(() => ({
|
|
@@ -205,12 +205,16 @@ export function pageDriver(stagehand, deadlines) {
|
|
|
205
205
|
selector = target.selector;
|
|
206
206
|
return await facade.run(locateCode(selector));
|
|
207
207
|
}),
|
|
208
|
+
// Stagehand's page.screenshot scales to its device's pixels or to one per CSS pixel, and only a clip: a scale below 1
|
|
209
|
+
// is a clip (the viewport's, when none is asked) at one image pixel per CSS pixel, which is no smaller than that on a
|
|
210
|
+
// display of one device pixel per CSS pixel. A full page it does not scale (captureWithinBudget takes the viewport).
|
|
208
211
|
screenshot: async ({ type = "png", quality, fullPage, scale, clip }) => {
|
|
212
|
+
const css = scale !== undefined && scale < 1;
|
|
209
213
|
// A clip is read from the viewport's corner, and the browser's own is from the document's: the scroll offset is added.
|
|
210
|
-
const
|
|
214
|
+
const view = clip || (css && !fullPage) ? await facade.run(`return await page.evaluate("({ x: scrollX, y: scrollY, width: innerWidth, height: innerHeight })");`) : null;
|
|
215
|
+
const region = view && (clip ? { ...clip, x: clip.x + view.x, y: clip.y + view.y } : view);
|
|
211
216
|
const bytes = await (await active()).screenshot({
|
|
212
|
-
type, ...(fullPage === undefined ? {} : { fullPage }), ...(
|
|
213
|
-
...(clip && origin ? { clip: { ...clip, x: clip.x + origin.x, y: clip.y + origin.y } } : {}),
|
|
217
|
+
type, ...(region ? { clip: region } : fullPage === undefined ? {} : { fullPage }), ...(css ? { scale: "css" } : {}),
|
|
214
218
|
// CDP takes a quality for jpeg only, and only as an integer.
|
|
215
219
|
...(type === "jpeg" && quality !== undefined ? { quality: Math.round(quality) } : {}),
|
|
216
220
|
});
|
|
@@ -12,7 +12,9 @@ export declare const SEALED_STAGEHAND: {
|
|
|
12
12
|
};
|
|
13
13
|
};
|
|
14
14
|
type StagehandModule = Pick<typeof import("@browserbasehq/stagehand"), "localBrowser" | "Stagehand">;
|
|
15
|
-
/** The batch deadline
|
|
15
|
+
/** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
|
|
16
|
+
export declare const DEFAULT_BATCH_TIMEOUT_MS = 60000;
|
|
17
|
+
/** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
|
|
16
18
|
* client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
|
|
17
19
|
* the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
|
|
18
20
|
* for tests: the Stagehand module the driver uses. */
|
package/dist/driver/stagehand.js
CHANGED
|
@@ -7,7 +7,9 @@ export const SEALED_STAGEHAND = {
|
|
|
7
7
|
cache: false,
|
|
8
8
|
model: { generate: async () => { throw new Error(STAGEHAND_INFERENCE_REFUSED); } },
|
|
9
9
|
};
|
|
10
|
-
/** The batch deadline
|
|
10
|
+
/** The batch deadline a caller that passes none in `DriverOptions` gets: 60 s, the facade's. */
|
|
11
|
+
export const DEFAULT_BATCH_TIMEOUT_MS = 60_000;
|
|
12
|
+
/** The batch deadline comes from `DriverOptions`; a caller that passes none gets `DEFAULT_BATCH_TIMEOUT_MS`. Stagehand allows one
|
|
11
13
|
* client per browser: an attach that fails or is cancelled after it connected disconnects again, and only then fails, so
|
|
12
14
|
* the next attach never meets its slot still taken (Stagehand bounds the disconnect: 10 s for the detach). `internals` is
|
|
13
15
|
* for tests: the Stagehand module the driver uses. */
|
|
@@ -20,7 +22,7 @@ export function stagehandDriver(internals = {}) {
|
|
|
20
22
|
const browser = await untilCancelled(attachStep(host)(connecting), signal, (late) => late.disconnect());
|
|
21
23
|
try {
|
|
22
24
|
const stagehand = await untilCancelled(Stagehand.create({ browser, ...SEALED_STAGEHAND }), signal, () => undefined);
|
|
23
|
-
return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ??
|
|
25
|
+
return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? DEFAULT_BATCH_TIMEOUT_MS });
|
|
24
26
|
}
|
|
25
27
|
catch (error) {
|
|
26
28
|
await browser.disconnect().catch(() => undefined);
|
package/dist/durable/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context } from "@earendil-works/chord";
|
|
1
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
2
2
|
import { type ConversationDocToken, type ConversationId, type DocumentReader, type Harness, type TaskId, type Tx } from "@earendil-works/pi-durable";
|
|
3
3
|
import type { BrowserConfig, BrowserProvider, HandoffOutcome, HandoffPort, InventoryRow, ReconcileReport, ReleaseReason, SessionChange, SessionRecord, SessionsState } from "../core/host.js";
|
|
4
4
|
import type { LeaseRef, LeaseState } from "../core/lease.js";
|
|
@@ -6,6 +6,7 @@ export declare const now: () => string;
|
|
|
6
6
|
/** Release attempts before custody is given up as `lost`, and status polls before a release is sent again. */
|
|
7
7
|
export declare const RELEASE_ATTEMPTS = 6;
|
|
8
8
|
export declare const CONFIRM_POLLS = 5;
|
|
9
|
+
/** `owed` adds to the row's owed ids, `told` takes those told off it (InventoryRow.owed). */
|
|
9
10
|
type Move = {
|
|
10
11
|
state: LeaseState;
|
|
11
12
|
resourceId?: string;
|
|
@@ -13,6 +14,8 @@ type Move = {
|
|
|
13
14
|
at: string;
|
|
14
15
|
notice?: "kept" | "lost";
|
|
15
16
|
handoff?: string;
|
|
17
|
+
owed?: string[];
|
|
18
|
+
told?: string[];
|
|
16
19
|
};
|
|
17
20
|
/** `found`: the ids an earlier attempt (or a task this one succeeds) released under the row's tag, kept until the release
|
|
18
21
|
* is billed: a provider's tag lookup lists running sessions only, so a later attempt no longer finds one it stopped. */
|
|
@@ -41,6 +44,8 @@ type HandoffResult = {
|
|
|
41
44
|
outcome: HandoffOutcome;
|
|
42
45
|
reason?: string;
|
|
43
46
|
};
|
|
47
|
+
/** When the provider made each session a tag lookup found, by id (InventoryRow.made). */
|
|
48
|
+
type Made = Record<string, string>;
|
|
44
49
|
export type StoreDeps = {
|
|
45
50
|
name: string;
|
|
46
51
|
Config: ConversationDocToken<BrowserConfig>;
|
|
@@ -59,8 +64,12 @@ export type StoreDeps = {
|
|
|
59
64
|
handedBack?(tag: string, fence: number): void;
|
|
60
65
|
/** A release task (an attempt, or its abort handler) had the provider release `tag`'s session, and the provider answered. */
|
|
61
66
|
stopped?(tag: string): void;
|
|
67
|
+
/** A release by `row`'s tag ended sessions besides the row's own (`ids`, each confirmed no longer running): a create
|
|
68
|
+
* retried behind the provider, or a create race, left them. Their time is on no record (durable.ts, onRaceReleased).
|
|
69
|
+
* `made`: when the provider made each, where a tag lookup said (InventoryRow.made). */
|
|
70
|
+
raced?(row: InventoryRow, ids: string[], made: Made): Promise<void>;
|
|
62
71
|
};
|
|
63
|
-
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook }: StoreDeps): {
|
|
72
|
+
export declare function custodyStore({ name, Config, Sessions, providerOf, emit, meter, bill, scrubbed, createDeadlineMs, handoff, handedBack, stopped: stoppedHook, raced }: StoreDeps): {
|
|
64
73
|
Inventory: import("@earendil-works/pi-durable").SessionDocToken<{
|
|
65
74
|
rows: Record<string, InventoryRow>;
|
|
66
75
|
}>;
|
|
@@ -69,7 +78,9 @@ export declare function custodyStore({ name, Config, Sessions, providerOf, emit,
|
|
|
69
78
|
begin: (tx: Tx, row: InventoryRow) => Promise<void>;
|
|
70
79
|
requestRelease: (tx: Tx, row: InventoryRow, reason: ReleaseReason, at: string, notBefore?: number) => Promise<void>;
|
|
71
80
|
bindByTag: (provider: BrowserProvider, row: InventoryRow, commit: (change: (tx: Tx) => Promise<void>) => Promise<unknown>, signal?: AbortSignal, found?: LeaseRef[]) => Promise<LeaseRef | null>;
|
|
72
|
-
emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string
|
|
81
|
+
emitReleased: (cid: ConversationId, tag: string, read: DocumentReader, context: Context, at?: string, found?: {
|
|
82
|
+
resourceId?: string;
|
|
83
|
+
}) => Promise<void>;
|
|
73
84
|
ReleaseTask: import("@earendil-works/pi-durable").Task<ReleaseInput, ReleaseState, {
|
|
74
85
|
released: number;
|
|
75
86
|
}, object>;
|