@parcha/pi-browser 0.1.0-beta.13 → 0.1.0-beta.14

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.
@@ -1,26 +1,41 @@
1
1
  import { BrowserFailureError } from "./custody.js";
2
2
  import { defaultInline } from "./evidence.js";
3
- import { classifyBrowserError } from "./failures.js";
3
+ import { browserFailure, classifyBrowserError } from "./failures.js";
4
4
  import { createRepeatGuard } from "./guard.js";
5
5
  import { captureWithinBudget } from "./images.js";
6
6
  import { orderFacts, receiptFacts, sha256Hex } from "./receipts.js";
7
7
  import { scrubPageUrl } from "./redact.js";
8
8
  import { pageNotice, wallFailure, wallOf } from "./web.js";
9
9
  const WHATS = ["markdown", "text", "html", "url", "title"];
10
+ const DROPPED_RUN = "The connection to your browser session dropped; the session is still open, and your next browser call reconnects to it with its pages and cookies. This run may have acted before the drop: take a snapshot to see the page before running again.";
11
+ const DROPPED_FOR_GOOD = "The connection to your browser session dropped and could not be re-established, though the session is still open. Call browser_relaunch for a fresh session (its pages and cookies are gone), or use web_fetch.";
10
12
  const text = (value, isError = false) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(isError ? { isError: true } : {}) });
11
13
  const withNews = (news, body) => (news ? `${news}\n\n${body}` : body);
12
14
  const pageUrl = (call, raw) => scrubPageUrl(raw, call.redact);
13
15
  /** A cut run that was observed and sent nothing that left the browser is safe to run again. */
14
16
  const harmless = (p) => p.observed === true && !(p.sent ?? []).some((r) => r.held !== "denied");
15
17
  function interruptedNotice(p, now) {
16
- const head = `Your run call ${p.callId}${p.url ? ` on ${p.url}` : ""} was interrupted`;
18
+ const where = `Your run call ${p.callId}${p.url ? ` on ${p.url}` : ""}`;
19
+ const sent = (p.sent ?? []).filter((r) => r.held !== "denied").map((r) => `${r.method} ${r.origin}${r.path}`);
20
+ if (p.finished) {
21
+ const head = `${where} ran, but the process stopped before its answer reached you`;
22
+ if (harmless(p))
23
+ return `${head}; it sent no request that changes anything, so it is safe to run again. The page is now ${now}.`;
24
+ if (sent.length)
25
+ return `${head}, after it sent ${sent.join(", ")}; the page is now ${now}. Check on the page whether that landed before acting again, and do not send it again if it did.`;
26
+ return `${head}, so what it did has taken effect; the page is now ${now}. Look at it with snapshot before acting again.`;
27
+ }
28
+ const head = `${where} was interrupted`;
17
29
  if (harmless(p))
18
30
  return `${head} before it sent any request that changes anything; it is safe to run again. The page is now ${now}.`;
19
- const sent = (p.sent ?? []).filter((r) => r.held !== "denied").map((r) => `${r.method} ${r.origin}${r.path}`);
20
31
  if (sent.length)
21
32
  return `${head} after it sent ${sent.join(", ")}; the page is now ${now}. Check on the page whether that landed before acting again, and do not send it again if it did.`;
22
33
  return `${head} and may have taken effect; the page is now ${now}. Check it with snapshot before acting again.`;
23
34
  }
