@parcha/pi-browser 0.1.0-beta.68 → 0.1.0-beta.70

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 CHANGED
@@ -2,6 +2,16 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.1.0-beta.70 (2026-11-29)
6
+
7
+ - 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 -->
8
+ - 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 -->
9
+ - `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 -->
10
+
11
+ ## 0.1.0-beta.69 (2026-11-28)
12
+
13
+ - `@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 -->
14
+
5
15
  ## 0.1.0-beta.66 (2026-11-27)
6
16
 
7
17
  - The browser's `screenshot` tool takes an optional `save_as`: a path relative to the workspace, its folders separated by `/`, ending `.png`, `.jpg` or `.jpeg` (`shots/home.png`). The capture is filed as evidence as before, and the same bytes are also written to that path. Missing folders are created and an existing file is replaced. The answer gets a `saved: <path>` line, and its details get `save_as: { path, saved: true }`. A `.png` name captures a PNG. An absolute path, a `..` segment, a backslash, a name that is not an image, or a name whose format contradicts `type` is refused before the browser is called, so nothing is captured or filed. If the size budget retakes a PNG as a JPEG, the capture still comes back and is filed, but nothing is written under the `.png` name: the answer says `not saved: ...` and its details give `save_as: { path, saved: false, reason: "format_changed", message }`. Without `save_as`, the tool behaves as before. <!-- changes/browser-screenshot-save-as.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 two pieces of Stagehand (https://github.com/browserbase/stagehand), both under its MIT license,
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
 
@@ -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 = {
@@ -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
- let timer;
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;
@@ -43,7 +43,8 @@ export declare function publicCheck(url: string, options?: {
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`; another status comes back without its
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
49
  * than https, with `httpsOnly`); a host that is local by name or resolves to any private address; a port other than 80
49
50
  * 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
@@ -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. */
@@ -204,7 +265,8 @@ function statedLength(headers) {
204
265
  }
205
266
  /**
206
267
  * 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`; another status comes back without its
268
+ * address checked. A 2xx answer of a text type is read whole, up to `maxBytes`, and
269
+ * decoded by the charset it declares (pageText); another status comes back without its
208
270
  * body. Refused (`BrowserFailureError` `refused`), on the first hop or a redirect: a scheme other than http(s) (other
209
271
  * than https, with `httpsOnly`); a host that is local by name or resolves to any private address; a port other than 80
210
272
  * 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
@@ -222,7 +284,7 @@ export async function publicFetch(url, options = {}) {
222
284
  if (!TEXT_TYPE.test(contentType))
223
285
  throw refusedError(`refused: ${contentType || "an unknown content type"} is not text`);
224
286
  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.toString("utf8") };
287
+ return { url: target.href, status: res.status, contentType, body: pageText(body, contentType) };
226
288
  });
227
289
  }
228
290
  /**
@@ -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 comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. Stagehand allows one
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. */
@@ -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 comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. Stagehand allows one
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 ?? 60_000 });
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.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
- // Closing a driver needs nothing from the store, so a release other than idle's starts closing the conversation's
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
- /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory. */
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
- /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory. */
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.68",
3
+ "version": "0.1.0-beta.70",
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": "~4.4.0",
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",