@parcha/pi-browser 0.1.0-beta.69 → 0.1.0-beta.73
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 +10 -0
- package/NOTICE +4 -1
- package/dist/core/custody.d.ts +6 -0
- package/dist/core/custody.js +15 -3
- package/dist/core/public-fetch.d.ts +7 -5
- package/dist/core/public-fetch.js +85 -17
- package/dist/durable.js +4 -4
- package/dist/providers/worker-extension.d.ts +14 -1
- package/dist/providers/worker-extension.js +68 -2
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.73 (2026-11-29)
|
|
6
|
+
|
|
7
|
+
- The public-host guard (`publicFetch`, `publicDownload`, `publicCheck`) refuses a URL holding a user name or password itself, on the first hop and at every redirect, before that hop's name is resolved or anything is sent to it: `refused: the URL holds a user name or password`, or `refused: a redirect to a URL holding a user name or password`. The refusal never quotes the URL. Before, a redirect to such a URL was stopped only by undici's own `Request`, whose error quotes the URL whole, and a guard given another fetch followed it. Every hop now goes through the same checks, the first one's included: scheme, user name or password, then name, addresses and port. web_fetch's direct fetch, web_save's download and the server's fal file download answer such a redirect with the guard's refusal. <!-- changes/public-fetch-userinfo-every-hop.md -->
|
|
8
|
+
|
|
9
|
+
## 0.1.0-beta.70 (2026-11-29)
|
|
10
|
+
|
|
11
|
+
- A process that dies inside a browser run on a local Chrome is reattached at once. Before, Stagehand's extension kept the dead client's callback batch running until its own timeout (60 s by default) and held the new process's `Stagehand.create` behind it, so the reattach took about as long as Stagehand's 60 s init deadline and failed when the batch timeout was longer. The copy of the extension the cdp provider gives a local Chrome now aborts a gone client's running batches when the extension releases it. The copy carries Stagehand's LICENSE and a NOTICE saying what changed. A Stagehand release whose worker has moved the code the change rewrites is refused by name at launch. The change isn't applied to a browser that brings its own copy of the extension (Browserbase), which still waits until Stagehand fixes this upstream. A local launch with no private TMPDIR (Windows, or a host temp path too long for one) already runs Stagehand's own extension directory unconfined, so it doesn't get the change either and still waits, like Browserbase. pi-browser now pins Stagehand 4.4.0 exactly, the version the change was written against. <!-- changes/pi-browser-reattach-ends-dead-batch.md -->
|
|
12
|
+
- A host's `close` release of a conversation's browser (`BrowserExtensionHandle.release(…, "close")`) now waits up to 2 s for the conversation's drivers to close before it records the release, and only then ends the session at the provider. Before, the session's end started alongside the driver's close, so a Stagehand driver could send its close and detach to a Chrome that was already gone. If its socket never said so (a path that hides the far end's close), it waited out both of Stagehand's 10 s disconnect bounds. A driver that answers fast now gets both answered first. One that hasn't answered by 2 s (`DRIVER_ACK_BEFORE_KILL_MS`) is not waited for, so a wedged close holds up the session's end by 2 s at most, never its full 25 s close bound. Releases for any other reason are unchanged. <!-- changes/pi-browser-release-ack-before-kill.md -->
|
|
13
|
+
- `publicFetch` decodes a text page by the charset it declares, so a Latin-1 or Shift_JIS page reads as its words instead of U+FFFD. The charset is the Content-Type's `charset`, else (an HTML page) a `<meta charset>` or `<meta http-equiv="Content-Type">` in its first 1024 bytes, else UTF-8. A label no encoding goes by is passed over, and a `<meta>` naming UTF-16 reads as UTF-8, as a browser reads it. serve's default `web_fetch` reads pages through it. <!-- changes/public-fetch-page-charset.md -->
|
|
14
|
+
|
|
5
15
|
## 0.1.0-beta.69 (2026-11-28)
|
|
6
16
|
|
|
7
17
|
- `@parcha/pi-browser/driver/stagehand` exports `DEFAULT_BATCH_TIMEOUT_MS` (60 000), the batch deadline the Stagehand driver uses when it is given none. <!-- changes/pi-browser-default-batch-timeout-export.md -->
|
package/NOTICE
CHANGED
|
@@ -3,7 +3,7 @@ Copyright 2026 Parcha Labs, Inc.
|
|
|
3
3
|
|
|
4
4
|
The boxd computer provider (packages/computer/src/boxd.ts) was contributed by Michiel Voortman.
|
|
5
5
|
|
|
6
|
-
This package contains
|
|
6
|
+
This package contains three pieces of Stagehand (https://github.com/browserbase/stagehand), all under its MIT license,
|
|
7
7
|
whose text follows:
|
|
8
8
|
|
|
9
9
|
- The Chrome launch flags in src/providers/chrome-args.ts, copied from Stagehand 4.1.0's
|
|
@@ -11,6 +11,9 @@ whose text follows:
|
|
|
11
11
|
- The files in src/vendor/stagehand-facade (compiled to dist/vendor/stagehand-facade), copied from Stagehand 4.1.0's
|
|
12
12
|
packages/integrations/core/src/facade at commit cd7b230778cf92269e4cb90e80d97f5113781c51. UPSTREAM.json, shipped
|
|
13
13
|
beside them as src/vendor/stagehand-facade/UPSTREAM.json, records each file's upstream blob and SHA-256.
|
|
14
|
+
- The lines of Stagehand 4.4.0's dist/extension/service-worker.js that src/providers/worker-extension.ts quotes, and
|
|
15
|
+
rewrites in the copy of Stagehand's extension it gives a local Chrome. That copy carries Stagehand's LICENSE and a
|
|
16
|
+
NOTICE naming what changed in it.
|
|
14
17
|
|
|
15
18
|
MIT License
|
|
16
19
|
|
package/dist/core/custody.d.ts
CHANGED
|
@@ -10,6 +10,12 @@ export type BrowserDriver = {
|
|
|
10
10
|
* for the detach): a shorter wait could return while the client is still attached, and the next attach to the browser is
|
|
11
11
|
* refused until it has let go. */
|
|
12
12
|
export declare const DRIVER_CLOSE_MS = 25000;
|
|
13
|
+
/** How long a "close" release lets its drivers' close run before it ends the session: a live browser
|
|
14
|
+
* answers Stagehand's close and detach in well under a second, and one ended first leaves them nothing to answer. A
|
|
15
|
+
* close that has not come back by then is not waited for, so ending the session is never held up past this. */
|
|
16
|
+
export declare const DRIVER_ACK_BEFORE_KILL_MS = 2000;
|
|
17
|
+
/** Resolves once `work` settles, either way, or after `ms`, whichever is first; its timer goes with it. */
|
|
18
|
+
export declare function settledWithin(work: Promise<unknown>, ms: number): Promise<void>;
|
|
13
19
|
/** A close that fails is not the caller's: the session goes on or is released either way. */
|
|
14
20
|
export declare function closeDriver(driver: BrowserDriver): Promise<void>;
|
|
15
21
|
export type DriverOptions = {
|
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;
|
|
@@ -35,23 +35,25 @@ export type PublicFile = {
|
|
|
35
35
|
bytes: Uint8Array | null;
|
|
36
36
|
};
|
|
37
37
|
type Lookup = (host: string) => Promise<string[]>;
|
|
38
|
-
/** Whether publicFetch's first hop would be dialled for `url`:
|
|
39
|
-
* Resolves when it passes; throws publicFetch's own refusal when it does not. */
|
|
38
|
+
/** Whether publicFetch's first hop would be dialled for `url`: hopUrl's and hopAddresses' checks, http(s), with nothing
|
|
39
|
+
* sent. Resolves when it passes; throws publicFetch's own refusal when it does not. */
|
|
40
40
|
export declare function publicCheck(url: string, options?: {
|
|
41
41
|
lookup?: Lookup;
|
|
42
42
|
signal?: AbortSignal;
|
|
43
43
|
}): Promise<void>;
|
|
44
44
|
/**
|
|
45
45
|
* Fetches `url` from a public host, following at most 5 redirects (or `maxRedirects`), each hop resolved, checked and dialled at the
|
|
46
|
-
* address checked. A 2xx answer of a text type is read whole, up to `maxBytes
|
|
46
|
+
* address checked. A 2xx answer of a text type is read whole, up to `maxBytes`, and
|
|
47
|
+
* decoded by the charset it declares (pageText); another status comes back without its
|
|
47
48
|
* body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s) (other
|
|
48
|
-
* than https, with `httpsOnly`); a host that is local by name or resolves to any
|
|
49
|
+
* than https, with `httpsOnly`); a URL holding a user name or password; a host that is local by name or resolves to any
|
|
50
|
+
* private address; a port other than 80
|
|
49
51
|
* or 443; too many redirects (any, with `maxRedirects` 0); a 2xx body that is not text or is over the cap. `signal` ends the fetch at any point, a
|
|
50
52
|
* hop's name lookup included (it rejects with the signal's reason), and an aborted hop is never dialled.
|
|
51
53
|
*/
|
|
52
54
|
export declare function publicFetch(url: string, options?: PublicFetchOptions): Promise<PublicAnswer>;
|
|
53
55
|
/**
|
|
54
|
-
* Downloads `url` from a public host: publicFetch's hops and refusals (scheme, local or private host, port, redirects,
|
|
56
|
+
* Downloads `url` from a public host: publicFetch's hops and refusals (scheme, user name or password, local or private host, port, redirects,
|
|
55
57
|
* the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
|
|
56
58
|
* is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
|
|
57
59
|
* <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
|
|
@@ -73,6 +73,67 @@ function untilAborted(work, signal) {
|
|
|
73
73
|
* or application/<name>+json (atom, rss, xhtml, ld+json), so a site's feed reads like its pages. Anything else (a PDF,
|
|
74
74
|
* a zip, octet-stream, an image/svg+xml) is refused. */
|
|
75
75
|
const TEXT_TYPE = /^(text\/|application\/(json|xml|[\w.!#$&^-]+\+(xml|json)\b))/i;
|
|
76
|
+
/** The types whose own <meta> may name their charset: HTML and XHTML. */
|
|
77
|
+
const HTML_TYPE = /^(text\/html|application\/xhtml\+xml)\s*(;|$)/i;
|
|
78
|
+
/** How far into a page a <meta> charset counts: the first 1024 bytes, as a browser's prescan reads. */
|
|
79
|
+
const PRESCAN_BYTES = 1024;
|
|
80
|
+
/** The charset a `charset=` parameter in `words` names (a Content-Type, or a <meta http-equiv> tag's content), quotes
|
|
81
|
+
* taken off; undefined when there is none. */
|
|
82
|
+
const charsetParam = (words) => /(?:^|[;\s])charset\s*=\s*["']?([^"';\s]+)/i.exec(words)?.[1];
|
|
83
|
+
/** A decoder for `label`, or undefined when no encoding goes by it. A page's <meta> naming UTF-16 is read as UTF-8, as a
|
|
84
|
+
* browser does: a page whose bytes are UTF-16 could not have spelled the tag in ASCII. */
|
|
85
|
+
function decoderFor(label, fromMeta) {
|
|
86
|
+
if (label === undefined)
|
|
87
|
+
return undefined;
|
|
88
|
+
let decoder;
|
|
89
|
+
try {
|
|
90
|
+
decoder = new TextDecoder(label);
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
return fromMeta && decoder.encoding.startsWith("utf-16") ? new TextDecoder("utf-8") : decoder;
|
|
96
|
+
}
|
|
97
|
+
/** A decoder for the charset an HTML page's own <meta> names in its first 1024 bytes: the first `<meta charset>` or
|
|
98
|
+
* `<meta http-equiv="Content-Type" content="...; charset=...">` whose label an encoding goes by, as a browser's
|
|
99
|
+
* prescan takes it. A tag inside a comment is not read. Undefined when none does. */
|
|
100
|
+
function metaDecoder(bytes) {
|
|
101
|
+
// latin1 maps each byte to one char: an ASCII tag reads the same whatever the page's charset. A comment, and one left
|
|
102
|
+
// open at the scan's end, is dropped first.
|
|
103
|
+
const head = Buffer.from(bytes.buffer, bytes.byteOffset, Math.min(bytes.byteLength, PRESCAN_BYTES)).toString("latin1").replace(/<!--[\s\S]*?(?:-->|$)/g, "");
|
|
104
|
+
for (const [tag] of head.matchAll(/<meta\b[^>]*>/gi)) {
|
|
105
|
+
const attributes = new Map();
|
|
106
|
+
for (const [, name, double, single, bare] of tag.slice(5).matchAll(/([^\s"'>/=]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/g)) {
|
|
107
|
+
const key = name.toLowerCase();
|
|
108
|
+
if (!attributes.has(key))
|
|
109
|
+
attributes.set(key, (double ?? single ?? bare ?? "").trim());
|
|
110
|
+
}
|
|
111
|
+
const charset = attributes.get("charset");
|
|
112
|
+
const said = charset ? charset : attributes.get("http-equiv")?.toLowerCase() === "content-type" ? charsetParam(attributes.get("content") ?? "") : undefined;
|
|
113
|
+
const decoder = decoderFor(said, true);
|
|
114
|
+
if (decoder)
|
|
115
|
+
return decoder;
|
|
116
|
+
}
|
|
117
|
+
return undefined;
|
|
118
|
+
}
|
|
119
|
+
/** The encoding a page's byte order mark names (UTF-8, UTF-16LE, UTF-16BE), or undefined with none. */
|
|
120
|
+
function bomEncoding(bytes) {
|
|
121
|
+
if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)
|
|
122
|
+
return "utf-8";
|
|
123
|
+
if (bytes[0] === 0xff && bytes[1] === 0xfe)
|
|
124
|
+
return "utf-16le";
|
|
125
|
+
if (bytes[0] === 0xfe && bytes[1] === 0xff)
|
|
126
|
+
return "utf-16be";
|
|
127
|
+
return undefined;
|
|
128
|
+
}
|
|
129
|
+
/** A text page's `bytes` as text, decoded as a browser decodes it: by its byte order mark, else its Content-Type's
|
|
130
|
+
* `charset`, else (an HTML page) its <meta> charset in the first 1024 bytes, else UTF-8. A label no encoding goes by is
|
|
131
|
+
* passed over for the next. The mark itself is not kept. Bytes the charset cannot read become U+FFFD. */
|
|
132
|
+
function pageText(bytes, contentType) {
|
|
133
|
+
const bom = bomEncoding(bytes);
|
|
134
|
+
const decoder = (bom ? new TextDecoder(bom) : undefined) ?? decoderFor(charsetParam(contentType), false) ?? (HTML_TYPE.test(contentType) ? metaDecoder(bytes) : undefined) ?? new TextDecoder("utf-8");
|
|
135
|
+
return decoder.decode(bytes);
|
|
136
|
+
}
|
|
76
137
|
const MIB = 1024 * 1024;
|
|
77
138
|
/** The options checked before any lookup: `maxBytes` (default 5 MiB) a whole number of bytes above 0, and
|
|
78
139
|
* `maxRedirects` a whole number from 0 to 5. */
|
|
@@ -102,29 +163,36 @@ async function hopAddresses(target, lookup, signal) {
|
|
|
102
163
|
signal?.throwIfAborted();
|
|
103
164
|
return addresses;
|
|
104
165
|
}
|
|
105
|
-
/**
|
|
106
|
-
*
|
|
166
|
+
/** One hop's URL checks, before its name is resolved: its scheme matches `scheme`, and it holds no user name or password
|
|
167
|
+
* (no credentials go out, and undici's own refusal of such a URL quotes it whole). `redirected` when the hop is a
|
|
168
|
+
* redirect's target. The refusal never quotes the URL. */
|
|
169
|
+
function hopUrl(target, [scheme, schemeName], redirected) {
|
|
170
|
+
if (!scheme.test(target.protocol))
|
|
171
|
+
throw refusedError(redirected ? `refused: a redirect left ${schemeName}` : `refused: ${target.protocol} is not ${schemeName}`);
|
|
172
|
+
if (target.username || target.password)
|
|
173
|
+
throw refusedError(`refused: ${redirected ? "a redirect to a URL holding" : "the URL holds"} a user name or password`);
|
|
174
|
+
}
|
|
175
|
+
/** Whether publicFetch's first hop would be dialled for `url`: hopUrl's and hopAddresses' checks, http(s), with nothing
|
|
176
|
+
* sent. Resolves when it passes; throws publicFetch's own refusal when it does not. */
|
|
107
177
|
export async function publicCheck(url, options = {}) {
|
|
108
178
|
const target = new URL(url);
|
|
109
|
-
|
|
110
|
-
throw refusedError(`refused: ${target.protocol} is not http(s)`);
|
|
179
|
+
hopUrl(target, [/^https?:$/, "http(s)"], false);
|
|
111
180
|
await hopAddresses(target, options.lookup ?? systemLookup, options.signal);
|
|
112
181
|
}
|
|
113
182
|
/**
|
|
114
|
-
* The hop loop both answers share: `url` fetched from a public host, following at most 5 redirects, each hop
|
|
115
|
-
* checked and dialled at the address checked, asking for
|
|
116
|
-
* which reads what it needs of it; whatever it leaves
|
|
117
|
-
* returns or throws.
|
|
183
|
+
* The hop loop both answers share: `url` fetched from a public host, following at most 5 redirects, each hop, the first
|
|
184
|
+
* and every redirect's alike, checked (hopUrl, then hopAddresses) and dialled at the address checked, asking for
|
|
185
|
+
* `accept`. The answer that ends the redirects goes to `answer`, which reads what it needs of it; whatever it leaves
|
|
186
|
+
* unread is cancelled, and the hop's connection closed, once it returns or throws.
|
|
118
187
|
*/
|
|
119
188
|
async function publicHops(url, options, accept, answer) {
|
|
120
189
|
const lookup = options.lookup ?? systemLookup;
|
|
121
190
|
const request = options.fetchImpl ?? ((target, init) => undiciFetch(target, init));
|
|
122
|
-
const
|
|
191
|
+
const scheme = options.httpsOnly ? [/^https:$/, "https"] : [/^https?:$/, "http(s)"];
|
|
123
192
|
const most = options.maxRedirects ?? MAX_REDIRECTS;
|
|
124
193
|
let target = new URL(url);
|
|
125
|
-
if (!scheme.test(target.protocol))
|
|
126
|
-
throw refusedError(`refused: ${target.protocol} is not ${schemeName}`);
|
|
127
194
|
for (let hop = 0;; hop += 1) {
|
|
195
|
+
hopUrl(target, scheme, hop > 0);
|
|
128
196
|
const addresses = await hopAddresses(target, lookup, options.signal);
|
|
129
197
|
const dispatcher = new Agent({ connect: { lookup: pinnedLookup(addresses[0]) } });
|
|
130
198
|
let res;
|
|
@@ -134,8 +202,6 @@ async function publicHops(url, options, accept, answer) {
|
|
|
134
202
|
if (hop >= most)
|
|
135
203
|
throw refusedError(most === 0 ? "refused: a redirect, and this download follows none" : "refused: too many redirects");
|
|
136
204
|
target = new URL(res.headers.get("location"), target);
|
|
137
|
-
if (!scheme.test(target.protocol))
|
|
138
|
-
throw refusedError(`refused: a redirect left ${schemeName}`);
|
|
139
205
|
continue;
|
|
140
206
|
}
|
|
141
207
|
return await answer(res, target);
|
|
@@ -204,9 +270,11 @@ function statedLength(headers) {
|
|
|
204
270
|
}
|
|
205
271
|
/**
|
|
206
272
|
* Fetches `url` from a public host, following at most 5 redirects (or `maxRedirects`), each hop resolved, checked and dialled at the
|
|
207
|
-
* address checked. A 2xx answer of a text type is read whole, up to `maxBytes
|
|
273
|
+
* address checked. A 2xx answer of a text type is read whole, up to `maxBytes`, and
|
|
274
|
+
* decoded by the charset it declares (pageText); another status comes back without its
|
|
208
275
|
* body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s) (other
|
|
209
|
-
* than https, with `httpsOnly`); a host that is local by name or resolves to any
|
|
276
|
+
* than https, with `httpsOnly`); a URL holding a user name or password; a host that is local by name or resolves to any
|
|
277
|
+
* private address; a port other than 80
|
|
210
278
|
* or 443; too many redirects (any, with `maxRedirects` 0); a 2xx body that is not text or is over the cap. `signal` ends the fetch at any point, a
|
|
211
279
|
* hop's name lookup included (it rejects with the signal's reason), and an aborted hop is never dialled.
|
|
212
280
|
*/
|
|
@@ -222,11 +290,11 @@ export async function publicFetch(url, options = {}) {
|
|
|
222
290
|
if (!TEXT_TYPE.test(contentType))
|
|
223
291
|
throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
|
|
224
292
|
const body = await readCapped(res.body, maxBytes, `refused: the page is over ${maxBytes === PUBLIC_MAX_BYTES ? "5 MiB" : `${maxBytes} bytes`}`);
|
|
225
|
-
return { url: target.href, status: res.status, contentType, body: body
|
|
293
|
+
return { url: target.href, status: res.status, contentType, body: pageText(body, contentType) };
|
|
226
294
|
});
|
|
227
295
|
}
|
|
228
296
|
/**
|
|
229
|
-
* Downloads `url` from a public host: publicFetch's hops and refusals (scheme, local or private host, port, redirects,
|
|
297
|
+
* Downloads `url` from a public host: publicFetch's hops and refusals (scheme, user name or password, local or private host, port, redirects,
|
|
230
298
|
* the signal), with any content type accepted and the body kept as bytes, up to `maxBytes` (default 5 MiB). A 2xx answer
|
|
231
299
|
* is read whole; another status comes back with `bytes` null. A body over the cap is refused (`refused: the file is over
|
|
232
300
|
* <cap>`): before a byte is read when its content-length says so, else as soon as it passes it. A body whose length its
|
package/dist/durable.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { defineDoc, defineExtension, defineTool } from "@earendil-works/pi-durable";
|
|
3
3
|
import { browserSection, browserToolsFor, listedFor } from "./core/contract.js";
|
|
4
|
-
import { BrowserFailureError, closeDriver, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
|
|
4
|
+
import { BrowserFailureError, closeDriver, DRIVER_ACK_BEFORE_KILL_MS, settledWithin, currentRecord, loadedNoPage, custodyTools, FIXED_SESSION_RELAUNCH, fenced, HANDED_BACK, newSessionRecord, notices, NAVIGATION_CAP, NOTHING_TO_HOLD, navigationRefusal, profileRefusal, relaunchRefusal, SESSION_REPLACED, sessionSpec, waitingForHuman, NO_HANDOFF } from "./core/custody.js";
|
|
5
5
|
import { forModel } from "./durable/result.js";
|
|
6
6
|
import { EffectObserver, effectDecider, observerFailure } from "./core/effects.js";
|
|
7
7
|
import { browserFailure, classifyBrowserError, isRefusal } from "./core/failures.js";
|
|
@@ -647,10 +647,10 @@ async function releasePlane(c, conversation, reason, context, still = () => true
|
|
|
647
647
|
const mine = () => c.held.tags().filter((tag) => c.owned.get(tag)?.cid === conversation.id);
|
|
648
648
|
// Kept before anything closes: the browser is still there, and a release that is cancelled (a call since) only made one capture more.
|
|
649
649
|
await Promise.all(leasesOf(c, conversation.id).map((tag) => captureSession(c, tag)));
|
|
650
|
-
//
|
|
651
|
-
// drivers first and never waits for the commit to do it; the commit runs alongside, so the release task starts as
|
|
652
|
-
// early as before. An idle release leaves it to the commit, which can find a call since or a person on the live view.
|
|
650
|
+
// Ack-then-kill, "close" only (a new reason gets the wait by decision, not by default): its drivers' close gets DRIVER_ACK_BEFORE_KILL_MS to answer before the commit that ends the session.
|
|
653
651
|
const closing = reason === "idle" ? Promise.resolve() : Promise.all(mine().map((tag) => c.held.detach(tag)));
|
|
652
|
+
if (reason === "close")
|
|
653
|
+
await settledWithin(closing, DRIVER_ACK_BEFORE_KILL_MS);
|
|
654
654
|
const tags = await conversation.commit(async (tx) => {
|
|
655
655
|
const state = await tx.doc(c.Sessions, conversation.id);
|
|
656
656
|
const record = still() ? currentRecord(state, PLANE) : null;
|
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
export declare const COPY = "stagehand-extension";
|
|
2
2
|
/** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
|
|
3
3
|
export declare const STAGEHAND_EXTENSION = "Stagehand Runtime";
|
|
4
|
-
/**
|
|
4
|
+
/** The Stagehand release the rewrite below was written against; a test holds it to the installed one, so a bump re-reads it. */
|
|
5
|
+
export declare const REWRITE_FOR = "4.4.0";
|
|
6
|
+
/** The first line of a rewritten worker, so the copy a browser runs can be told from Stagehand's own. */
|
|
7
|
+
export declare const REWRITE_MARK = "// pi-browser: a released client's callback batches end with it (see NOTICE in this directory).\n";
|
|
8
|
+
export declare const COPY_NOTICE = "This directory is a copy of the extension in @browserbasehq/stagehand 4.4.0 (dist/extension), under\nStagehand's MIT license (LICENSE, beside this file). @parcha/pi-browser changed two files in it:\n- manifest.json: a content security policy limiting the extension's connections to its own files and one browser's\n DevTools socket.\n- service-worker.js: when the extension releases a client that went away, it now aborts that client's running callback batches,\n rather than leaving each to run until its own timeout.\n";
|
|
9
|
+
/** The Stagehand version installed beside this package. */
|
|
10
|
+
export declare const installedStagehand: () => string;
|
|
11
|
+
/** Stagehand's extension worker with the rewrite above. Each place it changes must appear exactly once: a worker that has moved
|
|
12
|
+
* any of them is refused whole, naming the place and the installed Stagehand (`installed`), and never rewritten in part. A
|
|
13
|
+
* refusal fails the local Chrome launch with that error (copyExtension runs before Chrome starts, and the cdp provider removes
|
|
14
|
+
* what the launch made): a launch never goes ahead on a copy without the rewrite, nor on Stagehand's own directory. */
|
|
15
|
+
export declare function endBatchesOnRelease(worker: string, installed?: string): string;
|
|
16
|
+
/** `<into>/stagehand-extension`, a copy of Stagehand's extension directory, its worker rewritten (above), with Stagehand's LICENSE
|
|
17
|
+
* and a NOTICE naming what changed. The worker is rewritten before anything is copied, so a refused one leaves no copy. */
|
|
5
18
|
export declare function copyExtension(into: string, source?: string): Promise<string>;
|
|
6
19
|
/** The policy for the extension's pages and worker: its own files, and the browser's DevTools socket by its whole URL path. A
|
|
7
20
|
* manifest that already sets one is left alone only when it is exactly this one (an earlier load of this copy wrote it and failed
|
|
@@ -2,19 +2,85 @@
|
|
|
2
2
|
// connect to nothing but the extension's own files and the browser's DevTools socket. Run code executes in that worker with
|
|
3
3
|
// the extension's host permissions, so the browser itself refuses what the observer can only watch. A copy, because the
|
|
4
4
|
// manifest is Stagehand's bytes and a directory shared by every lease cannot name this lease's socket; created before the
|
|
5
|
-
// browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to.
|
|
5
|
+
// browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to. The
|
|
6
|
+
// copy's worker also carries one rewrite, so a process that dies inside a run can be reattached at once (endBatchesOnRelease).
|
|
7
|
+
import { readFileSync } from "node:fs";
|
|
6
8
|
import { cp, readFile, writeFile } from "node:fs/promises";
|
|
7
9
|
import path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
8
11
|
import { cdpCall } from "../core/cdp-call.js";
|
|
12
|
+
import { BrowserFailureError } from "../core/custody.js";
|
|
13
|
+
import { browserFailure } from "../core/failures.js";
|
|
9
14
|
import { extensionDirectory, extensionOrigin } from "./chrome-args.js";
|
|
10
15
|
export const COPY = "stagehand-extension";
|
|
11
16
|
/** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
|
|
12
17
|
export const STAGEHAND_EXTENSION = "Stagehand Runtime";
|
|
13
18
|
const LOAD_MS = 20_000;
|
|
14
|
-
/**
|
|
19
|
+
/** The Stagehand release the rewrite below was written against; a test holds it to the installed one, so a bump re-reads it. */
|
|
20
|
+
export const REWRITE_FOR = "4.4.0";
|
|
21
|
+
const WORKER = "service-worker.js";
|
|
22
|
+
/** The first line of a rewritten worker, so the copy a browser runs can be told from Stagehand's own. */
|
|
23
|
+
export const REWRITE_MARK = "// pi-browser: a released client's callback batches end with it (see NOTICE in this directory).\n";
|
|
24
|
+
export const COPY_NOTICE = `This directory is a copy of the extension in @browserbasehq/stagehand ${REWRITE_FOR} (dist/extension), under
|
|
25
|
+
Stagehand's MIT license (LICENSE, beside this file). @parcha/pi-browser changed two files in it:
|
|
26
|
+
- manifest.json: a content security policy limiting the extension's connections to its own files and one browser's
|
|
27
|
+
DevTools socket.
|
|
28
|
+
- ${WORKER}: when the extension releases a client that went away, it now aborts that client's running callback batches,
|
|
29
|
+
rather than leaving each to run until its own timeout.
|
|
30
|
+
`;
|
|
31
|
+
// Stagehand's extension keeps a dead client's callback batch running until the batch's own timeout, and holds the next client's
|
|
32
|
+
// stagehand.init behind it: releasing the client (ClientLifecycle.lost, then RPCClient.releaseClient) does not reach the batch's
|
|
33
|
+
// AbortController (createCallbackBatchController), while disposing the instance waits for every request in flight, the batch
|
|
34
|
+
// among them, and init queues behind that disposal. A process that dies inside a run is reattached only after its last batch's
|
|
35
|
+
// deadline (60 s by default), as long as Stagehand's own init deadline. The rewrite has releaseClient abort the running batches.
|
|
36
|
+
// That alone frees init (lines in Stagehand 4.4.0's dist/extension/service-worker.js): run() races the callback against its
|
|
37
|
+
// abort (:14696), so it rejects at once; only the outer callback_batch request holds the instance (:13368), the commands a batch
|
|
38
|
+
// sends taking none; its error reply throws, the client being gone (:13224), and its finally still releases the instance. One
|
|
39
|
+
// client is attached at a time and the router serves whichever it is, so only the dead client's batches are running when its
|
|
40
|
+
// release comes. Delete this rewrite once Stagehand ships the same change (upstream issue to be linked here).
|
|
41
|
+
const EDITS = [
|
|
42
|
+
{ name: "the batch registry",
|
|
43
|
+
find: "function createCallbackBatchController(router) {\n",
|
|
44
|
+
to: "function createCallbackBatchController(router) {\n\tconst active = new Set();\n" },
|
|
45
|
+
{ name: "a batch's start",
|
|
46
|
+
find: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n",
|
|
47
|
+
to: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n\t\tactive.add(controller);\n" },
|
|
48
|
+
{ name: "a batch's end",
|
|
49
|
+
find: "\t\t\tclearTimeout(timeoutId);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n",
|
|
50
|
+
to: "\t\t\tclearTimeout(timeoutId);\n\t\t\tactive.delete(controller);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n" },
|
|
51
|
+
{ name: "the batch controller's interface",
|
|
52
|
+
find: "\treturn { run };\n}\nfunction createCallbackContextFacade(",
|
|
53
|
+
to: "\treturn {\n\t\trun,\n\t\tabortAll(reason) {\n\t\t\tfor (const controller of active) controller.abort(reason);\n\t\t}\n\t};\n}\nfunction createCallbackContextFacade(" },
|
|
54
|
+
{ name: "the client's release",
|
|
55
|
+
find: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n",
|
|
56
|
+
to: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n\t\tthis.router.callbackBatchController.abortAll(/* @__PURE__ */ new Error(\"Stagehand client disconnected\"));\n" },
|
|
57
|
+
];
|
|
58
|
+
/** Stagehand's package root (the module it exports is dist/index.mjs). */
|
|
59
|
+
const stagehandRoot = () => path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "..");
|
|
60
|
+
/** The Stagehand version installed beside this package. */
|
|
61
|
+
export const installedStagehand = () => JSON.parse(readFileSync(path.join(stagehandRoot(), "package.json"), "utf8")).version;
|
|
62
|
+
/** Stagehand's extension worker with the rewrite above. Each place it changes must appear exactly once: a worker that has moved
|
|
63
|
+
* any of them is refused whole, naming the place and the installed Stagehand (`installed`), and never rewritten in part. A
|
|
64
|
+
* refusal fails the local Chrome launch with that error (copyExtension runs before Chrome starts, and the cdp provider removes
|
|
65
|
+
* what the launch made): a launch never goes ahead on a copy without the rewrite, nor on Stagehand's own directory. */
|
|
66
|
+
export function endBatchesOnRelease(worker, installed = installedStagehand()) {
|
|
67
|
+
for (const edit of EDITS) {
|
|
68
|
+
const at = worker.indexOf(edit.find);
|
|
69
|
+
if (at >= 0 && worker.indexOf(edit.find, at + 1) < 0)
|
|
70
|
+
continue;
|
|
71
|
+
throw new BrowserFailureError(browserFailure("browser_unavailable", `Stagehand's extension worker (${WORKER}, Stagehand ${installed}) has ${at < 0 ? "no" : "more than one"} match for ${edit.name}, which pi-browser rewrites so a gone client's callback batches end with it; the rewrite was written against Stagehand ${REWRITE_FOR}. No browser was started.`));
|
|
72
|
+
}
|
|
73
|
+
return REWRITE_MARK + EDITS.reduce((text, edit) => text.replace(edit.find, () => edit.to), worker);
|
|
74
|
+
}
|
|
75
|
+
/** `<into>/stagehand-extension`, a copy of Stagehand's extension directory, its worker rewritten (above), with Stagehand's LICENSE
|
|
76
|
+
* and a NOTICE naming what changed. The worker is rewritten before anything is copied, so a refused one leaves no copy. */
|
|
15
77
|
export async function copyExtension(into, source = extensionDirectory()) {
|
|
78
|
+
const worker = endBatchesOnRelease(await readFile(path.join(source, WORKER), "utf8"));
|
|
16
79
|
const copy = path.join(into, COPY);
|
|
17
80
|
await cp(source, copy, { recursive: true, dereference: true });
|
|
81
|
+
await writeFile(path.join(copy, WORKER), worker);
|
|
82
|
+
await cp(path.join(stagehandRoot(), "LICENSE"), path.join(copy, "LICENSE"));
|
|
83
|
+
await writeFile(path.join(copy, "NOTICE"), COPY_NOTICE);
|
|
18
84
|
return copy;
|
|
19
85
|
}
|
|
20
86
|
/** The policy for the extension's pages and worker: its own files, and the browser's DevTools socket by its whole URL path. A
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/pi-browser",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.73",
|
|
4
4
|
"description": "Your agent gets its own browser, and you can take over and hand it back.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-durable",
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
"verify:tarball": "node scripts/verify-tarball.mjs"
|
|
71
71
|
},
|
|
72
72
|
"dependencies": {
|
|
73
|
-
"@browserbasehq/stagehand": "
|
|
73
|
+
"@browserbasehq/stagehand": "4.4.0",
|
|
74
74
|
"node-html-markdown": "^2.0.0",
|
|
75
75
|
"node-html-parser": "^6.1.13",
|
|
76
76
|
"typebox": "1.3.27",
|