35
+ const factsOf = (p, now) => ({
36
+ callId: p.callId, urlAtDispatch: p.url, urlNow: now, observed: p.observed === true,
37
+ sent: p.watched ? (p.sent ?? []).map((r) => ({ method: r.method, url: `${r.origin}${r.path}`, held: r.held })) : null,
38
+ });
24
39
  async function markdown(html, fallback) {
25
40
  try {
26
41
  const [{ parse }, { NodeHtmlMarkdown }] = await Promise.all([import("node-html-parser"), import("node-html-markdown")]);
@@ -33,8 +48,8 @@ async function markdown(html, fallback) {
33
48
  catch { }
34
49
  return { body: fallback, extractor: "inner-text", ext: "txt" };
35
50
  }
36
- export function pageTools() {
37
- const guards = new Map();
51
+ /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
52
+ export function pageTools({ guards = new Map() } = {}) {
38
53
  const guardOf = (conversationId) => guards.get(conversationId) ?? guards.set(conversationId, createRepeatGuard()).get(conversationId);
39
54
  async function failureOf(error, effectful, port, call) {
40
55
  if (error instanceof BrowserFailureError)
@@ -45,55 +60,74 @@ export function pageTools() {
45
60
  return first;
46
61
  return classifyBrowserError(error, effectful, { ...facts, sessionEnded: true });
47
62
  }
48
- async function perform(tool, args, port, call, effectful, body) {
63
+ /** A replay-unsafe action is journaled before it acts and marked finished after; the entry stays until a later call
64
+ * settles it, so a process that dies before pi commits the answer leaves a cut for the resumed run. */
65
+ async function dispatched(port, call, s, key, action) {
66
+ await port.dispatching({ callId: call.callId, codeSha: key, url: s.record.lastUrl, observed: s.effects?.holding === true, watched: s.effects != null });
67
+ try {
68
+ return await action();
69
+ }
70
+ finally {
71
+ await port.mark("finished", call.callId).catch(() => undefined);
72
+ }
73
+ }
74
+ async function perform(tool, args, port, call, kind, body) {
75
+ const effect = typeof kind === "object" ? kind.effect : null;
76
+ const effectful = effect !== null;
49
77
  const guard = guardOf(call.conversationId);
50
78
  const refused = guard.check(tool, args);
51
79
  if (refused)
52
80
  return text(refused, true);
53
- // Custody's news is told on this call whatever it ends in: a cut run is settled once it has been told.
81
+ // A cut is told once, on the call after it, whatever that call ends in. An identical action is refused until a look
82
+ // that follows the refusal settles the cut.
54
83
  let news = "";
84
+ let cut = null;
85
+ let facts = null;
86
+ const tell = (out) => (facts ? { ...out, details: { ...out.details, pendingEffect: facts } } : out);
87
+ const done = (out) => { guard.note(tool, args, null); return tell(out); };
88
+ const fail = (failure) => { guard.note(tool, args, failure); return tell(text(news ? { ...failure, notice: news } : failure, true)); };
89
+ const looked = async (out) => { if (kind === "look" && cut?.refused)
90
+ await port.settle(cut.callId); return done(out); };
55
91
  try {
56
92
  const s = await port.session();
57
93
  news = s.notice ?? "";
58
- if (s.interrupted) {
59
- const now = pageUrl(call, await s.driver.url().catch(() => "gone"));
60
- news = [news, interruptedNotice(s.interrupted, now)].filter(Boolean).join(" ");
61
- await port.settle();
94
+ cut = s.interrupted;
95
+ const same = cut !== null && effect === cut.codeSha && !harmless(cut);
96
+ if (cut && (!cut.told || same))
97
+ facts = factsOf(cut, pageUrl(call, await s.driver.url().catch(() => "gone")));
98
+ if (cut && !cut.told) {
99
+ news = [news, interruptedNotice(cut, facts.urlNow)].filter(Boolean).join(" ");
100
+ await (harmless(cut) ? port.settle(cut.callId) : port.mark("told", cut.callId));
62
101
  }
63
- const out = await body(s, news);
64
- guard.note(tool, args, null);
65
- return out;
102
+ if (cut && same) {
103
+ await port.mark("refused", cut.callId);
104
+ return done(text(browserFailure("effect_unknown", `${news ? `${news} ` : ""}This is the same code, and it may already have taken effect, so it is not run again now: look at the page with snapshot or browser_read before you run this again.`, { retryable: true, effect: "possibly_effected" }), true));
105
+ }
106
+ return await looked(effect === null ? await body(s, news) : await dispatched(port, call, s, effect, () => body(s, news)));
66
107
  }
67
108
  catch (error) {
68
- let failure = await failureOf(error, effectful, port, call);
69
- // A dropped CDP connection to a session the provider still runs: reconnect. A read runs once more; a run, which
109
+ const failure = await failureOf(error, effectful, port, call);
110
+ if (failure.code !== "browser_unavailable" || error instanceof BrowserFailureError)
111
+ return fail(failure);
112
+ // A dropped CDP connection to a session the provider still runs: a read reconnects and runs once more; a run, which
70
113
  // may have acted, is not repeated.
71
- if (failure.code === "browser_unavailable" && !(error instanceof BrowserFailureError)) {
72
- await port.dropped().catch(() => undefined);
73
- if (effectful)
74
- failure = { ...failure, retryable: true, message: "The connection to your browser session dropped; the session is still open, and your next browser call reconnects to it with its pages and cookies. This run may have acted before the drop: take a snapshot to see the page before running again." };
75
- else {
76
- let again = null;
77
- try {
78
- again = await port.session();
79
- }
80
- catch (reconnect) {
81
- const refused = await failureOf(reconnect, effectful, port, call);
82
- failure = refused.code === "aborted" || refused.code === "auth" ? refused : { ...refused, code: "browser_unavailable", retryable: false, message: "The connection to your browser session dropped and could not be re-established, though the session is still open. Call browser_relaunch for a fresh session (its pages and cookies are gone), or use web_fetch." };
83
- }
84
- if (again)
85
- try {
86
- const out = await body(again, news);
87
- guard.note(tool, args, null);
88
- return out;
89
- }
90
- catch (retried) {
91
- failure = await failureOf(retried, effectful, port, call);
92
- }
93
- }
114
+ await port.dropped().catch(() => undefined);
115
+ if (effectful)
116
+ return fail({ ...failure, retryable: true, message: DROPPED_RUN });
117
+ let again;
118
+ try {
119
+ again = await port.session();
120
+ }
121
+ catch (reconnect) {
122
+ const refused = await failureOf(reconnect, effectful, port, call);
123
+ return fail(refused.code === "aborted" || refused.code === "auth" ? refused : { ...refused, code: "browser_unavailable", retryable: false, message: DROPPED_FOR_GOOD });
124
+ }
125
+ try {
126
+ return await looked(await body(again, news));
127
+ }
128
+ catch (retried) {
129
+ return fail(await failureOf(retried, effectful, port, call));
94
130
  }
95
- guard.note(tool, args, failure);
96
- return text(news ? { ...failure, notice: news } : failure, true);
97
131
  }
98
132
  }
99
133
  async function file(s, call, record) {
@@ -102,17 +136,13 @@ export function pageTools() {
102
136
  return { path: filed?.path ?? null, bodyLine: filed?.bodyLine ?? null, sha256: facts.sha256 };
103
137
  }
104
138
  return {
105
- snapshot: (args, port, call) => perform("snapshot", args ?? {}, port, call, false, async (s, news) => text(withNews(news, await s.driver.snapshot(args ?? {})))),
139
+ snapshot: (args, port, call) => perform("snapshot", args ?? {}, port, call, "look", async (s, news) => text(withNews(news, await s.driver.snapshot(args ?? {})))),
106
140
  run: async (args, port, call) => {
107
141
  if ((args?.code === undefined) === (args?.actions === undefined)) {
108
- return text({ ok: false, code: "refused", retryable: false, effect: "none", message: "run requires exactly one of code or actions" }, true);
142
+ return text(browserFailure("refused", "run requires exactly one of code or actions"), true);
109
143
  }
110
144
  const codeSha = sha256Hex(JSON.stringify(args.code ?? args.actions));
111
- return perform("run", args, port, call, true, async (s, news) => {
112
- if (s.interrupted?.codeSha === codeSha && !harmless(s.interrupted)) {
113
- return text({ ok: false, code: "effect_unknown", retryable: true, effect: "possibly_effected", message: `${news} This is the same code, so it is not run again now: check whether it landed, then call run again only if it did not.` }, true);
114
- }
115
- await port.dispatching({ callId: call.callId, codeSha, url: s.record.lastUrl, observed: s.effects?.holding === true });
145
+ return perform("run", args, port, call, { effect: codeSha }, async (s, news) => {
116
146
  const sent = [];
117
147
  const stop = s.effects?.record((row) => { sent.push({ method: row.method, url: call.redact(`${row.origin}${row.path}`), held: row.held }); return port.journal(row); });
118
148
  let value;
@@ -122,7 +152,6 @@ export function pageTools() {
122
152
  finally {
123
153
  await s.effects?.flush(call.signal).catch(() => undefined);
124
154
  stop?.();
125
- await port.settle();
126
155
  }
127
156
  const url = await s.driver.url().catch(() => null);
128
157
  // Compared as custody keeps it, so a page with a query value never looks new on every run.
@@ -134,20 +163,21 @@ export function pageTools() {
134
163
  });
135
164
  },
136
165
  screenshot: (args, port, call) => {
137
- const { ask: _ask, ...requested } = args ?? {};
138
- return perform("screenshot", args ?? {}, port, call, false, async (s, news) => {
166
+ const { ask: asked, ...requested } = args ?? {};
167
+ const ask = typeof asked === "string" && asked.trim() ? asked.trim() : undefined;
168
+ return perform("screenshot", args ?? {}, port, call, "read", async (s, news) => {
139
169
  const shot = await captureWithinBudget((options) => s.driver.screenshot(options), requested);
140
170
  const url = pageUrl(call, await s.driver.url());
141
171
  const receipt = await file(s, call, { tool: "screenshot", args: requested, status: "ok", facts: { final_url: url }, body: Buffer.from(shot.data, "base64"), ext: shot.size.type === "png" ? "png" : "jpg" });
142
172
  const first = shot.adjusted?.first;
143
173
  const adjusted = shot.adjusted && `adjusted: the first capture${first ? ` (${first.width}x${first.height})` : ""} was over the ${shot.adjusted.why === "long_edge" ? "2,000 px long edge" : "size"} budget; this is the viewport at ${shot.size.width}x${shot.size.height}`;
144
174
  const lines = [news, `url: ${url}`, `evidence: ${receipt.path ?? "(not filed)"}`, adjusted].filter(Boolean).join("\n");
145
- return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256 } };
175
+ return { content: [{ type: "text", text: lines }, { type: "image", data: shot.data, mimeType: shot.mimeType }], details: { evidence: receipt.path, sha256: receipt.sha256, ...(ask ? { media: { ask } } : {}) } };
146
176
  });
147
177
  },
148
178
  browser_read: (args, port, call) => {
149
- const what = WHATS.includes(args?.what) ? args.what : "markdown";
150
- return perform("browser_read", { what }, port, call, false, async (s, news) => {
179
+ const what = args?.what && WHATS.includes(args.what) ? args.what : "markdown";
180
+ return perform("browser_read", { what }, port, call, "look", async (s, news) => {
151
181
  const page = await s.driver.page();
152
182
  const read = what === "markdown" ? await markdown(page.html, page.text)
153
183
  : what === "html" ? { body: page.html, extractor: "raw", ext: "html" }
@@ -1,23 +1,4 @@
1
- import { type PriceTable, type SessionRecord } from "./host.js";
2
- export type PriceState = "priced" | "unpriced" | "invalid";
3
- export type PiUsage = {
4
- input: 0;
5
- output: 0;
6
- cacheRead: 0;
7
- cacheWrite: 0;
8
- totalTokens: 0;
9
- cost: {
10
- input: 0;
11
- output: 0;
12
- cacheRead: 0;
13
- cacheWrite: 0;
14
- total: number;
15
- };
16
- };
17
- export type ToolUsage = {
18
- usage: PiUsage;
19
- state: PriceState;
20
- };
1
+ import { type PriceState, type PriceTable, type SessionRecord, type ToolUsage } from "./host.js";
21
2
  /** Dollars per minute: unset or blank is unpriced; anything but a non-negative decimal is invalid. Zero is a price. */
22
3
  export declare function sessionPrice(raw: string | null | undefined): {
23
4
  prices: Pick<PriceTable, "sessionUsdPerHour">;
@@ -0,0 +1,6 @@
1
+ export declare const STAGEHAND_EXTENSION = "Stagehand Runtime";
2
+ /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
3
+ * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
4
+ * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
5
+ * With no worker running nothing is held, and the worker is woken until it is listed. */
6
+ export declare function installedExtension(cdpUrl: string, signal?: AbortSignal, known?: string): Promise<string | null>;
@@ -0,0 +1,121 @@
1
+ export const STAGEHAND_EXTENSION = "Stagehand Runtime";
2
+ const DISCOVERY_MS = 10_000;
3
+ const WAKE_TRIES = 60;
4
+ const CLOSE_REPLY_MS = 3_000;
5
+ const SEND_TO_HOST = "__stagehandSendToHost";
6
+ const RESET_ID = 2_147_000_000;
7
+ /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
8
+ * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
9
+ * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
10
+ * With no worker running nothing is held, and the worker is woken until it is listed. */
11
+ export async function installedExtension(cdpUrl, signal, known) {
12
+ const socket = new WebSocket(cdpUrl);
13
+ const timer = setTimeout(() => socket.close(), DISCOVERY_MS);
14
+ const stop = () => socket.close();
15
+ signal?.addEventListener("abort", stop, { once: true });
16
+ // A call the browser never answers settles empty when the socket closes (the deadline, an abort, the browser).
17
+ const pending = new Map();
18
+ const listeners = new Set();
19
+ let next = 0;
20
+ let closed = false;
21
+ // A send on a closed socket neither throws nor is ever answered (Node 24): once closed, every call settles empty.
22
+ const call = (method, params = {}, sessionId) => new Promise((resolve) => {
23
+ if (closed || socket.readyState !== WebSocket.OPEN)
24
+ return resolve(undefined);
25
+ pending.set(++next, resolve);
26
+ socket.send(JSON.stringify({ id: next, method, params, ...(sessionId ? { sessionId } : {}) }));
27
+ });
28
+ try {
29
+ await new Promise((resolve, reject) => {
30
+ socket.onopen = () => resolve();
31
+ // A refused connection raises `error` and, on Node 22, never `close`: waiting for `close` alone would hang the
32
+ // attach.
33
+ socket.onerror = () => reject(new Error("Failed to open CDP WebSocket"));
34
+ socket.onclose = () => {
35
+ closed = true;
36
+ for (const settle of pending.values())
37
+ settle(undefined);
38
+ for (const listener of listeners)
39
+ listener({ method: "closed" });
40
+ reject(new Error("the CDP socket closed"));
41
+ };
42
+ socket.onmessage = (event) => {
43
+ const message = JSON.parse(String(event.data));
44
+ if (message.id !== undefined)
45
+ pending.get(message.id)?.(message.result);
46
+ else
47
+ for (const listener of listeners)
48
+ listener(message);
49
+ };
50
+ });
51
+ let id = known ?? null;
52
+ if (!id) {
53
+ const extensions = (await call("Extensions.getExtensions"))?.extensions ?? [];
54
+ const enabled = extensions.filter((extension) => extension.name === STAGEHAND_EXTENSION && extension.enabled);
55
+ if (enabled.length !== 1)
56
+ return null;
57
+ id = enabled[0].id;
58
+ }
59
+ const workers = async () => ((await call("Target.getTargets"))?.targetInfos ?? [])
60
+ .filter((target) => target.type === "service_worker" && target.url.startsWith(`chrome-extension://${id}/`))
61
+ .map((target) => target.targetId);
62
+ const running = await workers();
63
+ if (running.length === 0) {
64
+ let wake = null;
65
+ for (let tries = 0; !closed && tries < WAKE_TRIES && (await workers()).length === 0; tries += 1) {
66
+ if (tries % 10 === 0) {
67
+ if (wake)
68
+ await call("Target.closeTarget", { targetId: wake });
69
+ wake = (await call("Target.createTarget", { url: `chrome-extension://${id}/wake-service-worker.html` }))?.targetId ?? null;
70
+ }
71
+ await new Promise((r) => setTimeout(r, 100));
72
+ }
73
+ if (wake)
74
+ await call("Target.closeTarget", { targetId: wake });
75
+ return id;
76
+ }
77
+ const sessionId = (await call("Target.attachToTarget", { targetId: running[0], flatten: true }))?.sessionId;
78
+ if (!sessionId)
79
+ return id;
80
+ try {
81
+ await call("Runtime.enable", {}, sessionId);
82
+ await call("Runtime.addBinding", { name: SEND_TO_HOST }, sessionId);
83
+ const replied = new Promise((resolve) => {
84
+ const wait = setTimeout(resolve, CLOSE_REPLY_MS);
85
+ listeners.add((event) => {
86
+ if (event.method === "closed") {
87
+ clearTimeout(wait);
88
+ return resolve();
89
+ }
90
+ if (event.method !== "Runtime.bindingCalled" || event.sessionId !== sessionId || event.params?.name !== SEND_TO_HOST)
91
+ return;
92
+ let reply = null;
93
+ try {
94
+ reply = JSON.parse(event.params.payload);
95
+ }
96
+ catch { }
97
+ if (reply?.id === RESET_ID) {
98
+ clearTimeout(wait);
99
+ resolve();
100
+ }
101
+ });
102
+ });
103
+ const close = JSON.stringify({ jsonrpc: "2.0", id: RESET_ID, method: "stagehand.close", params: {} });
104
+ const sent = await call("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost(${JSON.stringify(close)}); true`, returnByValue: true }, sessionId);
105
+ if (sent && !sent.exceptionDetails)
106
+ await replied;
107
+ }
108
+ finally {
109
+ await call("Target.detachFromTarget", { sessionId });
110
+ }
111
+ return id;
112
+ }
113
+ catch {
114
+ return known ?? null;
115
+ }
116
+ finally {
117
+ clearTimeout(timer);
118
+ signal?.removeEventListener("abort", stop);
119
+ socket.close();
120
+ }
121
+ }
@@ -1,4 +1,5 @@
1
1
  import { StagehandFacadeTools } from "../vendor/stagehand-facade/tools.js";
2
+ import { installedExtension } from "./extension-worker.js";
2
3
  /** A closed loopback port, so no span leaves the host: Stagehand 4.1.0 cannot turn its trace exporter off. */
3
4
  export const STAGEHAND_TELEMETRY = { traces: { endpoint: "http://127.0.0.1:9/v1/traces" } };
4
5
  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.";
@@ -8,8 +9,6 @@ export const SEALED_STAGEHAND = {
8
9
  model: { generate: async () => { throw new Error(STAGEHAND_INFERENCE_REFUSED); } },
9
10
  telemetry: STAGEHAND_TELEMETRY,
10
11
  };
11
- const STAGEHAND_EXTENSION = "Stagehand Runtime";
12
- const DISCOVERY_MS = 10_000;
13
12
  // A page's address is its document's (location.href): page.url() names a goto's target once Chrome starts it, so a
14
13
  // receipt could cite a page it does not hold. One evaluate reads all four, so they are one document's.
15
14
  const PAGE_CODE = `return await page.evaluate(() => ({
@@ -30,55 +29,6 @@ async function documentUrl(stagehand, page) {
30
29
  catch { }
31
30
  return await page.url();
32
31
  }
33
- /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
34
- * so a new attach would be refused: closing its service worker target (no page target) resets it first. */
35
- async function installedExtension(cdpUrl, signal, known) {
36
- const socket = new WebSocket(cdpUrl);
37
- const timer = setTimeout(() => socket.close(), DISCOVERY_MS);
38
- const stop = () => socket.close();
39
- signal?.addEventListener("abort", stop, { once: true });
40
- // A call the browser never answers settles empty when the socket closes (the deadline, an abort, the browser).
41
- const pending = new Map();
42
- let next = 0;
43
- const call = (method, params = {}) => new Promise((resolve) => { pending.set(++next, resolve); socket.send(JSON.stringify({ id: next, method, params })); });
44
- try {
45
- await new Promise((resolve, reject) => {
46
- socket.onopen = () => resolve();
47
- // A refused connection raises `error` and, on Node 22, never `close`: waiting for `close` alone would hang the
48
- // attach.
49
- socket.onerror = () => reject(new Error("Failed to open CDP WebSocket"));
50
- socket.onclose = () => { for (const settle of pending.values())
51
- settle(undefined); reject(new Error("the CDP socket closed")); };
52
- socket.onmessage = (event) => { const message = JSON.parse(String(event.data)); pending.get(message.id)?.(message.result); };
53
- });
54
- let id = known ?? null;
55
- if (!id) {
56
- const extensions = (await call("Extensions.getExtensions"))?.extensions ?? [];
57
- const enabled = extensions.filter((extension) => extension.name === STAGEHAND_EXTENSION && extension.enabled);
58
- if (enabled.length !== 1)
59
- return null;
60
- id = enabled[0].id;
61
- }
62
- const workers = async () => ((await call("Target.getTargets"))?.targetInfos ?? [])
63
- .filter((target) => target.type === "service_worker" && target.url.startsWith(`chrome-extension://${id}/`))
64
- .map((target) => target.targetId);
65
- const closing = await workers();
66
- for (const targetId of closing)
67
- await call("Target.closeTarget", { targetId });
68
- // A closed worker stays listed for a moment and Stagehand would attach to it: wait until it is gone (best effort).
69
- for (let tries = 0; tries < 40 && (await workers()).some((targetId) => closing.includes(targetId)); tries += 1)
70
- await new Promise((r) => setTimeout(r, 50));
71
- return id;
72
- }
73
- catch {
74
- return known ?? null;
75
- }
76
- finally {
77
- clearTimeout(timer);
78
- signal?.removeEventListener("abort", stop);
79
- socket.close();
80
- }
81
- }
82
32
  /** Batches run under `timeoutMs`, not the facade's fixed 60 s; one failing at or past it is a `TimeoutError`, since
83
33
  * Stagehand's own is a plain Error. */
84
34
  function withBatchTimeout(stagehand, timeoutMs) {
package/dist/durable.d.ts CHANGED
@@ -4,9 +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 PageDriver, type ToolImpl } from "./core/tools.js";
7
+ import { type BrowserToolImpls, type PageDriver } from "./core/tools.js";
8
8
  import type { BrowserConfig, BrowserProvider, InventoryRow, ObserverRow, PriceTable, ReconcileReport, ReleaseReason, SessionChange, SessionRow, SessionsState, SiteInfo, SiteRunPort } from "./core/host.js";
9
- export type { PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
9
+ export type { BrowserToolArgs, BrowserToolImpls, PageDriver, ToolCall, ToolImpl } from "./core/tools.js";
10
10
  export type { DriverFactory, DriverOptions } from "./core/custody.js";
11
11
  export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
12
12
  /** Default "browser"; a second plane installs a second extension under another name. */
@@ -20,7 +20,7 @@ export type BrowserExtensionOptions<D extends PageDriver = PageDriver> = {
20
20
  }) => BrowserProvider | Promise<BrowserProvider>;
21
21
  driver: DriverFactory<D>;
22
22
  /** Implementations by contract name, over the package's own; a contract tool with no implementation is not listed. */
23
- tools?: Partial<Record<string, ToolImpl<D>>>;
23
+ tools?: Partial<BrowserToolImpls<D>>;
24
24
  evidence: EvidenceSink;
25
25
  /** Where `browser_downloads` writes files; absent, the tool is not listed. */
26
26
  workspace?: (conversationId: ConversationId) => string;
@@ -67,8 +67,12 @@ export type BrowserExtensionHandle = {
67
67
  release(conversation: Conversation, reason: ReleaseReason, context: Context): Promise<void>;
68
68
  /** At run open, after install and before resume: every open lease is reconciled with its provider. */
69
69
  reconcile(harness: Harness, isActive: (conversationId: ConversationId) => boolean, context: Context): Promise<ReconcileReport>;
70
+ /** Shutdown is release, `waitForIdle`, `drain`, close: resolves when none of this extension's release tasks is live. */
71
+ drain(harness: Harness, context: Context, signal?: AbortSignal): Promise<void>;
70
72
  /** Drop in-memory driver attachments and idle timers (process exit); never releases. */
71
73
  close(): Promise<void>;
74
+ /** How many conversations the extension still holds in-memory state for: a repeat guard, an idle timer or a queued call. */
75
+ retained(): number;
72
76
  };
73
77
  export { createWebExtension, type WebExtensionOptions } from "./web.js";
74
78
  export { CONFIRM_POLLS, RELEASE_ATTEMPTS } from "./store.js";