@parcha/pi-browser 0.1.0-beta.21 → 0.1.0-beta.26

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 (58) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +38 -7
  3. package/dist/coding-agent-local.js +7 -6
  4. package/dist/coding-agent.js +32 -28
  5. package/dist/core/clip.js +2 -2
  6. package/dist/core/contract.d.ts +7 -0
  7. package/dist/core/contract.js +3 -0
  8. package/dist/core/custody.d.ts +13 -4
  9. package/dist/core/custody.js +23 -6
  10. package/dist/core/downloads.js +2 -2
  11. package/dist/core/driving.d.ts +6 -0
  12. package/dist/core/driving.js +8 -0
  13. package/dist/core/failures.d.ts +13 -3
  14. package/dist/core/failures.js +22 -15
  15. package/dist/core/host.d.ts +6 -0
  16. package/dist/core/redact.d.ts +9 -0
  17. package/dist/core/redact.js +9 -0
  18. package/dist/core/sites.js +2 -1
  19. package/dist/core/tools.d.ts +2 -2
  20. package/dist/core/tools.js +7 -10
  21. package/dist/core/web.d.ts +1 -6
  22. package/dist/core/web.js +8 -4
  23. package/dist/driver/extension-worker.js +149 -118
  24. package/dist/driver/page-driver.d.ts +2 -1
  25. package/dist/driver/sealed.d.ts +16 -0
  26. package/dist/driver/sealed.js +47 -0
  27. package/dist/driver/stagehand.js +7 -43
  28. package/dist/durable/journal.d.ts +31 -0
  29. package/dist/durable/journal.js +105 -0
  30. package/dist/{durable-result.d.ts → durable/result.d.ts} +1 -1
  31. package/dist/{store.d.ts → durable/store.d.ts} +2 -2
  32. package/dist/{store.js → durable/store.js} +1 -1
  33. package/dist/{web.d.ts → durable/web.d.ts} +4 -4
  34. package/dist/{web.js → durable/web.js} +5 -5
  35. package/dist/durable.d.ts +2 -2
  36. package/dist/durable.js +42 -135
  37. package/dist/live-view/provider.d.ts +1 -1
  38. package/dist/live-view/provider.js +1 -1
  39. package/dist/live-view/server.d.ts +2 -2
  40. package/dist/live-view/server.js +1 -3
  41. package/dist/providers/assigned.js +2 -3
  42. package/dist/providers/browserbase-net.d.ts +0 -1
  43. package/dist/providers/browserbase-net.js +0 -1
  44. package/dist/providers/browserbase.js +5 -4
  45. package/dist/providers/cdp.js +38 -43
  46. package/dist/providers/chrome-args.d.ts +18 -0
  47. package/dist/providers/chrome-args.js +66 -0
  48. package/dist/providers/chrome-stderr.d.ts +21 -0
  49. package/dist/providers/chrome-stderr.js +108 -0
  50. package/dist/providers/http.d.ts +4 -1
  51. package/dist/providers/http.js +5 -8
  52. package/dist/providers/kernel.d.ts +10 -1
  53. package/dist/providers/kernel.js +1 -1
  54. package/dist/providers/profiles.js +6 -6
  55. package/dist/providers/shared.d.ts +9 -0
  56. package/dist/providers/shared.js +5 -1
  57. package/package.json +7 -3
  58. /package/dist/{durable-result.js → durable/result.js} +0 -0
@@ -6,6 +6,8 @@ export const FAILURE_CODES = Object.freeze([
6
6
  "session_replaced", "effect_unknown", "code_error", "command_failed", "not_content", "blocked", "rate_limited", "waiting_for_human",
7
7
  ]);
8
8
  export const browserFailure = (code, message, options = {}) => ({ ok: false, code, retryable: options.retryable ?? false, effect: options.effect ?? "none", message, ...(options.detail === undefined ? {} : { detail: options.detail }) });
9
+ /** The vendored facade's refusal texts (vendor/stagehand-facade/contract.ts), copied so the root entry does not load the facade; a test pins
10
+ * them to the facade's own. */
9
11
  export const NO_HYDRATED_SNAPSHOT_ERROR = "No hydrated snapshot exists for the active page; call snapshot first.";
10
12
  export const NAVIGATED_SNAPSHOT_ERROR = "The active page navigated after its snapshot; call snapshot again.";
11
13
  export const STALE_SNAPSHOT_ID_ERROR = 'Snapshot ID "${id}" is stale or not actionable; call snapshot again.';
@@ -16,9 +18,11 @@ const isStaleSnapshot = (message) => message === NO_HYDRATED_SNAPSHOT_ERROR || m
16
18
  * host rethrows it with the extension's JSON-RPC internal error (-32603) as the cause. The driver is gone, not the session. */
17
19
  export const STAGEHAND_LOOPBACK_DISCONNECTED = "Stagehand loopback CDP is disconnected";
18
20
  const JSONRPC_INTERNAL_ERROR = -32603;
