@parcha/pi-browser 0.1.0-beta.17 → 0.1.0-beta.19

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 (87) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +177 -39
  3. package/dist/coding-agent-local.js +2 -1
  4. package/dist/coding-agent.d.ts +42 -2
  5. package/dist/coding-agent.js +159 -21
  6. package/dist/core/clip.d.ts +31 -0
  7. package/dist/core/clip.js +49 -0
  8. package/dist/core/contract.d.ts +4 -1
  9. package/dist/core/contract.js +40 -7
  10. package/dist/core/custody.d.ts +79 -5
  11. package/dist/core/custody.js +66 -5
  12. package/dist/core/decisions.d.ts +4 -0
  13. package/dist/core/dial.d.ts +7 -0
  14. package/dist/core/dial.js +41 -0
  15. package/dist/core/downloads.d.ts +1 -0
  16. package/dist/core/downloads.js +17 -5
  17. package/dist/core/driving-guard.d.ts +13 -0
  18. package/dist/core/driving-guard.js +61 -0
  19. package/dist/core/driving.d.ts +61 -0
  20. package/dist/core/driving.js +156 -0
  21. package/dist/core/effects.js +33 -13
  22. package/dist/core/evidence.d.ts +3 -1
  23. package/dist/core/failures.d.ts +5 -1
  24. package/dist/core/failures.js +20 -4
  25. package/dist/core/files.d.ts +8 -0
  26. package/dist/core/files.js +74 -0
  27. package/dist/core/find.d.ts +3 -1
  28. package/dist/core/find.js +2 -1
  29. package/dist/core/guard.d.ts +9 -1
  30. package/dist/core/guard.js +7 -2
  31. package/dist/core/host.d.ts +49 -1
  32. package/dist/core/images.d.ts +10 -2
  33. package/dist/core/images.js +4 -4
  34. package/dist/core/lease.d.ts +1 -1
  35. package/dist/core/lease.js +2 -1
  36. package/dist/core/session-control.d.ts +2 -0
  37. package/dist/core/session-control.js +5 -0
  38. package/dist/core/tools.d.ts +70 -4
  39. package/dist/core/tools.js +288 -45
  40. package/dist/core/unanswered.d.ts +3 -0
  41. package/dist/core/unanswered.js +17 -0
  42. package/dist/core/usage.d.ts +2 -0
  43. package/dist/core/usage.js +6 -0
  44. package/dist/core/web.d.ts +1 -1
  45. package/dist/core/web.js +9 -7
  46. package/dist/driver/extension-worker.d.ts +4 -2
  47. package/dist/driver/extension-worker.js +16 -10
  48. package/dist/driver/page-driver.d.ts +8 -0
  49. package/dist/driver/page-driver.js +128 -0
  50. package/dist/driver/stagehand.d.ts +3 -1
  51. package/dist/driver/stagehand.js +40 -66
  52. package/dist/durable.d.ts +16 -4
  53. package/dist/durable.js +415 -82
  54. package/dist/index.d.ts +2 -0
  55. package/dist/index.js +2 -0
  56. package/dist/live-view/index.d.ts +4 -0
  57. package/dist/live-view/index.js +4 -0
  58. package/dist/live-view/protocol.d.ts +152 -0
  59. package/dist/live-view/protocol.js +84 -0
  60. package/dist/live-view/provider.d.ts +6 -0
  61. package/dist/live-view/provider.js +23 -0
  62. package/dist/live-view/server.d.ts +50 -0
  63. package/dist/live-view/server.js +342 -0
  64. package/dist/live-view/stream.d.ts +7 -0
  65. package/dist/live-view/stream.js +388 -0
  66. package/dist/live-view/token.d.ts +6 -0
  67. package/dist/live-view/token.js +13 -0
  68. package/dist/live-view/viewer.d.ts +6 -0
  69. package/dist/live-view/viewer.js +350 -0
  70. package/dist/live-view/ws.d.ts +19 -0
  71. package/dist/live-view/ws.js +176 -0
  72. package/dist/providers/assigned.d.ts +18 -0
  73. package/dist/providers/assigned.js +76 -0
  74. package/dist/providers/cdp-call.js +12 -2
  75. package/dist/providers/cdp.js +37 -11
  76. package/dist/recorder/follow.d.ts +10 -0
  77. package/dist/recorder/follow.js +27 -2
  78. package/dist/recorder/frames.d.ts +7 -0
  79. package/dist/recorder/frames.js +73 -5
  80. package/dist/store.d.ts +22 -3
  81. package/dist/store.js +75 -4
  82. package/dist/testing/backend.d.ts +26 -0
  83. package/dist/testing/backend.js +21 -3
  84. package/dist/testing/driver.d.ts +18 -1
  85. package/dist/testing/driver.js +4 -0
  86. package/dist/web.js +2 -2
  87. package/package.json +10 -2
