@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.340

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.
Files changed (78) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/NOTICE +6 -1
  3. package/README.md +70 -60
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +12 -30
  6. package/dist/core/custody.d.ts +6 -0
  7. package/dist/core/custody.js +15 -3
  8. package/dist/core/downloads.d.ts +37 -3
  9. package/dist/core/downloads.js +81 -57
  10. package/dist/core/driving-guard.d.ts +1 -1
  11. package/dist/core/driving-guard.js +1 -1
  12. package/dist/core/evidence.d.ts +1 -1
  13. package/dist/core/files.d.ts +20 -2
  14. package/dist/core/files.js +161 -10
  15. package/dist/core/host.d.ts +18 -75
  16. package/dist/core/images.d.ts +32 -4
  17. package/dist/core/images.js +81 -16
  18. package/dist/core/lease.d.ts +2 -1
  19. package/dist/core/page-scan.d.ts +81 -2
  20. package/dist/core/page-scan.js +487 -13
  21. package/dist/core/public-fetch.d.ts +70 -9
  22. package/dist/core/public-fetch.js +348 -51
  23. package/dist/core/read-page-worker.js +5 -4
  24. package/dist/core/read-page.d.ts +23 -8
  25. package/dist/core/read-page.js +64 -20
  26. package/dist/core/redact.d.ts +0 -2
  27. package/dist/core/redact.js +0 -32
  28. package/dist/core/session-control.d.ts +0 -2
  29. package/dist/core/session-control.js +0 -5
  30. package/dist/core/tools.d.ts +23 -1
  31. package/dist/core/tools.js +46 -4
  32. package/dist/core/usage.d.ts +4 -3
  33. package/dist/core/usage.js +5 -4
  34. package/dist/core/vault.d.ts +0 -10
  35. package/dist/core/vault.js +0 -13
  36. package/dist/core/web.d.ts +2 -111
  37. package/dist/core/web.js +0 -443
  38. package/dist/driver/cdp.js +3 -3
  39. package/dist/driver/page-driver.js +7 -3
  40. package/dist/driver/stagehand.d.ts +3 -1
  41. package/dist/driver/stagehand.js +4 -2
  42. package/dist/durable/store.d.ts +14 -3
  43. package/dist/durable/store.js +204 -51
  44. package/dist/durable.d.ts +32 -16
  45. package/dist/durable.js +68 -95
  46. package/dist/index.d.ts +3 -3
  47. package/dist/index.js +5 -3
  48. package/dist/live-view/index.d.ts +3 -1
  49. package/dist/live-view/index.js +4 -0
  50. package/dist/live-view/protocol.d.ts +1 -1
  51. package/dist/live-view/server.d.ts +30 -0
  52. package/dist/live-view/server.js +152 -25
  53. package/dist/providers/cdp.js +2 -2
  54. package/dist/providers/profiles.d.ts +1 -15
  55. package/dist/providers/profiles.js +1 -64
  56. package/dist/providers/shared.d.ts +1 -47
  57. package/dist/providers/shared.js +1 -82
  58. package/dist/providers/worker-extension.d.ts +14 -1
  59. package/dist/providers/worker-extension.js +69 -3
  60. package/dist/testing/backend.d.ts +6 -24
  61. package/dist/testing/backend.js +7 -30
  62. package/dist/vault-session.d.ts +4 -7
  63. package/dist/vault-session.js +26 -81
  64. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  65. package/dist/vendor/browser-use-pi/page.js +6 -19
  66. package/package.json +9 -22
  67. package/dist/core/sites.d.ts +0 -33
  68. package/dist/core/sites.js +0 -104
  69. package/dist/durable/web.d.ts +0 -47
  70. package/dist/durable/web.js +0 -41
  71. package/dist/providers/browserbase-net.d.ts +0 -12
  72. package/dist/providers/browserbase-net.js +0 -95
  73. package/dist/providers/browserbase.d.ts +0 -169
  74. package/dist/providers/browserbase.js +0 -319
  75. package/dist/providers/kernel.d.ts +0 -58
  76. package/dist/providers/kernel.js +0 -291
  77. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  78. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -5,6 +5,8 @@ import { openStream } from "./stream.js";
