@parcha/pi-browser 0.1.0-beta.31 → 0.1.0-beta.310
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 +232 -0
- package/NOTICE +39 -4
- package/README.md +122 -236
- package/dist/core/contract.d.ts +9 -6
- package/dist/core/contract.js +27 -36
- package/dist/core/custody.d.ts +19 -2
- package/dist/core/custody.js +28 -6
- package/dist/core/downloads.d.ts +44 -3
- package/dist/core/downloads.js +94 -58
- package/dist/core/driving-guard.d.ts +20 -0
- package/dist/core/driving-guard.js +190 -23
- package/dist/core/driving.d.ts +56 -2
- package/dist/core/driving.js +189 -10
- package/dist/core/effects.d.ts +80 -6
- package/dist/core/effects.js +374 -41
- package/dist/core/evidence.d.ts +1 -1
- package/dist/core/failures.d.ts +15 -1
- package/dist/core/failures.js +7 -0
- package/dist/core/files.d.ts +20 -2
- package/dist/core/files.js +161 -10
- package/dist/core/host.d.ts +29 -77
- package/dist/core/images.d.ts +32 -4
- package/dist/core/images.js +81 -16
- package/dist/core/lease.d.ts +2 -1
- package/dist/core/page-scan.d.ts +81 -2
- package/dist/core/page-scan.js +487 -13
- package/dist/core/public-fetch.d.ts +70 -9
- package/dist/core/public-fetch.js +348 -51
- package/dist/core/read-page-worker.js +5 -4
- package/dist/core/read-page.d.ts +23 -8
- package/dist/core/read-page.js +64 -20
- package/dist/core/redact.d.ts +0 -2
- package/dist/core/redact.js +0 -32
- package/dist/core/session-control.d.ts +0 -2
- package/dist/core/session-control.js +0 -5
- package/dist/core/tools.d.ts +46 -1
- package/dist/core/tools.js +88 -12
- package/dist/core/usage.d.ts +4 -3
- package/dist/core/usage.js +5 -4
- package/dist/core/vault.d.ts +0 -10
- package/dist/core/vault.js +0 -13
- package/dist/core/web.d.ts +2 -111
- package/dist/core/web.js +0 -443
- package/dist/driver/cdp.d.ts +6 -0
- package/dist/driver/cdp.js +245 -0
- package/dist/driver/page-driver.js +110 -7
- package/dist/driver/sealed.d.ts +4 -12
- package/dist/driver/sealed.js +23 -37
- package/dist/driver/stagehand.d.ts +12 -15
- package/dist/driver/stagehand.js +21 -17
- package/dist/durable/result.d.ts +1 -2
- package/dist/durable/result.js +2 -2
- package/dist/durable/store.d.ts +17 -3
- package/dist/durable/store.js +231 -64
- package/dist/durable.d.ts +47 -17
- package/dist/durable.js +106 -105
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -3
- package/dist/live-view/index.d.ts +4 -1
- package/dist/live-view/index.js +5 -0
- package/dist/live-view/protocol.d.ts +39 -7
- package/dist/live-view/protocol.js +2 -0
- package/dist/live-view/provider.d.ts +2 -2
- package/dist/live-view/provider.js +2 -2
- package/dist/live-view/server.d.ts +55 -2
- package/dist/live-view/server.js +282 -35
- package/dist/live-view/stream.js +16 -3
- package/dist/live-view/viewer.js +106 -13
- package/dist/providers/cdp.d.ts +0 -1
- package/dist/providers/cdp.js +35 -13
- package/dist/providers/chrome-args.d.ts +3 -0
- package/dist/providers/chrome-args.js +13 -2
- package/dist/providers/profiles.d.ts +1 -15
- package/dist/providers/profiles.js +1 -64
- package/dist/providers/shared.d.ts +1 -47
- package/dist/providers/shared.js +1 -82
- package/dist/providers/worker-extension.d.ts +20 -1
- package/dist/providers/worker-extension.js +86 -7
- package/dist/testing/backend.d.ts +6 -24
- package/dist/testing/backend.js +7 -30
- package/dist/vault-session.d.ts +4 -7
- package/dist/vault-session.js +26 -81
- package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
- package/dist/vendor/browser-use-pi/ax.js +642 -0
- package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
- package/dist/vendor/browser-use-pi/cdp.js +106 -0
- package/dist/vendor/browser-use-pi/page.d.ts +29 -0
- package/dist/vendor/browser-use-pi/page.js +99 -0
- package/package.json +15 -46
- package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
- package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
- package/dist/coding-agent-local.d.ts +0 -12
- package/dist/coding-agent-local.js +0 -72
- package/dist/coding-agent.d.ts +0 -134
- package/dist/coding-agent.js +0 -641
- package/dist/core/sites.d.ts +0 -33
- package/dist/core/sites.js +0 -104
- package/dist/driver/extension-worker.d.ts +0 -9
- package/dist/driver/extension-worker.js +0 -185
- package/dist/durable/web.d.ts +0 -47
- package/dist/durable/web.js +0 -41
- package/dist/providers/assigned.d.ts +0 -18
- package/dist/providers/assigned.js +0 -75
- package/dist/providers/browserbase-net.d.ts +0 -12
- package/dist/providers/browserbase-net.js +0 -95
- package/dist/providers/browserbase.d.ts +0 -169
- package/dist/providers/browserbase.js +0 -319
- package/dist/providers/kernel.d.ts +0 -58
- package/dist/providers/kernel.js +0 -291
- package/dist/recorder/credential.d.ts +0 -9
- package/dist/recorder/credential.js +0 -49
- package/dist/recorder/follow.d.ts +0 -36
- package/dist/recorder/follow.js +0 -163
- package/dist/recorder/frames.d.ts +0 -87
- package/dist/recorder/frames.js +0 -377
- package/dist/recorder/index.d.ts +0 -4
- package/dist/recorder/index.js +0 -7
- package/dist/recorder/jpeg.d.ts +0 -8
- package/dist/recorder/jpeg.js +0 -70
- package/dist/recorder/track.d.ts +0 -107
- package/dist/recorder/track.js +0 -280
- package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
- package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
- /package/dist/{providers → core}/cdp-call.d.ts +0 -0
- /package/dist/{providers → core}/cdp-call.js +0 -0
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/redact.d.ts
CHANGED
|
@@ -16,7 +16,5 @@ export declare function redactContent<T extends {
|
|
|
16
16
|
/** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
|
|
17
17
|
* whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
|
|
18
18
|
export declare function hostLiveView(view: LiveView, redact: Redact): LiveView;
|
|
19
|
-
/** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
|
|
20
|
-
export declare function scrubFetchedUrl(raw: string, requested: string, redact: Redact): string;
|
|
21
19
|
/** Every string inside `value`, object keys included, passed through `redact`. */
|
|
22
20
|
export declare function redactDeep<T>(value: T, redact: Redact): T;
|
package/dist/core/redact.js
CHANGED
|
@@ -47,38 +47,6 @@ export function redactContent(content, redact) {
|
|
|
47
47
|
export function hostLiveView(view, redact) {
|
|
48
48
|
return { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, redact), title: page.title === null ? null : redact(page.title) })) };
|
|
49
49
|
}
|
|
50
|
-
/** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
|
|
51
|
-
export function scrubFetchedUrl(raw, requested, redact) {
|
|
52
|
-
let url, asked;
|
|
53
|
-
try {
|
|
54
|
-
url = new URL(raw);
|
|
55
|
-
}
|
|
56
|
-
catch {
|
|
57
|
-
return redact(raw);
|
|
58
|
-
}
|
|
59
|
-
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
60
|
-
return redact(raw);
|
|
61
|
-
try {
|
|
62
|
-
asked = new URL(requested);
|
|
63
|
-
}
|
|
64
|
-
catch {
|
|
65
|
-
return scrubPageUrl(raw, redact);
|
|
66
|
-
}
|
|
67
|
-
const decoded = (text) => { try {
|
|
68
|
-
return decodeURIComponent(text.replace(/\+/g, " "));
|
|
69
|
-
}
|
|
70
|
-
catch {
|
|
71
|
-
return text;
|
|
72
|
-
} };
|
|
73
|
-
const pairsOf = (search) => search.slice(1).split("&").filter(Boolean).map((pair) => {
|
|
74
|
-
const at = pair.indexOf("=");
|
|
75
|
-
return at < 0 ? { pair, key: pair, value: "" } : { pair, key: pair.slice(0, at), value: pair.slice(at + 1) };
|
|
76
|
-
});
|
|
77
|
-
const sent = new Set(pairsOf(asked.search).map(({ key, value }) => `${decoded(key)}\0${decoded(value)}`));
|
|
78
|
-
const query = pairsOf(url.search).map(({ pair, key, value }) => (sent.has(`${decoded(key)}\0${decoded(value)}`) ? pair : `${key}=${REDACTED}`));
|
|
79
|
-
const fragment = url.hash && url.hash === asked.hash ? url.hash : "";
|
|
80
|
-
return redact(`${url.protocol}//${url.host}${url.pathname}${query.length ? `?${query.join("&")}` : ""}${fragment}`);
|
|
81
|
-
}
|
|
82
50
|
/** Every string inside `value`, object keys included, passed through `redact`. */
|
|
83
51
|
export function redactDeep(value, redact) {
|
|
84
52
|
if (typeof value === "string")
|
|
@@ -23,5 +23,3 @@ export declare function idleTracker<K = string>(options: {
|
|
|
23
23
|
/** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
|
|
24
24
|
export declare const PROVIDER_KEY_ENV: readonly string[];
|
|
25
25
|
export declare const providerKeyValues: (env: NodeJS.ProcessEnv, host?: () => readonly string[]) => string[];
|
|
26
|
-
/** Runs one at a time, in arrival order: each starts once the one before it has settled, however that one ended. */
|
|
27
|
-
export declare function oneAtATime(): <T>(run: () => Promise<T>) => Promise<T>;
|
|
@@ -73,8 +73,3 @@ export function idleTracker(options) {
|
|
|
73
73
|
/** Every environment variable that holds a provider key: each redactor in either adapter scrubs their values. */
|
|
74
74
|
export const PROVIDER_KEY_ENV = Object.freeze(["BROWSERBASE_API_KEY", "BB_API_KEY", "KERNEL_API_KEY"]);
|
|
75
75
|
export const providerKeyValues = (env, host) => [...PROVIDER_KEY_ENV.map((name) => env[name] ?? "").filter(Boolean), ...(host?.() ?? [])];
|
|
76
|
-
/** Runs one at a time, in arrival order: each starts once the one before it has settled, however that one ended. */
|
|
77
|
-
export function oneAtATime() {
|
|
78
|
-
let turn = Promise.resolve();
|
|
79
|
-
return (run) => { const mine = turn.then(run, run); turn = mine.catch(() => undefined); return mine; };
|
|
80
|
-
}
|
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";
|
|
@@ -14,6 +15,9 @@ import type { Geo } from "./host.js";
|
|
|
14
15
|
* compiles the whole of it as a single expression (compiled, never run). Any other code reaches the driver unchanged. */
|
|
15
16
|
export declare function runnableCode(code: string): string;
|
|
16
17
|
export type RunAction = {
|
|
18
|
+
op: "goto";
|
|
19
|
+
url: string;
|
|
20
|
+
} | {
|
|
17
21
|
op: "click";
|
|
18
22
|
id: string;
|
|
19
23
|
} | {
|
|
@@ -41,15 +45,28 @@ export type PageDriver = BrowserDriver & {
|
|
|
41
45
|
snapshot(options?: {
|
|
42
46
|
includeIframes?: boolean;
|
|
43
47
|
}): Promise<string>;
|
|
48
|
+
/** `checked`: an action after the first of a run of several, sent alone (driving-guard sends a batch one action at a time)
|
|
49
|
+
* after the whole batch was checked against the page's snapshot: the page's address, which the batch's own earlier
|
|
50
|
+
* actions may have moved (a same-page link), is not checked against the snapshot again. Its ids still are. */
|
|
44
51
|
run(input: {
|
|
45
52
|
code?: string;
|
|
46
53
|
actions?: RunAction[];
|
|
54
|
+
checked?: true;
|
|
55
|
+
rest?: number;
|
|
47
56
|
}): Promise<unknown>;
|
|
57
|
+
/** Whether the last `run` moved the driver to another tab (it followed a tab the page opened, or left one that
|
|
58
|
+
* closed): the batch's actions after it name the old tab's ids, so driving-guard sends none of them. `rest`, given to
|
|
59
|
+
* `run`, is how many of the batch's actions follow the ones it was sent, for its answer to say they were not run.
|
|
60
|
+
* Optional: a driver that never changes tabs has neither. */
|
|
61
|
+
movedTab?(): boolean;
|
|
48
62
|
/** The page's URL, cheaply: no page content is read. */
|
|
49
63
|
url(): Promise<string>;
|
|
50
64
|
/** Drops every snapshot's element ids, so an action by an old id fails as a stale snapshot (a person changed the page, whatever its URL). Optional:
|
|
51
65
|
* a driver without ids has none to drop. */
|
|
52
66
|
forgetSnapshots?(): void;
|
|
67
|
+
/** Checks a run's actions against the page's latest snapshot (every id there, the page still its address) without
|
|
68
|
+
* sending any, failing as `run` would. Optional: a driver without it sends a run's actions as one batch. */
|
|
69
|
+
checkActions?(actions: RunAction[]): Promise<void>;
|
|
53
70
|
screenshot(options: ScreenshotOptions): Promise<{
|
|
54
71
|
data: string;
|
|
55
72
|
mimeType: string;
|
|
@@ -76,7 +93,7 @@ export type ToolCall = {
|
|
|
76
93
|
redact: Redact;
|
|
77
94
|
evidence: EvidenceSink;
|
|
78
95
|
classifyPage?: Decisions["classifyPage"];
|
|
79
|
-
workspace?:
|
|
96
|
+
workspace?: DownloadsWorkspace;
|
|
80
97
|
files?: WorkspaceFiles;
|
|
81
98
|
};
|
|
82
99
|
export type ToolImpl<D extends BrowserDriver = BrowserDriver, A = unknown> = (args: A, port: CustodyPort<D>, call: ToolCall) => Promise<ToolOutput>;
|
|
@@ -102,6 +119,7 @@ export type BrowserToolArgs = {
|
|
|
102
119
|
};
|
|
103
120
|
id?: string;
|
|
104
121
|
selector?: string;
|
|
122
|
+
save_as?: string;
|
|
105
123
|
};
|
|
106
124
|
browser_read: {
|
|
107
125
|
what?: (typeof WHATS)[number];
|
|
@@ -134,6 +152,33 @@ type ReconnectTimings = {
|
|
|
134
152
|
tryMs: number;
|
|
135
153
|
backoffMs: readonly number[];
|
|
136
154
|
};
|
|
155
|
+
type Lost = {
|
|
156
|
+
method: string;
|
|
157
|
+
url: string;
|
|
158
|
+
};
|
|
159
|
+
/** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
|
|
160
|
+
* them): they were not sent, so the model may send them again. */
|
|
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
|
+
};
|
|
137
182
|
export declare function pageTools({ guards, reconnect: timings, readDeadlineMs }?: {
|
|
138
183
|
/** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
|
|
139
184
|
guards?: Map<number, RepeatGuard>;
|
package/dist/core/tools.js
CHANGED
|
@@ -2,7 +2,8 @@ import { setImmediate as yieldToLoop } from "node:timers/promises";
|
|
|
2
2
|
import { BrowserFailureError, FenceRefusal, refusedError, loadedNoPage, passedThrough } from "./custody.js";
|
|
3
3
|
import { defaultInline } from "./evidence.js";
|
|
4
4
|
import { fetchDownloads } from "./downloads.js";
|
|
5
|
-
import { browserFailure, classifyBrowserError, transportFactOf } from "./failures.js";
|
|
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";
|
|
@@ -57,6 +58,47 @@ const pause = (ms, signal) => new Promise((resolve) => {
|
|
|
57
58
|
});
|
|
58
59
|
const text = (value, isError = false) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(isError ? { isError: true } : {}) });
|
|
59
60
|
const withNews = (news, body) => (news ? `${news}\n\n${body}` : body);
|
|
61
|
+
const LOST = Symbol("lost requests");
|
|
62
|
+
/** An action's error carries the requests its call lost (`lost` is filled by the flush in the `finally` that follows the
|
|
63
|
+
* throw), so the failure answer still tells them. */
|
|
64
|
+
const withLost = (error, lost) => {
|
|
65
|
+
const carrier = error !== null && typeof error === "object" ? error : Object.assign(new Error(String(error)), { cause: error });
|
|
66
|
+
Object.defineProperty(carrier, LOST, { value: lost, configurable: true });
|
|
67
|
+
return carrier;
|
|
68
|
+
};
|
|
69
|
+
const lostOf = (error) => (error !== null && typeof error === "object" ? (error[LOST] ?? []) : []);
|
|
70
|
+
/** Told to a call whose page sent requests the browser lost before they left it (Chrome's network service restarted under
|
|
71
|
+
* them): they were not sent, so the model may send them again. */
|
|
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
|
+
}
|
|
60
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
|
|
61
103
|
* session's last page when there is one. */
|
|
62
104
|
function freshBrowser(replaced) {
|
|
@@ -207,8 +249,8 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
207
249
|
if (call.signal?.aborted)
|
|
208
250
|
break;
|
|
209
251
|
}
|
|
210
|
-
// The try's attach is bounded by what is left of the budget: one that waits on the browser (
|
|
211
|
-
//
|
|
252
|
+
// The try's attach is bounded by what is left of the budget: one that waits on the browser (a connection held on
|
|
253
|
+
// the way) stops there instead of running past it. The timer is a ref'd one, cleared when the try ends, so a
|
|
212
254
|
// reconnect in progress keeps the process alive (AbortSignal.timeout's timer does not, and Node 22 then drains).
|
|
213
255
|
const deadline = new AbortController();
|
|
214
256
|
const timer = setTimeout(() => deadline.abort(new DOMException("the reconnect's budget ran out", "TimeoutError")), Math.max(0, until - Date.now()));
|
|
@@ -257,7 +299,17 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
257
299
|
const tell = (out) => (facts || previous ? { ...out, details: { ...out.details, ...(facts ? { pendingEffect: facts } : {}), ...(previous ? { previous_session: previous } : {}) } } : out);
|
|
258
300
|
const done = (out) => { guard.note(tool, args, null); return tell(out); };
|
|
259
301
|
// The notice leads a failure, never after its own keys: a call told nothing else first reads it.
|
|
260
|
-
|
|
302
|
+
// A run of several actions that dropped partway (driving-guard's partway): its failure says how many ran.
|
|
303
|
+
let partial;
|
|
304
|
+
// Requests the failed action's call lost: told in the failure's message and listed in details, as on success.
|
|
305
|
+
let lostOnError = [];
|
|
306
|
+
const fail = (given) => {
|
|
307
|
+
const failure = partial ? asPartial(given, partial) : given;
|
|
308
|
+
guard.note(tool, args, failure);
|
|
309
|
+
const told = lostOnError.length ? { ...failure, message: `${failure.message} ${lostRequests(lostOnError)}` } : failure;
|
|
310
|
+
const out = tell(text(news ? { notice: news, ...(previous ? { previous_session: previous } : {}), ...told } : told, true));
|
|
311
|
+
return lostOnError.length ? { ...out, details: { ...out.details, lost: lostOnError } } : out;
|
|
312
|
+
};
|
|
261
313
|
let cuts = [];
|
|
262
314
|
// A look after a refusal settles every refused cut in the chain whose warning a saved answer had already told; one this call is
|
|
263
315
|
// telling stays until a later look, so a process that dies before this answer is saved tells it again.
|
|
@@ -314,6 +366,8 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
314
366
|
return await looked(effect === null ? await body(s, news) : await dispatched(tool, port, call, s, effect, () => body(s, news)));
|
|
315
367
|
}
|
|
316
368
|
catch (error) {
|
|
369
|
+
partial = partialOf(error);
|
|
370
|
+
lostOnError = lostOf(error);
|
|
317
371
|
const failure = await failureOf(error, effectful, port, call, action);
|
|
318
372
|
if (failure.code !== "browser_unavailable" || error instanceof BrowserFailureError)
|
|
319
373
|
return fail(failure);
|
|
@@ -362,11 +416,15 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
362
416
|
const codeSha = sha256Hex(JSON.stringify(args.code ?? args.actions));
|
|
363
417
|
return perform("run", args, port, call, { effect: codeSha }, async (s, news) => {
|
|
364
418
|
const sent = [];
|
|
365
|
-
const
|
|
419
|
+
const lost = [];
|
|
420
|
+
const stop = s.effects?.record((row) => { sent.push({ method: row.method, url: call.redact(`${row.origin}${row.path}`), held: row.held }); return port.journal(row); }, (request) => { lost.push({ method: request.method, url: call.redact(`${request.origin}${request.path}`) }); });
|
|
366
421
|
let value;
|
|
367
422
|
try {
|
|
368
423
|
value = await s.driver.run(args.code !== undefined ? { code: runnableCode(args.code) } : { actions: args.actions });
|
|
369
424
|
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
throw withLost(error, lost);
|
|
427
|
+
}
|
|
370
428
|
finally {
|
|
371
429
|
await s.effects?.flush(call.signal).catch(() => undefined);
|
|
372
430
|
stop?.();
|
|
@@ -379,12 +437,21 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
379
437
|
}
|
|
380
438
|
const reported = args.actions !== undefined && value && typeof value === "object" && typeof value.url === "string" ? { ...value, url: pageUrl(call, value.url) } : value;
|
|
381
439
|
const shown = typeof reported === "string" ? reported : reported === undefined ? "(run completed; the code returned no value: end it with `return <value>` to get one back)" : JSON.stringify(reported, null, 2) ?? String(reported);
|
|
382
|
-
|
|
440
|
+
const told = lost.length ? `${shown}\n\n${lostRequests(lost)}` : shown;
|
|
441
|
+
return { ...text(withNews(news, told)), ...(sent.length || lost.length ? { details: { ...(sent.length ? { sent } : {}), ...(lost.length ? { lost } : {}) } } : {}) };
|
|
383
442
|
});
|
|
384
443
|
},
|
|
385
444
|
screenshot: (args, port, call) => {
|
|
386
|
-
const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, ...
|
|
445
|
+
const { ask: asked, clip: wantedClip, id: wantedId, selector: wantedSelector, save_as: saveAs, ...asks } = args ?? {};
|
|
387
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;
|
|
388
455
|
return perform("screenshot", args ?? {}, port, call, "read", async (s, news) => {
|
|
389
456
|
// A region goes through the same capture as the whole page, so whatever guards a capture guards a clipped one.
|
|
390
457
|
const region = await regionOf({ clip: wantedClip, id: wantedId, selector: wantedSelector, fullPage: requested.fullPage }, s.driver.locate?.bind(s.driver));
|
|
@@ -392,10 +459,14 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
392
459
|
const url = pageUrl(call, await s.driver.url());
|
|
393
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" });
|
|
394
461
|
const first = shot.adjusted?.first;
|
|
395
|
-
const
|
|
396
|
-
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");
|
|
397
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 } : {}) };
|
|
398
|
-
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 } : {}) } };
|
|
399
470
|
});
|
|
400
471
|
},
|
|
401
472
|
browser_read: (args, port, call) => {
|
|
@@ -442,15 +513,20 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT,
|
|
|
442
513
|
if (!s.driver.setInputFiles)
|
|
443
514
|
throw refusedError("This browser driver cannot set a file input.");
|
|
444
515
|
const sent = [];
|
|
445
|
-
const
|
|
516
|
+
const lost = [];
|
|
517
|
+
const stop = s.effects?.record((row) => { sent.push({ method: row.method, url: call.redact(`${row.origin}${row.path}`), held: row.held }); return port.journal(row); }, (request) => { lost.push({ method: request.method, url: call.redact(`${request.origin}${request.path}`) }); });
|
|
446
518
|
try {
|
|
447
519
|
await s.driver.setInputFiles(selector, { name: file.name, mimeType: file.mime, buffer: file.bytes });
|
|
448
520
|
}
|
|
521
|
+
catch (error) {
|
|
522
|
+
throw withLost(error, lost);
|
|
523
|
+
}
|
|
449
524
|
finally {
|
|
450
525
|
await s.effects?.flush(call.signal).catch(() => undefined);
|
|
451
526
|
stop?.();
|
|
452
527
|
}
|
|
453
|
-
|
|
528
|
+
const notice = [news, lost.length ? lostRequests(lost) : ""].filter(Boolean).join(" ");
|
|
529
|
+
return { content: [{ type: "text", text: JSON.stringify({ ok: true, uploaded, selector, ...(notice ? { notice } : {}) }) }], details: { uploaded, ...(sent.length ? { sent } : {}), ...(lost.length ? { lost } : {}) } };
|
|
454
530
|
});
|
|
455
531
|
},
|
|
456
532
|
browser_downloads: (args, port, call) => perform("browser_downloads", {}, port, call, "read", async (s, news) => {
|
package/dist/core/usage.d.ts
CHANGED
|
@@ -7,15 +7,16 @@ export declare function sessionPrice(raw: string | null | undefined): {
|
|
|
7
7
|
/** List prices with the host's overrides on top; an override of `null` is a deliberate gap. */
|
|
8
8
|
export declare const resolvePrices: (overrides?: Partial<PriceTable>) => PriceTable;
|
|
9
9
|
export declare const toolUsage: (usd: number, state?: PriceState) => ToolUsage;
|
|
10
|
-
export declare const fetchUsage: (prices: PriceTable, proxied: boolean) => ToolUsage;
|
|
11
|
-
export declare const searchUsage: (prices: PriceTable) => ToolUsage;
|
|
12
10
|
type Spent = SessionRecord["spent"];
|
|
13
11
|
export declare const startSpent: (createdAt: string) => Spent;
|
|
14
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. */
|
|
15
13
|
export declare function withEstimate(before: Spent, after: Spent, listPriced: boolean): Spent;
|
|
16
|
-
/** `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`. */
|
|
17
17
|
export declare function sessionCharge(spent: Spent, at: string, prices: PriceTable, state?: PriceState, final?: boolean): {
|
|
18
18
|
spent: Spent;
|
|
19
19
|
usage: ToolUsage;
|
|
20
|
+
overbookedS?: number;
|
|
20
21
|
};
|
|
21
22
|
export {};
|
package/dist/core/usage.js
CHANGED
|
@@ -17,8 +17,6 @@ export const toolUsage = (usd, state = "priced") => ({
|
|
|
17
17
|
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usd } },
|
|
18
18
|
state,
|
|
19
19
|
});
|
|
20
|
-
export const fetchUsage = (prices, proxied) => toolUsage(proxied ? prices.fetchProxiedUsd : prices.fetchUsd);
|
|
21
|
-
export const searchUsage = (prices) => toolUsage(prices.searchUsd);
|
|
22
20
|
/** Integer picodollars, so a bill reads as its decimal amount (0.002, not 0.0019999999999999996). */
|
|
23
21
|
const PICO = 1e12;
|
|
24
22
|
const HOUR_MS = 3600000n;
|
|
@@ -29,7 +27,9 @@ export function withEstimate(before, after, listPriced) {
|
|
|
29
27
|
const estimated = Math.round(((before.estimatedUsd ?? 0) + (listPriced ? added : 0)) * PICO) / PICO;
|
|
30
28
|
return estimated > 0 ? { ...after, estimatedUsd: estimated } : after;
|
|
31
29
|
}
|
|
32
|
-
/** `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`. */
|
|
33
33
|
export function sessionCharge(spent, at, prices, state = "priced", final = false) {
|
|
34
34
|
if (spent.final)
|
|
35
35
|
return { spent, usage: toolUsage(0, state === "invalid" ? "invalid" : prices.sessionUsdPerHour === null || state !== "priced" ? "unpriced" : "priced") };
|
|
@@ -37,6 +37,7 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
|
|
|
37
37
|
// 59.99999999999999 s.
|
|
38
38
|
const before = Math.round(spent.seconds * 1000);
|
|
39
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));
|
|
40
41
|
const charged = elapsed + (final ? Math.max(0, Math.round(prices.sessionMinimumS * 1000) - (before + elapsed)) : 0);
|
|
41
42
|
const price = prices.sessionUsdPerHour;
|
|
42
43
|
const priced = price !== null && state === "priced";
|
|
@@ -46,5 +47,5 @@ export function sessionCharge(spent, at, prices, state = "priced", final = false
|
|
|
46
47
|
const picos = Number(owed / HOUR_MS);
|
|
47
48
|
const carry = Number(owed % HOUR_MS);
|
|
48
49
|
const gap = priced ? "priced" : state === "invalid" ? "invalid" : "unpriced";
|
|
49
|
-
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 } : {}) };
|
|
50
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) {
|