@@ -14,11 +14,13 @@ class TargetsUnlistedError extends Error {
14
14
  * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
15
15
  * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
16
16
  * With no worker running nothing is held, and the worker is woken until it is listed. A target list the browser does
17
- * not give by DISCOVERY_MS is not a list without a worker: the attach fails. */
18
- export async function installedExtension(cdpUrl, signal, known) {
17
+ * not give by DISCOVERY_MS is not a list without a worker: the attach fails. `replyMs`: how long the close waits for the
18
+ * runtime's reply. An init still running in the extension answers it only once that init ends, since the runtime runs
19
+ * both one after the other; the socket outlives the deadline by that much more. */
20
+ export async function installedExtension(cdpUrl, signal, known, replyMs = CLOSE_REPLY_MS) {
19
21
  const socket = new WebSocket(cdpUrl);
20
22
  const deadline = Date.now() + DISCOVERY_MS;
21
- const timer = setTimeout(() => socket.close(), DISCOVERY_MS + CLEANUP_MS);
23
+ const timer = setTimeout(() => socket.close(), DISCOVERY_MS + CLEANUP_MS - CLOSE_REPLY_MS + replyMs);
22
24
  const stop = () => socket.close();
23
25
  signal?.addEventListener("abort", stop, { once: true });
24
26
  // A call the browser does not answer within `ms` (the deadline, unless shorter) settles empty, as does every call once
@@ -51,13 +53,17 @@ export async function installedExtension(cdpUrl, signal, known) {
51
53
  listener({ method: "closed" });
52
54
  reject(new Error("the CDP socket closed"));
53
55
  };
56
+ // A throw in a socket listener ends the process: a frame that is not JSON is dropped.
54
57
  socket.onmessage = (event) => {
55
- const message = JSON.parse(String(event.data));
56
- if (message.id !== undefined)
57
- pending.get(message.id)?.(message.result);
58
- else
59
- for (const listener of listeners)
60
- listener(message);
58
+ try {
59
+ const message = JSON.parse(String(event.data));
60
+ if (message?.id !== undefined)
61
+ pending.get(message.id)?.(message.result);
62
+ else
63
+ for (const listener of listeners)
64
+ listener(message);
65
+ }
66
+ catch { }
61
67
  };
62
68
  });
63
69
  let id = known ?? null;
@@ -106,7 +112,7 @@ export async function installedExtension(cdpUrl, signal, known) {
106
112
  await call("Runtime.enable", {}, sessionId);
107
113
  await call("Runtime.addBinding", { name: SEND_TO_HOST }, sessionId);
108
114
  const replied = new Promise((resolve) => {
109
- const wait = setTimeout(resolve, CLOSE_REPLY_MS);
115
+ const wait = setTimeout(resolve, replyMs);
110
116
  listeners.add((event) => {
111
117
  if (event.method === "closed") {
112
118
  clearTimeout(wait);
@@ -0,0 +1,8 @@
1
+ import type { PageDriver } from "../core/tools.js";
2
+ /** `batchMs` bounds every run batch; the page calls' own deadlines are fixed but for tests. */
3
+ export declare function pageDriver(stagehand: any, deadlines: {
4
+ batchMs: number;
5
+ snapshotMs?: number;
6
+ screenshotMs?: number;
7
+ uploadMs?: number;
8
+ }): PageDriver;
@@ -0,0 +1,128 @@
1
+ import { withinDeadline } from "../core/unanswered.js";
2
+ import { StagehandFacadeTools } from "../vendor/stagehand-facade/tools.js";
3
+ import { documentReads } from "./new-document.js";
4
+ import { NAVIGATED_SNAPSHOT_ERROR, NO_HYDRATED_SNAPSHOT_ERROR, staleSnapshotIdError } from "../vendor/stagehand-facade/contract.js";
5
+ const URL_READ_MS = 2_000;
6
+ /** Stagehand 4.1.0 sends a page's snapshot and screenshot with no response deadline (its url, title and active-page
7
+ * reads get 10 s) and cannot cancel one: a call the browser never answered held its tool call, and every facade call
8
+ * queued behind it, for 11 minutes in a smoke run. Set from the 2026-10-15/16 smoke arms' successful calls as
9
+ * max(30 s, 3x p99), at most 60 s: snapshot p99 1.4 s, screenshot p99 114 s. */
10
+ const SNAPSHOT_MS = 30_000;
11
+ const SCREENSHOT_MS = 60_000;
12
+ /** Setting a file input has no deadline in Stagehand either; it is bounded at the screenshot's 60 s. */
13
+ const UPLOAD_MS = 60_000;
14
+ /** How long a read that landed in a document a navigation replaced waits for the new one's DOMContentLoaded. */
15
+ const NEW_DOCUMENT_MS = 15_000;
16
+ /** Where an element is, in CSS pixels from the viewport's corner, once it is scrolled into view: how many the selector matches, and
17
+ * the box of the one that does. */
18
+ const locateCode = (selector) => `const viewport = await page.evaluate("({ width: innerWidth, height: innerHeight })");
19
+ ${selector === null ? "return { viewport };" : `const element = page.locator(${JSON.stringify(selector)});
20
+ const matches = await element.count();
21
+ if (matches !== 1) return { viewport, matches };
22
+ await element.scrollIntoViewIfNeeded();
23
+ return { viewport, matches, box: await element.boundingBox() };`}`;
24
+ /** In a batch of its own, which the browser runs after any batch still running, so the read never lands inside a
25
+ * pending navigation (a page call issued then never returns). Past URL_READ_MS, Stagehand's page.url(). */
26
+ async function documentUrl(stagehand, page) {
27
+ try {
28
+ const href = await stagehand.experimentalBatch(async (batch) => await batch.page.evaluate("location.href"), {}, { page, timeout: URL_READ_MS });
29
+ if (typeof href === "string" && href)
30
+ return href;
31
+ }
32
+ catch { }
33
+ return await page.url();
34
+ }
35
+ /** `target` with `own`'s members in place of its own; every other member is the target's. */
36
+ function overriding(target, own) {
37
+ return new Proxy(target, {
38
+ get(t, property) {
39
+ if (typeof property === "string" && Object.hasOwn(own, property))
40
+ return own[property];
41
+ const value = Reflect.get(t, property, t);
42
+ return typeof value === "function" ? value.bind(t) : value;
43
+ },
44
+ });
45
+ }
46
+ /** Batches run under `batchMs`, not the facade's fixed 60 s; one failing at or past it is a `TimeoutError`, since
47
+ * Stagehand's own is a plain Error. Each active page's snapshot and screenshot are bounded on the page itself, under
48
+ * the facade's queue: one past its deadline fails the facade call, so the calls queued behind it run and its late
49
+ * answer is never the facade's. */
50
+ function bounded(stagehand, deadlines) {
51
+ const page = (target) => overriding(target, {
52
+ snapshot: (options) => withinDeadline(target.snapshot(options), deadlines.snapshotMs, "page.snapshot"),
53
+ screenshot: (options) => withinDeadline(target.screenshot(options), deadlines.screenshotMs, "page.screenshot"),
54
+ });
55
+ const context = stagehand.browser.context;
56
+ return overriding(stagehand, {
57
+ experimentalBatch: async (callback, input, options = {}) => {
58
+ const started = Date.now();
59
+ try {
60
+ return await stagehand.experimentalBatch(callback, input, { ...options, timeout: deadlines.batchMs });
61
+ }
62
+ catch (error) {
63
+ if (Date.now() - started < deadlines.batchMs)
64
+ throw error;
65
+ throw Object.assign(new Error(`the run batch passed its ${deadlines.batchMs} ms deadline`, { cause: error }), { name: "TimeoutError" });
66
+ }
67
+ },
68
+ browser: overriding(stagehand.browser, { context: overriding(context, { activePage: async () => { const active = await context.activePage(); return active ? page(active) : active; } }) }),
69
+ });
70
+ }
71
+ /** `batchMs` bounds every run batch; the page calls' own deadlines are fixed but for tests. */
72
+ export function pageDriver(stagehand, deadlines) {
73
+ const host = bounded(stagehand, { snapshotMs: SNAPSHOT_MS, screenshotMs: SCREENSHOT_MS, ...deadlines });
74
+ const uploadMs = deadlines.uploadMs ?? UPLOAD_MS;
75
+ const facade = new StagehandFacadeTools(host);
76
+ const active = async () => {
77
+ const page = await host.browser.context.activePage();
78
+ if (!page)
79
+ throw new Error("Stagehand has no active page.");
80
+ return page;
81
+ };
82
+ // In a batch of its own, which the browser runs once the new document is its page's.
83
+ const newDocument = async () => stagehand.experimentalBatch(async (batch, input) => { await batch.page.waitForLoadState("domcontentloaded", input.ms); }, { ms: NEW_DOCUMENT_MS }, { page: await active(), timeout: NEW_DOCUMENT_MS + 1_000 });
84
+ const reads = documentReads(facade, newDocument);
85
+ return {
86
+ snapshot: (snapshotOptions) => reads.snapshot(snapshotOptions),
87
+ run: (input) => input.actions !== undefined ? facade.runActions(input.actions) : facade.run(input.code ?? ""),
88
+ url: async () => documentUrl(stagehand, await active()),
89
+ // The facade keeps each page's last snapshot's ids for its own actions; with none, an action by id fails NO_HYDRATED (a stale snapshot).
90
+ forgetSnapshots: () => { facade.snapshotsByPage.clear(); },
91
+ locate: (async (target) => {
92
+ let selector = null;
93
+ if (target?.id !== undefined) {
94
+ // The facade keeps each snapshot's IDs (as xpaths) for its own actions and offers them to no one else; a vendored file is not edited for it.
95
+ const ids = facade.snapshotsByPage;
96
+ const page = await active();
97
+ const snapshot = ids.get(page.pageId);
98
+ if (!snapshot)
99
+ throw new Error(NO_HYDRATED_SNAPSHOT_ERROR);
100
+ if ((await page.url()) !== snapshot.url)
101
+ throw new Error(NAVIGATED_SNAPSHOT_ERROR);
102
+ const xpath = snapshot.xpathById[target.id]?.replace(/\/text\(\)(\[\d+\])?$/iu, "");
103
+ if (!xpath)
104
+ throw new Error(staleSnapshotIdError(target.id));
105
+ selector = `xpath=${xpath}`;
106
+ }
107
+ else if (target?.selector !== undefined)
108
+ selector = target.selector;
109
+ return await facade.run(locateCode(selector));
110
+ }),
111
+ screenshot: async ({ type = "png", quality, fullPage, scale, clip }) => {
112
+ // A clip is read from the viewport's corner, and the browser's own is from the document's: the scroll offset is added.
113
+ const origin = clip ? await facade.run(`return await page.evaluate("({ x: scrollX, y: scrollY })");`) : null;
114
+ const bytes = await (await active()).screenshot({
115
+ type, ...(fullPage === undefined ? {} : { fullPage }), ...(scale === undefined ? {} : { scale }),
116
+ ...(clip && origin ? { clip: { ...clip, x: clip.x + origin.x, y: clip.y + origin.y } } : {}),
117
+ // CDP takes a quality for jpeg only, and only as an integer.
118
+ ...(type === "jpeg" && quality !== undefined ? { quality: Math.round(quality) } : {}),
119
+ });
120
+ return { data: Buffer.from(bytes).toString("base64"), mimeType: type === "jpeg" ? "image/jpeg" : "image/png" };
121
+ },
122
+ page: () => reads.page(),
123
+ // An upload is effectful: past its deadline it fails as unanswered, and the page tools tell it as possibly applied.
124
+ setInputFiles: async (selector, file) => { await withinDeadline((await active()).locator(selector).setInputFiles({ name: file.name, mimeType: file.mimeType, buffer: file.buffer }), uploadMs, "locator.setInputFiles"); },
125
+ // Stagehand's own close keeps the browser for another attach; the browser's close would end it.
126
+ close: () => stagehand.close(),
127
+ };
128
+ }
@@ -1,4 +1,4 @@
1
- import type { DriverFactory } from "../core/custody.js";
1
+ import { type DriverFactory } from "../core/custody.js";
2
2
  import type { PageDriver } from "../core/tools.js";
3
3
  /** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
4
4
  export declare const STAGEHAND_TELEMETRY: {
@@ -21,5 +21,7 @@ export declare const SEALED_STAGEHAND: {
21
21
  };
22
22
  };
23
23
  };
24
+ /** What Stagehand's extension answers an init while another is still running in it. */
25
+ export declare const STAGEHAND_INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
24
26
  /** The batch deadline comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. */
25
27
  export declare function stagehandDriver(): DriverFactory<PageDriver>;
@@ -1,6 +1,9 @@
1
- import { StagehandFacadeTools } from "../vendor/stagehand-facade/tools.js";
1
+ // Stagehand is created sealed: no inference leaves through it (act, extract and observe are refused), nothing is cached
2
+ // server side, and the driver never ends the browser: custody releases it through the provider.
3
+ import { BrowserFailureError } from "../core/custody.js";
4
+ import { browserFailure } from "../core/failures.js";
2
5
  import { installedExtension } from "./extension-worker.js";
3
- import { documentReads } from "./new-document.js";
6
+ import { pageDriver } from "./page-driver.js";
4
7
  /** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
5
8
  export const STAGEHAND_TELEMETRY = { traces: { endpoint: "http://127.0.0.1:9/v1/traces" } };
6
9
  export const STAGEHAND_INFERENCE_REFUSED = "Stagehand inference is off in this harness: act, extract and observe are unavailable. Drive the page with run code or snapshot IDs.";
@@ -10,43 +13,14 @@ export const SEALED_STAGEHAND = {
10
13
  model: { generate: async () => { throw new Error(STAGEHAND_INFERENCE_REFUSED); } },
11
14
  telemetry: STAGEHAND_TELEMETRY,
12
15
  };
13
- const URL_READ_MS = 2_000;
14
- /** How long a read that landed in a document a navigation replaced waits for the new one's DOMContentLoaded. */
15
- const NEW_DOCUMENT_MS = 15_000;
16
- /** In a batch of its own, which the browser runs after any batch still running, so the read never lands inside a
17
- * pending navigation (a page call issued then never returns). Past URL_READ_MS, Stagehand's page.url(). */
18
- async function documentUrl(stagehand, page) {
19
- try {
20
- const href = await stagehand.experimentalBatch(async (batch) => await batch.page.evaluate("location.href"), {}, { page, timeout: URL_READ_MS });
21
- if (typeof href === "string" && href)
22
- return href;
23
- }
24
- catch { }
25
- return await page.url();
26
- }
27
- /** Batches run under `timeoutMs`, not the facade's fixed 60 s; one failing at or past it is a `TimeoutError`, since
28
- * Stagehand's own is a plain Error. */
29
- function withBatchTimeout(stagehand, timeoutMs) {
30
- return new Proxy(stagehand, {
31
- get(target, property) {
32
- if (property === "experimentalBatch") {
33
- return async (callback, input, options = {}) => {
34
- const started = Date.now();
35
- try {
36
- return await target.experimentalBatch(callback, input, { ...options, timeout: timeoutMs });
37
- }
38
- catch (error) {
39
- if (Date.now() - started < timeoutMs)
40
- throw error;
41
- throw Object.assign(new Error(`the run batch passed its ${timeoutMs} ms deadline`, { cause: error }), { name: "TimeoutError" });
42
- }
43
- };
44
- }
45
- const value = Reflect.get(target, property, target);
46
- return typeof value === "function" ? value.bind(target) : value;
47
- },
48
- });
49
- }
16
+ /** What Stagehand's extension answers an init while another is still running in it. */
17
+ export const STAGEHAND_INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
18
+ /** Stagehand's own init deadline: an init the extension is still running has ended by then. */
19
+ const IN_FLIGHT_INIT_MS = 60_000;
20
+ const initInProgress = (error) => {
21
+ const cause = error?.cause;
22
+ return !!cause && typeof cause === "object" && typeof cause.code === "number" && cause.message === STAGEHAND_INIT_IN_PROGRESS;
23
+ };
50
24
  /** The batch deadline comes from `DriverOptions`; a caller that passes none gets the facade's 60 s. */
51
25
  export function stagehandDriver() {
52
26
  return async (target, signal, options) => {
@@ -58,32 +32,32 @@ export function stagehandDriver() {
58
32
  const named = (step) => step.catch((error) => { throw new Error(`attaching to the browser at ${host} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error }); });
59
33
  const extensionId = await named(installedExtension(target.sdkCdpUrl, signal, target.extensionId));
60
34
  const browser = await named(localBrowser.connect({ cdpUrl: target.sdkCdpUrl, ...(extensionId ? { extensionId } : {}) }));
61
- const stagehand = await Stagehand.create({ browser, ...SEALED_STAGEHAND });
62
- const facade = new StagehandFacadeTools(withBatchTimeout(stagehand, options?.batchTimeoutMs ?? 60_000));
63
- const active = async () => {
64
- const page = await stagehand.browser.context.activePage();
65
- if (!page)
66
- throw new Error("Stagehand has no active page.");
67
- return page;
68
- };
69
- // In a batch of its own, which the browser runs once the new document is its page's.
70
- const newDocument = async () => stagehand.experimentalBatch(async (batch, input) => { await batch.page.waitForLoadState("domcontentloaded", input.ms); }, { ms: NEW_DOCUMENT_MS }, { page: await active(), timeout: NEW_DOCUMENT_MS + 1_000 });
71
- const reads = documentReads(facade, newDocument);
72
- return {
73
- snapshot: (snapshotOptions) => reads.snapshot(snapshotOptions),
74
- run: (input) => input.actions !== undefined ? facade.runActions(input.actions) : facade.run(input.code ?? ""),
75
- url: async () => documentUrl(stagehand, await active()),
76
- screenshot: async ({ type = "png", quality, fullPage, scale }) => {
77
- const bytes = await (await active()).screenshot({
78
- type, ...(fullPage === undefined ? {} : { fullPage }), ...(scale === undefined ? {} : { scale }),
79
- // CDP takes a quality for jpeg only, and only as an integer.
80
- ...(type === "jpeg" && quality !== undefined ? { quality: Math.round(quality) } : {}),
81
- });
82
- return { data: Buffer.from(bytes).toString("base64"), mimeType: type === "jpeg" ? "image/jpeg" : "image/png" };
83
- },
84
- page: () => reads.page(),
85
- // Stagehand's own close keeps the browser for another attach; the browser's close would end it.
86
- close: () => stagehand.close(),
87
- };
35
+ let stagehand;
36
+ try {
37
+ stagehand = await Stagehand.create({ browser, ...SEALED_STAGEHAND });
38
+ }
39
+ catch (error) {
40
+ if (!initInProgress(error))
41
+ throw error;
42
+ // A cancelled call never starts an init of its own, however the wait ended.
43
+ const stopIfCancelled = () => {
44
+ if (signal?.aborted)
45
+ throw signal.reason instanceof Error ? signal.reason : Object.assign(new Error("the attach was cancelled"), { name: "AbortError" });
46
+ };
47
+ stopIfCancelled();
48
+ // An attach that gave up (a dropped connection, a deadline) left its init running in the extension. A close
49
+ // queues behind that init, so its reply means the init has ended; this attach then inits once more.
50
+ await named(installedExtension(target.sdkCdpUrl, signal, extensionId ?? undefined, IN_FLIGHT_INIT_MS));
51
+ stopIfCancelled();
52
+ try {
53
+ stagehand = await Stagehand.create({ browser, ...SEALED_STAGEHAND });
54
+ }
55
+ catch (again) {
56
+ if (!initInProgress(again))
57
+ throw again;
58
+ throw new BrowserFailureError(browserFailure("browser_unavailable", `The browser at ${host} is still finishing an earlier connection after ${IN_FLIGHT_INIT_MS / 1_000} s. Call again in a moment, or call browser_relaunch for a fresh session.`, { retryable: true }));
59
+ }
60
+ }
61
+ return pageDriver(stagehand, { batchMs: options?.batchTimeoutMs ?? 60_000 });
88
62
  };
89
63
  }
package/dist/durable.d.ts CHANGED
@@ -4,8 +4,9 @@ import { type DriverFactory } from "./core/custody.js";
4
4
  import type { Decisions } from "./core/decisions.js";
5
5
  import type { EvidenceSink } from "./core/evidence.js";
6
6
  import { EffectObserver } from "./core/effects.js";
7
+ import type { DrivingGates } from "./live-view/protocol.js";
7
8
  import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
8
- import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionRow, SessionsState, SiteInfo, SiteRunPort } from "./core/host.js";
9
+ import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionRow, SessionsState, SiteInfo, SiteRunPort, HandoffPort, WorkspaceFiles } from "./core/host.js";
9
10
  export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
10
11
  export type { DriverFactory, DriverOptions } from "./core/custody.js";
11
12
  export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
@@ -22,8 +23,12 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
22
23
  /** Implementations by contract name, over the package's own; a contract tool with no implementation is not listed. */
23
24
  tools?: Partial<BrowserToolImpls<D>>;
24
25
  evidence: EvidenceSink;
25
- /** Where `browser_downloads` writes files; absent, the tool is not listed. */
26
+ /** Where `browser_downloads` writes files and, without `files`, where `browser_upload` reads them; absent, neither is listed. */
26
27
  workspace?: (conversationId: ConversationId) => string;
28
+ /** Reaches a person for `browser_request_handoff`; absent, the tool is not listed. */
29
+ handoff?: HandoffPort;
30
+ /** Resolves `browser_upload` paths; defaults to files under `workspace`. */
31
+ files?: WorkspaceFiles;
27
32
  /** `use_website`'s sites; absent, the tool is not listed. `listing` is the port's `list()`, read once at host setup:
28
33
  * the tool's description renders from it. Each local child runs in a conversation this call owns. */
29
34
  sites?: {
@@ -32,6 +37,9 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
32
37
  };
33
38
  /** Live view and session status; a throw here never fails a call. */
34
39
  onSession?: (row: SessionRow, change: SessionChange) => void | Promise<void>;
40
+ /** The person/model mutex shared with the live view (`createLiveView`'s `gates`); the default, the package's process-wide `drivingGates`, is the one the live view
41
+ * defaults to as well. Pass it here only together with the same registry there. */
42
+ gates?: DrivingGates;
35
43
  /** A session runs without the effect observer its policy asked for; a throw here never fails a call. */
36
44
  onObserver?: (row: ObserverRow) => void | Promise<void>;
37
45
  prices?: Partial<PriceTable>;
@@ -70,13 +78,17 @@ export type BrowserExtensionHandle = {
70
78
  }>;
71
79
  };
72
80
  tools: readonly ToolRegistration[];
73
- /** Shutdown path (pi has no conversation-end event): commits `releasing` and a release task; it does not wait. */
81
+ /** Shutdown path (pi has no conversation-end event): closes the conversation's drivers and commits `releasing` and a
82
+ * release task; it does not wait for the task. A commit that throws still releases the conversation's sessions at
83
+ * the provider, then rejects with the commit's error. */
74
84
  release(conversation: Conversation, reason: ReleaseReason, context: Context): Promise<void>;
75
85
  /** At run open, after install and before resume: every open lease is reconciled with its provider. */
76
86
  reconcile(harness: Harness, isActive: (conversationId: ConversationId) => boolean, context: Context): Promise<ReconcileReport>;
77
87
  /** Shutdown is release, `waitForIdle`, `drain`, close: resolves when none of this extension's release tasks is live. */
78
88
  drain(harness: Harness, context: Context, signal?: AbortSignal): Promise<void>;
79
- /** Drop in-memory driver attachments and idle timers (process exit); never releases. */
89
+ /** Drop in-memory driver attachments and idle timers (process exit). Over a healthy store it releases nothing; over
90
+ * one that failed (a release commit of this process threw, or the Session ended failed) it releases every session
91
+ * this process still owns at the provider. */
80
92
  close(): Promise<void>;
81
93
  /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
82
94
  retained(): number;