5
5
  import { newToken, newViewerId, tokenMatches } from "./token.js";
6
6
  import { viewerAssets } from "./viewer.js";
7
7
  import { acceptWebSocket } from "./ws.js";
8
+ /** Where the live view's own server listens with no `listen`: this machine alone. */
9
+ const LOOPBACK_HOST = "127.0.0.1"; // key-gate: loopback-rule the default, this machine alone
8
10
  const ID = /^[A-Za-z0-9_-]{22}$/;
9
11
  /** A viewer that cannot take frames as fast as they come drops them: past this many unsent bytes a frame is acknowledged unsent. */
10
12
  const SLOW_VIEWER_BYTES = 512 * 1024;
@@ -17,6 +19,32 @@ const MAX_QUEUED_INPUT = 32;
17
19
  /** A viewer whose messages the protocol does not know: one is dropped with a notice, and past this many within the window the connection is closed. */
18
20
  const MAX_BAD_MESSAGES = 20;
19
21
  const BAD_WINDOW_MS = 10_000;
22
+ const handedSockets = new Map();
23
+ const handedSocket = (fd) => {
24
+ const known = handedSockets.get(fd);
25
+ if (known)
26
+ return known;
27
+ const made = new Promise((resolve, reject) => {
28
+ let at;
29
+ const s = createServer((req, res) => { if (!at?.route?.handle(req, res)) {
30
+ res.writeHead(404, { "Content-Length": 0 });
31
+ res.end();
32
+ } });
33
+ s.on("upgrade", (req, socket, head) => { if (!at?.route?.upgrade(req, socket, head))
34
+ socket.destroy(); });
35
+ s.once("error", reject);
36
+ s.listen({ fd }, () => {
37
+ s.unref();
38
+ at = { server: s, port: s.address().port, route: null };
39
+ resolve(at);
40
+ });
41
+ });
42
+ handedSockets.set(fd, made);
43
+ // A socket that could not be listened on is asked again by the next view, not refused from memory.
44
+ made.catch(() => { if (handedSockets.get(fd) === made)
45
+ handedSockets.delete(fd); });
46
+ return made;
47
+ };
20
48
  export function createLiveView(options) {
21
49
  const takeOver = options.readOnly ? undefined : options.takeOver;
22
50
  const helloTimeoutMs = options.helloTimeoutMs ?? 5_000;
@@ -27,6 +55,8 @@ export function createLiveView(options) {
27
55
  let origin = mounted?.origin ?? null;
28
56
  const prefix = mounted ? mounted.pathname.replace(/\/+$/, "") : "";
29
57
  let server = null;
58
+ /** The handed socket this view took (`listen.fd`), while it holds it. */
59
+ let handed = null;
30
60
  let starting = null;
31
61
  let closed = false;
32
62
  /** The opens waiting for the server, by tag: a `release` or a `close` that comes meanwhile marks them cancelled, and each open takes its own mark off when it ends, so
@@ -65,6 +95,11 @@ export function createLiveView(options) {
65
95
  const upgradeRoute = /^\/v\/([^/]+)\/ws$/.exec(rel);
66
96
  if (!page && !upgradeRoute && rel !== "/viewer.js" && rel !== "/viewer.css")
67
97
  return false;
98
+ if (options.admit && !options.admit(req)) {
99
+ res.writeHead(403, { ...securityHeaders(), "Content-Length": 0 });
100
+ res.end();
101
+ return true;
102
+ }
68
103
  const reply = (status, type, body) => { res.writeHead(status, { ...securityHeaders(), "Content-Type": type, "Content-Length": Buffer.byteLength(body) }); res.end(req.method === "HEAD" ? undefined : body); return true; };
69
104
  if (req.method !== "GET" && req.method !== "HEAD")
70
105
  return reply(405, "text/plain", "method not allowed");
@@ -90,6 +125,8 @@ export function createLiveView(options) {
90
125
  // A browser always sends its page's origin on a WebSocket; another tab's script cannot forge it. Anything but the viewer's own is refused.
91
126
  if (origin === null || req.headers.origin !== origin)
92
127
  return deny("403 Forbidden");
128
+ if (options.admit && !options.admit(req))
129
+ return deny("403 Forbidden");
93
130
  const entry = ID.test(match[1]) ? byId.get(match[1]) : undefined;
94
131
  if (!entry || entry.released)
95
132
  return deny("404 Not Found");
@@ -127,26 +164,10 @@ export function createLiveView(options) {
127
164
  if (entry.viewer)
128
165
  return refuse(conn, "viewer_in_use");
129
166
  let viewer;
167
+ const running = entry.stream !== null;
130
168
  try {
131
169
  const gate = (options.gates ?? drivingGates)(entry.tag);
132
- const stream = (options.stream ?? openStream)(entry.cdpUrl, {
133
- frame(jpeg, page, ack) {
134
- if (conn.closed || conn.buffered > SLOW_VIEWER_BYTES) {
135
- ack();
136
- return;
137
- }
138
- if (!conn.send(encodeFrame(jpeg, page.w, page.h), ack))
139
- ack();
140
- },
141
- page: (page) => send(conn, { type: "page", url: page.url, title: page.title }),
142
- noPage: () => send(conn, { type: "no_page" }),
143
- dialog: (dialog) => send(conn, dialog ? { type: "dialog", ...dialog } : { type: "dialog_closed" }),
144
- closed: () => { if (entry.viewer?.conn === conn) {
145
- send(conn, { type: "ended", reason: "browser_closed" });
146
- conn.close(CLOSE_CODES.browser_closed, "browser_closed");
147
- } },
148
- });
149
- viewer = { conn, stream, gate, unsubscribe: gate.onChange((drive) => send(conn, { type: "status", drive })), chain: Promise.resolve(), bad: [], queued: 0, tail: null };
170
+ viewer = { conn, stream: streamOf(entry), gate, unsubscribe: gate.onChange((drive) => send(conn, { type: "status", drive })), chain: Promise.resolve(), bad: [], queued: 0, tail: null };
150
171
  }
151
172
  catch {
152
173
  conn.close(1011, "unavailable");
@@ -160,6 +181,75 @@ export function createLiveView(options) {
160
181
  else if (!options.readOnly)
161
182
  viewer.gate.setViewing(true);
162
183
  send(conn, { type: "ready", drive: viewer.gate.state(), ...(options.readOnly ? { readOnly: true } : takeOver ? { takeOver: true, held: isHolding(viewer.gate) } : {}) });
184
+ // Joining a watcher's stream: what it last said, its newest frame too (already acked).
185
+ if (!running)
186
+ return;
187
+ const { page, dialog, frame } = entry.shown;
188
+ for (const said of [page, dialog])
189
+ if (said)
190
+ send(conn, said);
191
+ if (frame)
192
+ conn.send(encodeFrame(frame.jpeg, frame.page.w, frame.page.h));
193
+ };
194
+ /** The session's one stream, opened at its first viewer or watcher: each frame to every watcher, then to the viewer,
195
+ * whose send acks it (or at once, with no viewer or a slow one); the rest to the viewer alone. Kept in `shown` while it is
196
+ * open, for a viewer that joins later. */
197
+ const streamOf = (entry) => (entry.stream ??= (options.stream ?? openStream)(entry.cdpUrl, {
198
+ frame(jpeg, page, ack) {
199
+ for (const watcher of entry.watchers)
200
+ try {
201
+ watcher.frame(jpeg, page);
202
+ }
203
+ catch { /* a watcher's failure never holds the frame's ack */ }
204
+ entry.shown.frame = { jpeg, page };
205
+ const conn = entry.viewer?.conn;
206
+ if (!conn || conn.closed || conn.buffered > SLOW_VIEWER_BYTES) {
207
+ ack();
208
+ return;
209
+ }
210
+ if (!conn.send(encodeFrame(jpeg, page.w, page.h), ack))
211
+ ack();
212
+ },
213
+ page: (page) => tell(entry, "page", { type: "page", url: page.url, title: page.title }),
214
+ noPage: () => {
215
+ // The closed tab's picture goes with it: a viewer that joins now is told no page, and shown none.
216
+ delete entry.shown.frame;
217
+ tell(entry, "page", { type: "no_page" });
218
+ },
219
+ dialog: (dialog) => tell(entry, "dialog", dialog ? { type: "dialog", ...dialog } : { type: "dialog_closed" }),
220
+ closed: () => {
221
+ const conn = entry.viewer?.conn;
222
+ entry.stream = null;
223
+ entry.shown = {};
224
+ if (conn) {
225
+ send(conn, { type: "ended", reason: "browser_closed" });
226
+ conn.close(CLOSE_CODES.browser_closed, "browser_closed");
227
+ }
228
+ const watchers = [...entry.watchers];
229
+ entry.watchers.clear();
230
+ for (const watcher of watchers)
231
+ try {
232
+ watcher.ended();
233
+ }
234
+ catch { /* each watcher is told */ }
235
+ },
236
+ }));
237
+ const tell = (entry, key, message) => {
238
+ entry.shown[key] = message;
239
+ if (entry.viewer)
240
+ send(entry.viewer.conn, message);
241
+ };
242
+ /** The stream ends once neither a viewer nor a watcher has it. */
243
+ const unused = (entry) => {
244
+ if (entry.viewer || entry.watchers.size > 0 || !entry.stream)
245
+ return;
246
+ const stream = entry.stream;
247
+ entry.stream = null;
248
+ entry.shown = {};
249
+ try {
250
+ stream.close();
251
+ }
252
+ catch { /* the stream is gone either way */ }
163
253
  };
164
254
  const onViewerMessage = (entry, viewer, data, binary) => {
165
255
  const message = binary || typeof data !== "string" ? null : parseClientMessage(data);
@@ -361,14 +451,24 @@ export function createLiveView(options) {
361
451
  viewer.gate.setPresent?.(false);
362
452
  else if (!options.readOnly)
363
453
  viewer.gate.setViewing(false);
364
- try {
365
- viewer.stream.close();
366
- }
367
- catch { /* the stream is gone either way */ }
454
+ unused(entry);
368
455
  };
456
+ const routes = { handle: (req, res) => handle(req, res), upgrade: (req, socket, head) => upgrade(req, socket, head) };
369
457
  const ensureServer = () => {
370
458
  if (mounted || origin)
371
459
  return Promise.resolve();
460
+ const given = options.listen;
461
+ if (given && "fd" in given) {
462
+ starting ??= handedSocket(given.fd).then((socket) => {
463
+ // A close that came while the socket was being listened on leaves it to the next view.
464
+ if (closed)
465
+ return;
466
+ socket.route = routes;
467
+ handed = socket;
468
+ origin = `http://${given.host}:${socket.port}`;
469
+ });
470
+ return starting;
471
+ }
372
472
  starting ??= new Promise((resolve, reject) => {
373
473
  const s = createServer((req, res) => { if (!handle(req, res)) {
374
474
  res.writeHead(404, { "Content-Length": 0 });
@@ -377,8 +477,10 @@ export function createLiveView(options) {
377
477
  s.on("upgrade", (req, socket, head) => { if (!upgrade(req, socket, head))
378
478
  socket.destroy(); });
379
479
  s.once("error", reject);
380
- // Loopback only, never 0.0.0.0: the host that wants more mounts the handler on its own server.
381
- s.listen(0, "127.0.0.1", () => { s.unref(); server = s; origin = `http://127.0.0.1:${s.address().port}`; resolve(); });
480
+ // Loopback unless the host names another address (`listen`, with its `admit`): the host that wants more mounts the
481
+ // handler on its own server.
482
+ const at = given ?? { bind: LOOPBACK_HOST, host: LOOPBACK_HOST };
483
+ s.listen(0, at.bind, () => { s.unref(); server = s; origin = `http://${at.host}:${s.address().port}`; resolve(); });
382
484
  });
383
485
  return starting;
384
486
  };
@@ -398,6 +500,9 @@ export function createLiveView(options) {
398
500
  entry.pending.clear();
399
501
  const viewer = entry.viewer;
400
502
  endViewer(entry);
503
+ // Its watchers stop with no call: the host that released it ends what it watches for.
504
+ entry.watchers.clear();
505
+ unused(entry);
401
506
  // The gate is the session's, so it ends with it even when no viewer ever took it.
402
507
  (options.gates ?? drivingGates)(tag).end();
403
508
  void viewer;
@@ -429,7 +534,7 @@ export function createLiveView(options) {
429
534
  const raced = byTag.get(tag);
430
535
  if (raced?.view)
431
536
  return raced.view;
432
- const entry = { tag, id: newViewerId(), token: newToken(), cdpUrl, view: null, released: false, viewer: null, pending: new Set() };
537
+ const entry = { tag, id: newViewerId(), token: newToken(), cdpUrl, view: null, released: false, viewer: null, pending: new Set(), stream: null, watchers: new Set(), shown: {} };
433
538
  const url = `${origin}${prefix}/v/${entry.id}#t=${entry.token}`;
434
539
  entry.view = { fullscreen: url, framed: url, pages: [] };
435
540
  byTag.set(tag, entry);
@@ -439,6 +544,21 @@ export function createLiveView(options) {
439
544
  known: (tag) => { const entry = byTag.get(tag); return entry && !entry.released ? entry.view : null; },
440
545
  driving: (tag) => { const entry = byTag.get(tag); if (!entry)
441
546
  return false; const gate = (options.gates ?? drivingGates)(tag); return isHeld(gate) || (!!entry.viewer && gate.state() === "person"); },
547
+ watch(tag, watcher) {
548
+ const entry = byTag.get(tag);
549
+ if (!entry || entry.released)
550
+ return null;
551
+ entry.watchers.add(watcher);
552
+ try {
553
+ streamOf(entry);
554
+ }
555
+ catch {
556
+ entry.watchers.delete(watcher);
557
+ return null;
558
+ }
559
+ return () => { if (entry.watchers.delete(watcher))
560
+ unused(entry); };
561
+ },
442
562
  tracked: () => ({ sessions: byTag.size, opening: [...opening.values()].reduce((n, marks) => n + marks.size, 0) }),
443
563
  release,
444
564
  async close() {
@@ -451,6 +571,13 @@ export function createLiveView(options) {
451
571
  await starting.catch(() => undefined);
452
572
  for (const tag of [...byTag.keys()])
453
573
  await release(tag);
574
+ // A handed socket stays listening for the process's next view; this view's requests on it go, if it still holds it.
575
+ const socket = handed;
576
+ handed = null;
577
+ if (socket && socket.route === routes) {
578
+ socket.route = null;
579
+ socket.server.closeAllConnections();
580
+ }
454
581
  const s = server;
455
582
  server = null;
456
583
  if (s)
@@ -7,12 +7,12 @@ import path from "node:path";
7
7
  import { BrowserFailureError, PROFILE_NAME, refusedError } from "../core/custody.js";
8
8
  import { DownloadNotSettled } from "../core/downloads.js";
9
9
  import { browserFailure } from "../core/failures.js";
10
- import { cdpCall } from "./cdp-call.js";
10
+ import { cdpCall } from "../core/cdp-call.js";
11
11
  import { chromeTail, openChromeStderr, watchChromeStderr } from "./chrome-stderr.js";
12
12
  import { claimWriter, freeWriter, noteWriter } from "./profiles.js";
13
13
  import { chromeArgs } from "./chrome-args.js";
14
14
  import { COPY, copyExtension, copyId, isLoaded, loadConfined, soleStagehand } from "./worker-extension.js";
15
- const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 86_400, survivesDisconnect: true, releaseIsAsync: false, profiles: false, extension: "loaded-locally", settings: { proxies: false, verified: false, geolocation: false, region: false, context: false } };
15
+ const CAPS = { profiles: false, settings: { proxies: false, verified: false, geolocation: false, region: false, context: false } };
16
16
  const downloadsDir = (profileRoot, tag) => path.join(profileDir(profileRoot, tag) + ".downloads");
17
17
  const READY_MS = 20_000;
18
18
  /** The browser is gone and directories it used are not: a profile left behind holds the session's cookies, so a release that cannot remove
@@ -1,4 +1,4 @@
1
- /** Both vendors keep the last writer's state and neither locks, so within this process one session at a time may save to a
1
+ /** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
2
2
  * profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
3
3
  * while the old session is still being released) waits for the release; anyone else is refused. */
4
4
  export declare function claimWriter(key: string, name: string, tag: string, owner: string, signal?: AbortSignal): Promise<void>;
@@ -7,17 +7,3 @@ export declare function claimWriter(key: string, name: string, tag: string, owne
7
7
  export declare function noteWriter(tag: string, running: (signal: AbortSignal) => Promise<boolean>, settle?: () => Promise<void>): void;
8
8
  export declare function freeWriter(tag: string): void;
9
9
  export declare function isWriter(tag: string): boolean;
10
- /** Context ids are not secrets, and Browserbase has no way to look a context up by name, so the name to id map is the host's.
11
- * `resolve` returns the name's context, calling `make` only when there is none, and no two callers may both make one. */
12
- export type ProfileStore = {
13
- resolve(key: string, make: (signal: AbortSignal) => Promise<string>): Promise<string>;
14
- /** True when the store writes the ids it holds to a clear file (the default one does). A session vault refuses a provider whose store does. */
15
- readonly clear?: boolean;
16
- };
17
- /** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
18
- export declare function memoryProfileStore(): ProfileStore;
19
- /** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
20
- * not this format, or cannot be read, is never overwritten. */
21
- export declare function fileProfileStore(file?: string, options?: {
22
- makeLimitMs?: number;
23
- }): ProfileStore;
@@ -1,9 +1,4 @@
1
- import { randomBytes } from "node:crypto";
2
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
1
  import { refusedError } from "../core/custody.js";
6
- import { withLock } from "../core/downloads.js";
7
2
  import { profileHoldings } from "./shared.js";
8
3
  const writers = profileHoldings.writers;
9
4
  const WAIT_MS = 20_000;
@@ -31,7 +26,7 @@ async function waitFor(work, signal, ms) {
31
26
  signal?.removeEventListener("abort", abort);
32
27
  }
33
28
  }
34
- /** Both vendors keep the last writer's state and neither locks, so within this process one session at a time may save to a
29
+ /** A profile keeps the last writer's state and nothing locks it, so within this process one session at a time may save to a
35
30
  * profile. A holder that is no longer running is replaced; the same owner's successor (a relaunch asks for its replacement
36
31
  * while the old session is still being released) waits for the release; anyone else is refused. */
37
32
  export async function claimWriter(key, name, tag, owner, signal) {
@@ -74,61 +69,3 @@ export function isWriter(tag) {
74
69
  return true;
75
70
  return false;
76
71
  }
77
- /** Context ids kept in this process only: for a host that moves them into its own vault, so none lands on disk. */
78
- export function memoryProfileStore() {
79
- const ids = new Map();
80
- return { clear: false, resolve: (key, make) => { let known = ids.get(key); if (!known) {
81
- known = make(AbortSignal.timeout(20_000));
82
- ids.set(key, known);
83
- known.catch(() => ids.delete(key));
84
- } return known; } };
85
- }
86
- const SCHEMA = "pi-browser.profiles.v1";
87
- const defaultProfilesFile = () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "pi-browser", "profiles.json");
88
- const notOurs = (file) => new Error(`the profiles file ${path.basename(file)} is not a pi-browser profiles file, so it was left as it is`);
89
- async function readProfiles(file) {
90
- let text;
91
- try {
92
- text = await readFile(file, "utf8");
93
- }
94
- catch (error) {
95
- if (error.code === "ENOENT")
96
- return { schema: SCHEMA, contexts: {} };
97
- throw error;
98
- }
99
- try {
100
- const parsed = JSON.parse(text);
101
- const contexts = parsed?.contexts;
102
- if (parsed?.schema === SCHEMA && contexts && typeof contexts === "object" && !Array.isArray(contexts) && Object.values(contexts).every((id) => typeof id === "string" && id !== ""))
103
- return parsed;
104
- }
105
- catch { /* not JSON */ }
106
- throw notOurs(file);
107
- }
108
- /** A JSON file, read, extended and written under one lock, so two processes' first uses of a name make one context; a file that is
109
- * not this format, or cannot be read, is never overwritten. */
110
- export function fileProfileStore(file = defaultProfilesFile(), options = {}) {
111
- // The lock is taken over once it is 30 s old (core/downloads.ts's rule), so `make` must end well before: a slower one is cut here, never left
112
- // to run past the lock that protects it.
113
- const makeLimitMs = options.makeLimitMs ?? 20_000;
114
- return {
115
- clear: true,
116
- async resolve(key, make) {
117
- await mkdir(path.dirname(file), { recursive: true });
118
- return withLock(`${file}.lock`, async () => {
119
- const current = await readProfiles(file);
120
- const known = current.contexts[key];
121
- if (known)
122
- return known;
123
- const limit = AbortSignal.timeout(makeLimitMs);
124
- // Listening before `make` does, so the cut's own words are what the caller hears.
125
- const cut = new Promise((_, reject) => limit.addEventListener("abort", () => reject(new Error(`making the profile's context took longer than ${makeLimitMs} ms, so it was cut before the profiles file's lock could be taken over`)), { once: true }));
126
- const id = await Promise.race([make(limit), cut]);
127
- const next = `${file}.${randomBytes(4).toString("hex")}.tmp`;
128
- await writeFile(next, `${JSON.stringify({ schema: SCHEMA, contexts: { ...current.contexts, [key]: id } }, null, 2)}\n`);
129
- await rename(next, file);
130
- return id;
131
- }, "the profiles file");
132
- },
133
- };
134
- }
@@ -1,50 +1,5 @@
1
- import type { ResourceStatus } from "../core/lease.js";
2
- import type { CdpSession } from "./cdp-call.js";
3
1
  export declare const nonEmpty: (v: unknown) => string;
4
- /** Values are `[A-Za-z0-9._:-]`, at most 60 characters; the tag is exact, since a query matches it whole. */
5
- export declare const tagValue: (v: string) => string;
6
- export declare function assertTag(tag: string): void;
7
- export declare function extensionArchive(): string;
8
- export declare const accountKey: (origin: string, apiKey: string) => string;
9
- export declare const defaultSleep: (ms: number) => Promise<void>;
10
- export declare const DEFAULT_CONFIRM: {
11
- polls: number;
12
- intervalMs: number;
13
- };
14
- /** The work itself goes on when `signal` fires: another caller may be waiting for it. */
15
- export declare function untilAborted<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
16
- /** One upload per process and account; a failed upload is forgotten so the next create tries again. */
17
- export declare function uploadOnce<T>(uploads: Map<string, Promise<T>>, account: string, upload: () => Promise<T>): Promise<T>;
18
- /** The request is asked twice at most; released means the provider says the session is no longer running, not that the
19
- * request was sent. `request` answers "gone" when the provider no longer knows the session. */
20
- export declare function releaseAndConfirm(o: {
21
- request: () => Promise<"gone" | void>;
22
- status: () => Promise<ResourceStatus>;
23
- forget: () => void | Promise<void>;
24
- confirm: {
25
- polls: number;
26
- intervalMs: number;
27
- };
28
- sleep: (ms: number) => Promise<void>;
29
- stillRunning: string;
30
- }): Promise<void>;
31
- export declare const browserbaseHoldings: {
32
- connectUrls: Map<string, string>;
33
- settings: Map<string, Pick<CdpSession, "close" | "open">>;
34
- opening: Map<string, Promise<void>>;
35
- uploads: Map<string, Promise<string>>;
36
- boundDials: Map<string, string>;
37
- };
38
- export declare const kernelHoldings: {
39
- cdpUrls: Map<string, string>;
40
- liveUrls: Map<string, string>;
41
- uploads: Map<string, Promise<{
42
- id: string;
43
- } | {
44
- name: string;
45
- }>>;
46
- };
47
- /** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
2
+ /** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
48
3
  export declare const profileHoldings: {
49
4
  writers: Map<string, {
50
5
  tag: string;
@@ -53,4 +8,3 @@ export declare const profileHoldings: {
53
8
  settle?: () => Promise<void>;
54
9
  }>;
55
10
  };
56
- export declare function resetProviderHoldings(): void;
@@ -1,86 +1,5 @@
1
- import { createHash } from "node:crypto";
2
- import path from "node:path";
3
- import { fileURLToPath } from "node:url";
4
1
  export const nonEmpty = (v) => String(v ?? "").trim();
5
- /** Values are `[A-Za-z0-9._:-]`, at most 60 characters; the tag is exact, since a query matches it whole. */
6
- export const tagValue = (v) => String(v || "").replace(/[^A-Za-z0-9._:-]+/g, "_").slice(0, 60) || "unknown";
7
- export function assertTag(tag) {
8
- if (!/^[A-Za-z0-9_.-]+$/.test(tag))
9
- throw new Error("a session tag is [A-Za-z0-9_.-]");
10
- }
11
- export function extensionArchive() {
12
- return nonEmpty(process.env.STAGEHAND_EXTENSION_ARCHIVE_PATH) || path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "assets", "stagehand-extension.zip");
13
- }
14
- export const accountKey = (origin, apiKey) => `${origin}|${createHash("sha256").update(apiKey).digest("hex").slice(0, 16)}`;
15
- export const defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
16
- export const DEFAULT_CONFIRM = { polls: 6, intervalMs: 500 };
17
- /** The work itself goes on when `signal` fires: another caller may be waiting for it. */
18
- export function untilAborted(work, signal) {
19
- if (!signal)
20
- return work;
21
- return new Promise((resolve, reject) => {
22
- const abort = () => reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"));
23
- // The outcome is taken first, so a failure after the caller left is handled, never unhandled.
24
- work.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
25
- if (signal.aborted)
26
- return abort();
27
- signal.addEventListener("abort", abort, { once: true });
28
- });
29
- }
30
- /** One upload per process and account; a failed upload is forgotten so the next create tries again. */
31
- export function uploadOnce(uploads, account, upload) {
32
- let up = uploads.get(account);
33
- if (!up) {
34
- up = upload();
35
- uploads.set(account, up);
36
- up.catch(() => uploads.delete(account));
37
- }
38
- return up;
39
- }
40
- /** The request is asked twice at most; released means the provider says the session is no longer running, not that the
41
- * request was sent. `request` answers "gone" when the provider no longer knows the session. */
42
- export async function releaseAndConfirm(o) {
43
- let failure;
44
- for (let attempt = 0; attempt < 2; attempt += 1) {
45
- try {
46
- if ((await o.request()) === "gone")
47
- return o.forget();
48
- failure = undefined;
49
- break;
50
- }
51
- catch (error) {
52
- failure = error;
53
- }
54
- }
55
- for (let poll = 0;; poll += 1) {
56
- const now = await o.status();
57
- if (now !== "running" && now !== "pending")
58
- return o.forget();
59
- if (poll >= o.confirm.polls)
60
- throw failure ?? new Error(o.stillRunning);
61
- await o.sleep(o.confirm.intervalMs);
62
- }
63
- }
64
- // Process-wide on purpose: a provider built later (custody builds one for the release) must still close the attach socket,
65
- // drop the dial binding and reuse the account's upload. The URLs carry tokens and are never written anywhere.
66
- export const browserbaseHoldings = {
67
- connectUrls: new Map(),
68
- settings: new Map(),
69
- opening: new Map(),
70
- uploads: new Map(),
71
- boundDials: new Map(),
72
- };
73
- export const kernelHoldings = {
74
- cdpUrls: new Map(),
75
- liveUrls: new Map(),
76
- uploads: new Map(),
77
- };
78
- /** Which session may save to a named profile now, by profile: claimed by both cloud providers (providers/profiles.ts). */
2
+ /** Which session may save to a named profile now, by profile: claimed by the local Chrome provider (providers/profiles.ts). */
79
3
  export const profileHoldings = {
80
4
  writers: new Map(),
81
5
  };
82
- export function resetProviderHoldings() {
83
- for (const holdings of [browserbaseHoldings, kernelHoldings, profileHoldings])
84
- for (const map of Object.values(holdings))
85
- map.clear();
86
- }
@@ -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";
8
- import { cdpCall } from "./cdp-call.js";
10
+ import { fileURLToPath } from "node:url";
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