21
+ /** A property of a thrown value when it is an object: errors carry facts (a cause, a code, a status) no type declares. */
22
+ const field = (value, key) => (value !== null && typeof value === "object" ? value[key] : undefined);
19
23
  const lostLoopback = (error) => {
20
- const cause = error?.cause;
21
- return !!cause && typeof cause === "object" && cause.code === JSONRPC_INTERNAL_ERROR && cause.message === STAGEHAND_LOOPBACK_DISCONNECTED;
24
+ const cause = field(error, "cause");
25
+ return field(cause, "code") === JSONRPC_INTERNAL_ERROR && field(cause, "message") === STAGEHAND_LOOPBACK_DISCONNECTED;
22
26
  };
23
27
  const UNREACHABLE_CAUSES = new Set(["ECONNREFUSED", "ENOTFOUND", "ECONNRESET", "EAI_AGAIN", "EPIPE", "UND_ERR_SOCKET", "UND_ERR_CONNECT_TIMEOUT"]);
24
28
  // A host call the browser left unanswered past its deadline is a dropped connection too.
@@ -26,20 +30,21 @@ const UNREACHABLE_NAMES = new Set(["CDPConnectionClosedError", UNANSWERED_CALL])
26
30
  /** A throw site's `transport` record, else class name, `code` and `status` down the cause chain; first found wins. */
27
31
  export function transportFactOf(error) {
28
32
  const out = {};
29
- let current = error;
30
- for (let depth = 0; current && typeof current === "object" && depth < 6; depth += 1, current = current.cause) {
31
- const attached = current.transport;
33
+ const found = out;
34
+ for (let depth = 0, current = error; current && typeof current === "object" && depth < 6; depth += 1, current = field(current, "cause")) {
35
+ const attached = field(current, "transport");
32
36
  if (attached && typeof attached === "object") {
33
37
  for (const [key, value] of Object.entries(attached))
34
- if (value !== undefined && out[key] === undefined)
35
- out[key] = value;
38
+ if (value !== undefined && found[key] === undefined)
39
+ found[key] = value;
36
40
  }
37
- if (out.errorName === undefined && typeof current.name === "string" && current.name !== "Error")
38
- out.errorName = current.name;
39
- if (out.causeCode === undefined && typeof current.code === "string" && current.code)
40
- out.causeCode = current.code;
41
- if (out.status === undefined && Number.isInteger(current.status))
42
- out.status = current.status;
41
+ const name = field(current, "name"), code = field(current, "code"), status = field(current, "status");
42
+ if (out.errorName === undefined && typeof name === "string" && name !== "Error")
43
+ out.errorName = name;
44
+ if (out.causeCode === undefined && typeof code === "string" && code)
45
+ out.causeCode = code;
46
+ if (out.status === undefined && typeof status === "number" && Number.isInteger(status))
47
+ out.status = status;
43
48
  }
44
49
  return out;
45
50
  }
@@ -59,11 +64,11 @@ function withCause(own, cause) {
59
64
  }
60
65
  export function classifyBrowserError(error, effectful, facts = {}) {
61
66
  // Stagehand wraps SDK failures with { cause }: the HTTP status and the real message live on the cause.
62
- const cause = error?.cause;
67
+ const cause = field(error, "cause");
63
68
  const own = error instanceof Error ? error.message : String(error);
64
69
  const message = (facts.redact ?? ((text) => text))(withCause(own, cause));
65
70
  const fact = transportFactOf(error);
66
- const status = fact.status ?? Number(error?.statusCode ?? cause?.statusCode ?? NaN);
71
+ const status = fact.status ?? Number(field(error, "statusCode") ?? field(cause, "statusCode") ?? NaN);
67
72
  const effect = effectful ? "possibly_effected" : "none";
68
73
  const detail = message.slice(0, 2_000);
69
74
  if (facts.aborted || fact.errorName === "AbortError")
@@ -72,6 +77,8 @@ export function classifyBrowserError(error, effectful, facts = {}) {
72
77
  return browserFailure("auth", "The browser provider refused the credential (401). The browser plane is unavailable for this run; use fetch (executor tools).", { detail });
73
78
  if (status === 403)
74
79
  return browserFailure("auth", "The browser provider refused this session type (403). Retry without `verified`, or use web_fetch.", { detail });
80
+ if (status === 429)
81
+ return browserFailure("rate_limited", `The browser provider is rate limiting this run (429). ${effectful ? "Your call may have acted: take a snapshot before you act again." : "Wait a moment, then try again."}`, { retryable: !effectful, effect, detail });
75
82
  if (facts.sessionEnded)
76
83
  return browserFailure("session_ended", "The browser session ended (the provider closed it at its timeout, or the browser died). Your next browser call opens a fresh session automatically; the old tabs, page state and cookies are gone — navigate to the page again with run, then continue from there.", { retryable: true, effect, detail });
77
84
  if (facts.timedOut || fact.errorName === "TimeoutError")
@@ -99,6 +99,9 @@ export type ProviderCaps = {
99
99
  settings?: Partial<SessionSettingsSupport>;
100
100
  /** The host assigned the run this one session: there is no other to relaunch onto. */
101
101
  fixedSession?: boolean;
102
+ /** The provider enforces a navigation policy's `allow` list (only the listed sites load). A provider without it cannot apply an
103
+ * allow list, and a session under one is refused. */
104
+ navigationAllow?: boolean;
102
105
  };
103
106
  export type SessionSettingsSupport = {
104
107
  proxies: boolean;
@@ -250,6 +253,8 @@ export type SessionRecord = {
250
253
  releaseReason: ReleaseReason | null;
251
254
  plane: string;
252
255
  provider: string;
256
+ /** `navigationAllow`: the allow list the provider applied when it created the session, which it never changes afterwards.
257
+ * Absent: none was applied. */
253
258
  settings: {
254
259
  proxies: boolean;
255
260
  verified: boolean;
@@ -257,6 +262,7 @@ export type SessionRecord = {
257
262
  region: string | null;
258
263
  contextId: string | null;
259
264
  profile: string | null;
265
+ navigationAllow?: string[];
260
266
  };
261
267
  /** Every page the session moved to, in order; the last 500 kept. */
262
268
  navigation: Array<{
@@ -1,3 +1,4 @@
1
+ import type { LiveView } from "./host.js";
1
2
  export type Redact = (text: string) => string;
2
3
  /** Scrubbing a shorter string everywhere would destroy the text around it, and no credential is that short. */
3
4
  export declare const MIN_REDACTED_VALUE_LENGTH = 8;
@@ -7,6 +8,14 @@ export declare function createRedactor(values?: () => readonly string[]): Redact
7
8
  /** A credential can sit in any query value, the fragment or the userinfo, so every query value is replaced (names stay)
8
9
  * and the fragment and userinfo are dropped before `redact` runs. A non-http(s) URL is only redacted. */
9
10
  export declare function scrubPageUrl(raw: string, redact: Redact): string;
11
+ /** A tool result's content as the model is shown it: every text passes the redactor; an image is left as it is. */
12
+ export declare function redactContent<T extends {
13
+ type: string;
14
+ text?: string;
15
+ }>(content: readonly T[], redact: Redact): T[];
16
+ /** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
17
+ * whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
18
+ export declare function hostLiveView(view: LiveView, redact: Redact): LiveView;
10
19
  /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
11
20
  export declare function scrubFetchedUrl(raw: string, requested: string, redact: Redact): string;
12
21
  /** Every string inside `value`, object keys included, passed through `redact`. */
@@ -38,6 +38,15 @@ export function scrubPageUrl(raw, redact) {
38
38
  const names = [...new Set(url.searchParams.keys())];
39
39
  return redact(`${url.origin}${url.pathname}${names.length ? `?${names.map((n) => `${encodeURIComponent(n)}=${REDACTED}`).join("&")}` : ""}`);
40
40
  }
41
+ /** A tool result's content as the model is shown it: every text passes the redactor; an image is left as it is. */
42
+ export function redactContent(content, redact) {
43
+ return content.map((item) => (item.type === "text" && typeof item.text === "string" ? { ...item, text: redact(item.text) } : item));
44
+ }
45
+ /** A live view as the host receives it, on every channel (`onSession`, a handoff's `request`): the viewer's own URLs stay
46
+ * whole, since the host needs their token; a browsed page's URL and title are scrubbed, since its query can carry a credential. */
47
+ export function hostLiveView(view, redact) {
48
+ return { ...view, pages: view.pages.map((page) => ({ ...page, url: page.url === null ? null : scrubPageUrl(page.url, redact), title: page.title === null ? null : redact(page.title) })) };
49
+ }
41
50
  /** A fetch's final URL for the model: a query value or fragment stays only where the requested URL has it; userinfo never does. */
42
51
  export function scrubFetchedUrl(raw, requested, redact) {
43
52
  let url, asked;
@@ -1,3 +1,4 @@
1
+ import { browserFailure } from "./failures.js";
1
2
  export const MAX_SITE_INSTRUCTIONS = 16_000;
2
3
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3
4
  const RUN_ID = /^[A-Za-z0-9_.:-]{1,200}$/;
@@ -39,7 +40,7 @@ export function siteAnswer(raw) {
39
40
  return typeof id === "string" && RUN_ID.test(id) && typeof state === "string" && RUN_STATE.test(state) ? { run: { id, state } } : null;
40
41
  }
41
42
  const siteOutput = (body, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(body) }], ...(isError ? { isError: true } : {}) });
42
- const siteRefusal = (message) => siteOutput({ ok: false, code: "refused", retryable: false, effect: "none", message }, true);
43
+ const siteRefusal = (message) => siteOutput(browserFailure("refused", message), true);
43
44
  export async function useWebsite(args, port, sites, ctx) {
44
45
  const site = sites.find((known) => known.site === args.site);
45
46
  if (!site)
@@ -129,10 +129,10 @@ type ReconnectTimings = {
129
129
  tryMs: number;
130
130
  backoffMs: readonly number[];
131
131
  };
132
- /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
133
- /** `reconnect`: the reconnect timings, for tests; hosts keep the defaults. */
134
132
  export declare function pageTools({ guards, reconnect: timings }?: {
133
+ /** Each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
135
134
  guards?: Map<number, RepeatGuard>;
135
+ /** The reconnect timings, for tests; hosts keep the defaults. */
136
136
  reconnect?: ReconnectTimings;
137
137
  }): Pick<BrowserToolImpls<PageDriver>, "snapshot" | "run" | "screenshot" | "browser_read" | "browser_upload" | "browser_downloads">;
138
138
  export {};
@@ -1,4 +1,4 @@
1
- import { BrowserFailureError, FenceRefusal, loadedNoPage, passedThrough } from "./custody.js";
1
+ import { BrowserFailureError, FenceRefusal, refusedError, loadedNoPage, passedThrough } from "./custody.js";
2
2
  import { defaultInline } from "./evidence.js";
3
3
  import { fetchDownloads } from "./downloads.js";
4
4
  import { browserFailure, classifyBrowserError, transportFactOf } from "./failures.js";
@@ -26,7 +26,6 @@ const pause = (ms, signal) => new Promise((resolve) => {
26
26
  });
27
27
  const text = (value, isError = false) => ({ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value) }], ...(isError ? { isError: true } : {}) });
28
28
  const withNews = (news, body) => (news ? `${news}\n\n${body}` : body);
29
- const refused = (message) => ({ ok: false, code: "refused", retryable: false, effect: "none", message });
30
29
  /** A read of a browser that has loaded no page yet: it is fresh, and the next step is to navigate, to the replaced
31
30
  * session's last page when there is one. */
32
31
  function freshBrowser(replaced) {
@@ -140,8 +139,6 @@ async function markdown(html, fallback) {
140
139
  catch { }
141
140
  return { body: fallback, extractor: "inner-text", ext: "txt" };
142
141
  }
143
- /** `guards` holds each conversation's repeat guard; a host that owns the conversation's lifecycle passes it to evict one. */
144
- /** `reconnect`: the reconnect timings, for tests; hosts keep the defaults. */
145
142
  export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT } = {}) {
146
143
  const guardOf = (conversationId, redact) => guards.get(conversationId) ?? guards.set(conversationId, createRepeatGuard(redact)).get(conversationId);
147
144
  async function failureOf(error, effectful, port, call, action) {
@@ -406,19 +403,19 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT }
406
403
  const asked = typeof args?.path === "string" ? args.path : "";
407
404
  const selector = typeof args?.selector === "string" ? args.selector.trim() : "";
408
405
  if (!call.files)
409
- return text(refused("This host gives the browser no workspace to upload from."), true);
406
+ return text(browserFailure("refused", "This host gives the browser no workspace to upload from."), true);
410
407
  if (!selector)
411
- return text(refused("selector must name the page's file input."), true);
408
+ return text(browserFailure("refused", "selector must name the page's file input."), true);
412
409
  // The host resolves the path before any browser call, so a refused file never reaches the page.
413
410
  const file = await call.files.resolve(asked);
414
411
  if ("refused" in file)
415
- return text(refused(`browser_upload refused the file: ${file.refused}.`), true);
412
+ return text(browserFailure("refused", `browser_upload refused the file: ${file.refused}.`), true);
416
413
  const uploaded = { name: file.name, bytes: file.bytes.byteLength, sha256: sha256Hex(file.bytes) };
417
414
  const codeSha = sha256Hex(JSON.stringify({ upload: selector, sha256: uploaded.sha256 }));
418
415
  // A page can send the file once its input changes: an upload is journaled like a run and never repeated.
419
416
  return perform("browser_upload", { path: asked, selector }, port, call, { effect: codeSha }, async (s, news) => {
420
417
  if (!s.driver.setInputFiles)
421
- throw new BrowserFailureError(refused("This browser driver cannot set a file input."));
418
+ throw refusedError("This browser driver cannot set a file input.");
422
419
  const sent = [];
423
420
  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); });
424
421
  try {
@@ -433,9 +430,9 @@ export function pageTools({ guards = new Map(), reconnect: timings = RECONNECT }
433
430
  },
434
431
  browser_downloads: (args, port, call) => perform("browser_downloads", {}, port, call, "read", async (s, news) => {
435
432
  if (!call.workspace)
436
- throw new BrowserFailureError(refused("This host gives the browser no workspace to copy downloads into."));
433
+ throw refusedError("This host gives the browser no workspace to copy downloads into.");
437
434
  if (!s.downloads)
438
- throw new BrowserFailureError(refused("This browser provider cannot list the files its sessions download."));
435
+ throw refusedError("This browser provider cannot list the files its sessions download.");
439
436
  const result = await fetchDownloads({ provider: { downloads: s.downloads }, ref: { id: s.sessionId, tag: s.tag }, session: s.sessionId, workspace: call.workspace, redact: call.redact });
440
437
  return { content: [{ type: "text", text: JSON.stringify({ ok: true, ...result, ...(news ? { notice: news } : {}) }) }], details: { downloads: result } };
441
438
  }),
@@ -1,6 +1,6 @@
1
1
  import type { Decisions, PageVerdict, WallClass } from "./decisions.js";
2
2
  import { type EvidenceSink } from "./evidence.js";
3
- import { type BrowserFailure } from "./failures.js";
3
+ import { type BrowserFailure, type Next } from "./failures.js";
4
4
  import { type FetchRequest, type FetchResult, type PriceTable, type SearchRequest, type SearchResult } from "./host.js";
5
5
  export declare const WEB_SEARCH_QUERY_MAX = 200;
6
6
  export declare const WEB_SEARCH_RESULTS_MAX = 25;
@@ -62,13 +62,8 @@ export type WebToolsOptions = {
62
62
  timeoutMs?: number;
63
63
  };
64
64
  };
65
- export type Next = {
66
- action: "drive_page" | "other_source" | "browser_relaunch";
67
- note: string;
68
- };
69
65
  export type WebFailure = BrowserFailure & {
70
66
  wall?: WallClass;
71
- next?: Next;
72
67
  };
73
68
  export type WebOutcome = {
74
69
  text: string;
package/dist/core/web.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { BrowserFailureError } from "./custody.js";
2
3
  import { defaultInline } from "./evidence.js";
3
- import { classifyBrowserError, transportFactOf } from "./failures.js";
4
+ import { browserFailure, classifyBrowserError, transportFactOf } from "./failures.js";
4
5
  import { createRepeatGuard } from "./guard.js";
5
6
  import { LIST_PRICES } from "./host.js";
6
7
  import { createRedactor, scrubFetchedUrl, scrubPageUrl } from "./redact.js";
@@ -77,6 +78,9 @@ export function createWebTools(options) {
77
78
  const guardOf = (conversation) => guards.get(conversation) ?? guards.set(conversation, createRepeatGuard(redact)).get(conversation);
78
79
  const fail = (failure) => ({ text: JSON.stringify(failure, (_k, v) => (typeof v === "string" ? redact(v) : v)), isError: true, details: { code: failure.code }, usd: 0 });
79
80
  const failureOf = (error, tool, signal) => {
81
+ // A typed failure (a backup that refuses a private host, a non-text page or one over its size) is told as it is.
82
+ if (error instanceof BrowserFailureError && !signal?.aborted)
83
+ return error.failure;
80
84
  const base = classifyBrowserError(error, false, { aborted: signal?.aborted === true, redact });
81
85
  const status = transportFactOf(error).status;
82
86
  if (base.code === "aborted")
@@ -118,7 +122,7 @@ export function createWebTools(options) {
118
122
  }
119
123
  catch { }
120
124
  if (!parsed || !/^https?:$/.test(parsed.protocol) || parsed.username || parsed.password)
121
- return fail({ ok: false, code: "refused", retryable: false, effect: "none", message: "web_fetch needs an absolute http(s) URL with no credentials in it." });
125
+ return fail(browserFailure("refused", "web_fetch needs an absolute http(s) URL with no credentials in it."));
122
126
  let usd = 0;
123
127
  let guardLine;
124
128
  const file = async (record, body) => options.evidence.file(label, { tool: "web_fetch", ...record, facts: { requested_url: redact(url), sha256: sha256(body), ...record.facts, ...(guardLine ? { page_guard: guardLine } : {}) }, body }).catch(() => null);
@@ -265,7 +269,7 @@ export function createWebTools(options) {
265
269
  }
266
270
  if (signal?.aborted || primary?.code === "aborted")
267
271
  return { ...fail(ABORTED), usd };
268
- const base = primary ?? { ok: false, code: "refused", retryable: false, effect: "none", message: "No source can fetch pages in this run." };
272
+ const base = primary ?? browserFailure("refused", "No source can fetch pages in this run.");
269
273
  const others = tried.filter((name) => name !== primaryVia);
270
274
  const final = { ...base, message: `${base.message}${others.length ? ` Also tried: ${others.join(", ")}.` : ""}${base.next ? "" : " Drive the page with run and snapshot in a live session, or try a different URL."}` };
271
275
  await file({ args: { url: redact(url), via: primaryVia }, status: "failed", facts: { via: primaryVia } }, redact(`${final.message}\n${final.detail ?? ""}`));
@@ -281,7 +285,7 @@ export function createWebTools(options) {
281
285
  if (refused)
282
286
  return fail(refused);
283
287
  if (!query || !options.search)
284
- return fail({ ok: false, code: "refused", retryable: false, effect: "none", message: query ? "No search provider is configured for this run." : "web_search needs a query." });
288
+ return fail(browserFailure("refused", query ? "No search provider is configured for this run." : "web_search needs a query."));
285
289
  try {
286
290
  const { results } = await options.search({ query, n }, signal);
287
291
  guard.note("web_search", guardArgs, null);
@@ -10,6 +10,143 @@ const RESET_ID = 2_147_000_000;
10
10
  class TargetsUnlistedError extends Error {
11
11
  constructor() { super(`the browser did not list its targets within ${DISCOVERY_MS} ms, so a Stagehand runtime it may hold could not be freed`); }
12
12
  }
13
+ /** One attach's CDP socket, open for `lifeMs` at most and closed at once on an abort. A call settles empty when the
14
+ * browser does not answer within `ms` (the deadline, unless shorter), and every call settles empty once the socket
15
+ * closes (an abort, the browser, the end of its life). */
16
+ class Cdp {
17
+ deadline;
18
+ signal;
19
+ /** Settles when the socket opens; rejects when it fails to open or closes first. */
20
+ opened;
21
+ socket;
22
+ timer;
23
+ stop = () => this.socket.close();
24
+ pending = new Map();
25
+ listeners = new Set();
26
+ next = 0;
27
+ isClosed = false;
28
+ constructor(cdpUrl, deadline, lifeMs, signal) {
29
+ this.deadline = deadline;
30
+ this.signal = signal;
31
+ this.socket = new WebSocket(cdpUrl);
32
+ this.timer = setTimeout(() => this.socket.close(), lifeMs);
33
+ signal?.addEventListener("abort", this.stop, { once: true });
34
+ this.opened = new Promise((resolve, reject) => {
35
+ this.socket.onopen = () => resolve();
36
+ // A refused connection raises `error` and, on Node 22, never `close`: waiting for `close` alone would hang the attach.
37
+ this.socket.onerror = () => reject(new Error("Failed to open CDP WebSocket"));
38
+ this.socket.onclose = () => { this.onClose(); reject(new Error("the CDP socket closed")); };
39
+ this.socket.onmessage = (event) => this.onMessage(event.data);
40
+ });
41
+ }
42
+ /** A send on a closed socket neither throws nor is ever answered (Node 24): once closed, every call settles empty. */
43
+ call(method, params = {}, sessionId, ms = this.deadline - Date.now()) {
44
+ return new Promise((resolve) => {
45
+ if (this.isClosed || this.socket.readyState !== WebSocket.OPEN || ms <= 0)
46
+ return resolve(undefined);
47
+ const id = ++this.next;
48
+ const settle = (result) => { clearTimeout(wait); this.pending.delete(id); resolve(result); };
49
+ const wait = setTimeout(() => settle(undefined), ms);
50
+ this.pending.set(id, settle);
51
+ this.socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
52
+ });
53
+ }
54
+ listen(listener) { this.listeners.add(listener); }
55
+ closed() { return this.isClosed; }
56
+ end() { clearTimeout(this.timer); this.signal?.removeEventListener("abort", this.stop); this.socket.close(); }
57
+ onClose() {
58
+ this.isClosed = true;
59
+ for (const settle of [...this.pending.values()])
60
+ settle(undefined);
61
+ for (const listener of this.listeners)
62
+ listener({ method: "closed" });
63
+ }
64
+ /** A throw in a socket listener ends the process: a frame that is not JSON is dropped. */
65
+ onMessage(data) {
66
+ try {
67
+ const message = JSON.parse(String(data));
68
+ if (message?.id !== undefined)
69
+ this.pending.get(message.id)?.(message.result);
70
+ else if (message)
71
+ for (const listener of this.listeners)
72
+ listener(message);
73
+ }
74
+ catch { }
75
+ }
76
+ }
77
+ /** The one enabled Stagehand extension's id; null when there is none, or more than one. */
78
+ async function stagehandExtensionId(cdp) {
79
+ const extensions = (await cdp.call("Extensions.getExtensions"))?.extensions ?? [];
80
+ const enabled = extensions.filter((extension) => extension.name === STAGEHAND_EXTENSION && extension.enabled);
81
+ return enabled.length === 1 ? enabled[0].id : null;
82
+ }
83
+ /** The extension's workers; null when the browser gave no list, which is not a list without one. */
84
+ async function extensionWorkers(cdp, id) {
85
+ const infos = (await cdp.call("Target.getTargets"))?.targetInfos;
86
+ return infos?.filter((target) => target.type === "service_worker" && target.url.startsWith(`chrome-extension://${id}/`)).map((target) => target.targetId) ?? null;
87
+ }
88
+ /** With no worker running nothing is held, and the worker is woken until it is listed. Every wake page opened stays
89
+ * listed here until a close of it is answered. None is opened within CLEANUP_MS of the deadline, an opening's reply is
90
+ * awaited into the first half of that second, and the socket outlives the deadline by CLEANUP_MS, so the last pages are
91
+ * closed on it. */
92
+ async function wakeWorker(cdp, id, deadline) {
93
+ const wakes = new Set();
94
+ const closeWakes = async (ms) => { for (const page of [...wakes])
95
+ if ((await cdp.call("Target.closeTarget", { targetId: page }, undefined, ms)) !== undefined)
96
+ wakes.delete(page); };
97
+ for (let tries = 0; !cdp.closed() && Date.now() < deadline && tries < WAKE_TRIES && ((await extensionWorkers(cdp, id))?.length ?? 0) === 0; tries += 1) {
98
+ if (tries % 10 === 0 && deadline - Date.now() > CLEANUP_MS) {
99
+ await closeWakes();
100
+ const page = (await cdp.call("Target.createTarget", { url: `chrome-extension://${id}/wake-service-worker.html` }, undefined, deadline + CLEANUP_MS / 2 - Date.now()))?.targetId;
101
+ if (page)
102
+ wakes.add(page);
103
+ }
104
+ await new Promise((r) => setTimeout(r, 100));
105
+ }
106
+ await closeWakes(deadline + CLEANUP_MS - Date.now());
107
+ }
108
+ /** A binding call on `sessionId` that carries the reply to the close (its id is RESET_ID). */
109
+ function isResetReply(event, sessionId) {
110
+ if (event.method !== "Runtime.bindingCalled" || event.sessionId !== sessionId || event.params?.name !== SEND_TO_HOST)
111
+ return false;
112
+ try {
113
+ return JSON.parse(event.params.payload ?? "")?.id === RESET_ID;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ /** Settles on the runtime's reply to the close, at once when the socket closes, and after `replyMs` at most. */
120
+ function resetReplied(cdp, sessionId, replyMs) {
121
+ return new Promise((resolve) => {
122
+ const wait = setTimeout(resolve, replyMs);
123
+ cdp.listen((event) => {
124
+ if (event.method === "closed" || isResetReply(event, sessionId)) {
125
+ clearTimeout(wait);
126
+ resolve();
127
+ }
128
+ });
129
+ });
130
+ }
131
+ /** The held runtime's close, sent through the worker's own RPC, and its reply awaited for up to `replyMs`; the worker
132
+ * keeps running. */
133
+ async function closeHeldRuntime(cdp, worker, replyMs) {
134
+ const sessionId = (await cdp.call("Target.attachToTarget", { targetId: worker, flatten: true }))?.sessionId;
135
+ if (!sessionId)
136
+ return;
137
+ try {
138
+ await cdp.call("Runtime.enable", {}, sessionId);
139
+ await cdp.call("Runtime.addBinding", { name: SEND_TO_HOST }, sessionId);
140
+ const replied = resetReplied(cdp, sessionId, replyMs);
141
+ const close = JSON.stringify({ jsonrpc: "2.0", id: RESET_ID, method: "stagehand.close", params: {} });
142
+ const sent = await cdp.call("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost(${JSON.stringify(close)}); true`, returnByValue: true }, sessionId);
143
+ if (sent && !sent.exceptionDetails)
144
+ await replied;
145
+ }
146
+ finally {
147
+ await cdp.call("Target.detachFromTarget", { sessionId });
148
+ }
149
+ }
13
150
  /** A held extension runtime keeps one Stagehand instance until that instance's close, which a dead process never sent,
14
151
  * so a new attach would be refused. The close is sent here through the worker's own RPC, and the worker keeps running:
15
152
  * a worker closed under load is sometimes never restarted, and its attach waits out Stagehand's 60 s init deadline.
@@ -18,127 +155,23 @@ class TargetsUnlistedError extends Error {
18
155
  * runtime's reply. An init still running in the extension answers it only once that init ends, since the runtime runs
19
156
  * both one after the other; the socket outlives the deadline by that much more. */
20
157
  export async function installedExtension(cdpUrl, signal, known, replyMs = CLOSE_REPLY_MS) {
21
- const socket = new WebSocket(cdpUrl);
22
158
  const deadline = Date.now() + DISCOVERY_MS;
23
- const timer = setTimeout(() => socket.close(), DISCOVERY_MS + CLEANUP_MS - CLOSE_REPLY_MS + replyMs);
24
- const stop = () => socket.close();
25
- signal?.addEventListener("abort", stop, { once: true });
26
- // A call the browser does not answer within `ms` (the deadline, unless shorter) settles empty, as does every call once
27
- // the socket closes (an abort, the browser).
28
- const pending = new Map();
29
- const listeners = new Set();
30
- let next = 0;
31
- let closed = false;
32
- // A send on a closed socket neither throws nor is ever answered (Node 24): once closed, every call settles empty.
33
- const call = (method, params = {}, sessionId, ms = deadline - Date.now()) => new Promise((resolve) => {
34
- if (closed || socket.readyState !== WebSocket.OPEN || ms <= 0)
35
- return resolve(undefined);
36
- const id = ++next;
37
- const settle = (result) => { clearTimeout(wait); pending.delete(id); resolve(result); };
38
- const wait = setTimeout(() => settle(undefined), ms);
39
- pending.set(id, settle);
40
- socket.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
41
- });
159
+ const cdp = new Cdp(cdpUrl, deadline, DISCOVERY_MS + CLEANUP_MS - CLOSE_REPLY_MS + replyMs, signal);
42
160
  try {
43
- await new Promise((resolve, reject) => {
44
- socket.onopen = () => resolve();
45
- // A refused connection raises `error` and, on Node 22, never `close`: waiting for `close` alone would hang the
46
- // attach.
47
- socket.onerror = () => reject(new Error("Failed to open CDP WebSocket"));
48
- socket.onclose = () => {
49
- closed = true;
50
- for (const settle of [...pending.values()])
51
- settle(undefined);
52
- for (const listener of listeners)
53
- listener({ method: "closed" });
54
- reject(new Error("the CDP socket closed"));
55
- };
56
- // A throw in a socket listener ends the process: a frame that is not JSON is dropped.
57
- socket.onmessage = (event) => {
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 { }
67
- };
68
- });
69
- let id = known ?? null;
70
- if (!id) {
71
- const extensions = (await call("Extensions.getExtensions"))?.extensions ?? [];
72
- const enabled = extensions.filter((extension) => extension.name === STAGEHAND_EXTENSION && extension.enabled);
73
- if (enabled.length !== 1)
74
- return null;
75
- id = enabled[0].id;
76
- }
77
- /** The extension's workers; null when the browser gave no list, which is not a list without one. */
78
- const workers = async () => {
79
- const infos = (await call("Target.getTargets"))?.targetInfos;
80
- return infos?.filter((target) => target.type === "service_worker" && target.url.startsWith(`chrome-extension://${id}/`)).map((target) => target.targetId) ?? null;
81
- };
82
- const running = await workers();
161
+ await cdp.opened;
162
+ const id = known || (await stagehandExtensionId(cdp));
163
+ if (!id)
164
+ return null;
165
+ const running = await extensionWorkers(cdp, id);
83
166
  if (running === null) {
84
- if (signal?.aborted || closed)
167
+ if (signal?.aborted || cdp.closed())
85
168
  return id;
86
169
  throw new TargetsUnlistedError();
87
170
  }
88
- if (running.length === 0) {
89
- // Every wake page opened stays listed here until a close of it is answered. None is opened within CLEANUP_MS of the
90
- // deadline, an opening's reply is awaited into the first half of that second, and the socket outlives the deadline
91
- // by CLEANUP_MS, so the last pages are closed on it.
92
- const wakes = new Set();
93
- const closeWakes = async (ms) => { for (const page of [...wakes])
94
- if ((await call("Target.closeTarget", { targetId: page }, undefined, ms)) !== undefined)
95
- wakes.delete(page); };
96
- for (let tries = 0; !closed && Date.now() < deadline && tries < WAKE_TRIES && ((await workers())?.length ?? 0) === 0; tries += 1) {
97
- if (tries % 10 === 0 && deadline - Date.now() > CLEANUP_MS) {
98
- await closeWakes();
99
- const page = (await call("Target.createTarget", { url: `chrome-extension://${id}/wake-service-worker.html` }, undefined, deadline + CLEANUP_MS / 2 - Date.now()))?.targetId;
100
- if (page)
101
- wakes.add(page);
102
- }
103
- await new Promise((r) => setTimeout(r, 100));
104
- }
105
- await closeWakes(deadline + CLEANUP_MS - Date.now());
106
- return id;
107
- }
108
- const sessionId = (await call("Target.attachToTarget", { targetId: running[0], flatten: true }))?.sessionId;
109
- if (!sessionId)
110
- return id;
111
- try {
112
- await call("Runtime.enable", {}, sessionId);
113
- await call("Runtime.addBinding", { name: SEND_TO_HOST }, sessionId);
114
- const replied = new Promise((resolve) => {
115
- const wait = setTimeout(resolve, replyMs);
116
- listeners.add((event) => {
117
- if (event.method === "closed") {
118
- clearTimeout(wait);
119
- return resolve();
120
- }
121
- if (event.method !== "Runtime.bindingCalled" || event.sessionId !== sessionId || event.params?.name !== SEND_TO_HOST)
122
- return;
123
- let reply = null;
124
- try {
125
- reply = JSON.parse(event.params.payload);
126
- }
127
- catch { }
128
- if (reply?.id === RESET_ID) {
129
- clearTimeout(wait);
130
- resolve();
131
- }
132
- });
133
- });
134
- const close = JSON.stringify({ jsonrpc: "2.0", id: RESET_ID, method: "stagehand.close", params: {} });
135
- const sent = await call("Runtime.evaluate", { expression: `void globalThis.__stagehandReceiveFromHost(${JSON.stringify(close)}); true`, returnByValue: true }, sessionId);
136
- if (sent && !sent.exceptionDetails)
137
- await replied;
138
- }
139
- finally {
140
- await call("Target.detachFromTarget", { sessionId });
141
- }
171
+ if (running.length === 0)
172
+ await wakeWorker(cdp, id, deadline);
173
+ else
174
+ await closeHeldRuntime(cdp, running[0], replyMs);
142
175
  return id;
143
176
  }
144
177
  catch (error) {
@@ -147,8 +180,6 @@ export async function installedExtension(cdpUrl, signal, known, replyMs = CLOSE_
147
180
  return known ?? null;
148
181
  }
149
182
  finally {
150
- clearTimeout(timer);
151
- signal?.removeEventListener("abort", stop);
152
- socket.close();
183
+ cdp.end();
153
184
  }
154
185
  }
@@ -1,6 +1,7 @@
1
+ import type { Stagehand } from "@browserbasehq/stagehand";
1
2
  import type { PageDriver } from "../core/tools.js";
2
3
  /** `batchMs` bounds every run batch; the page calls' own deadlines are fixed but for tests. */
3
- export declare function pageDriver(stagehand: any, deadlines: {
4
+ export declare function pageDriver(stagehand: Stagehand, deadlines: {
4
5
  batchMs: number;
5
6
  snapshotMs?: number;
6
7
  screenshotMs?: number;
@@ -0,0 +1,16 @@
1
+ /** What Stagehand's extension answers an init while another is still running in it. */
2
+ export declare const INIT_IN_PROGRESS = "Stagehand initialization is already in progress";
3
+ /** Stagehand's own init deadline: an init the extension is still running has ended by then. */
4
+ export declare const IN_FLIGHT_INIT_MS = 60000;
5
+ /** The extension refused an init because another is still running in it (its JSON-RPC error, as Stagehand's cause). */
6
+ export declare const initInProgress: (error: unknown) => boolean;
7
+ /** A failed attach step names where it went: Stagehand reports a failed open as "[object Object]", and the socket's error
8
+ * has no address. */
9
+ export declare const attachStep: (host: string) => <T>(step: Promise<T>) => Promise<T>;
10
+ /** A cancelled call never starts an init of its own, however the wait ended. */
11
+ export declare function throwIfCancelled(signal?: AbortSignal): void;
12
+ /** The sealed Stagehand, created once more when the extension is still running an earlier attach's init: an attach that
13
+ * gave up (a dropped connection, a deadline) left its init running there, and `waitForThatInit` (a close, which queues
14
+ * behind that init, so its reply means the init has ended) waits it out first. A second refusal is the browser still
15
+ * busy, retryable. */
16
+ export declare function createSealed<S>(create: () => Promise<S>, waitForThatInit: () => Promise<unknown>, host: string, signal?: AbortSignal): Promise<S>;