@parcha/pi-browser 0.1.0-beta.31 → 0.1.0-beta.310

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 (125) hide show
  1. package/CHANGELOG.md +232 -0
  2. package/NOTICE +39 -4
  3. package/README.md +122 -236
  4. package/dist/core/contract.d.ts +9 -6
  5. package/dist/core/contract.js +27 -36
  6. package/dist/core/custody.d.ts +19 -2
  7. package/dist/core/custody.js +28 -6
  8. package/dist/core/downloads.d.ts +44 -3
  9. package/dist/core/downloads.js +94 -58
  10. package/dist/core/driving-guard.d.ts +20 -0
  11. package/dist/core/driving-guard.js +190 -23
  12. package/dist/core/driving.d.ts +56 -2
  13. package/dist/core/driving.js +189 -10
  14. package/dist/core/effects.d.ts +80 -6
  15. package/dist/core/effects.js +374 -41
  16. package/dist/core/evidence.d.ts +1 -1
  17. package/dist/core/failures.d.ts +15 -1
  18. package/dist/core/failures.js +7 -0
  19. package/dist/core/files.d.ts +20 -2
  20. package/dist/core/files.js +161 -10
  21. package/dist/core/host.d.ts +29 -77
  22. package/dist/core/images.d.ts +32 -4
  23. package/dist/core/images.js +81 -16
  24. package/dist/core/lease.d.ts +2 -1
  25. package/dist/core/page-scan.d.ts +81 -2
  26. package/dist/core/page-scan.js +487 -13
  27. package/dist/core/public-fetch.d.ts +70 -9
  28. package/dist/core/public-fetch.js +348 -51
  29. package/dist/core/read-page-worker.js +5 -4
  30. package/dist/core/read-page.d.ts +23 -8
  31. package/dist/core/read-page.js +64 -20
  32. package/dist/core/redact.d.ts +0 -2
  33. package/dist/core/redact.js +0 -32
  34. package/dist/core/session-control.d.ts +0 -2
  35. package/dist/core/session-control.js +0 -5
  36. package/dist/core/tools.d.ts +46 -1
  37. package/dist/core/tools.js +88 -12
  38. package/dist/core/usage.d.ts +4 -3
  39. package/dist/core/usage.js +5 -4
  40. package/dist/core/vault.d.ts +0 -10
  41. package/dist/core/vault.js +0 -13
  42. package/dist/core/web.d.ts +2 -111
  43. package/dist/core/web.js +0 -443
  44. package/dist/driver/cdp.d.ts +6 -0
  45. package/dist/driver/cdp.js +245 -0
  46. package/dist/driver/page-driver.js +110 -7
  47. package/dist/driver/sealed.d.ts +4 -12
  48. package/dist/driver/sealed.js +23 -37
  49. package/dist/driver/stagehand.d.ts +12 -15
  50. package/dist/driver/stagehand.js +21 -17
  51. package/dist/durable/result.d.ts +1 -2
  52. package/dist/durable/result.js +2 -2
  53. package/dist/durable/store.d.ts +17 -3
  54. package/dist/durable/store.js +231 -64
  55. package/dist/durable.d.ts +47 -17
  56. package/dist/durable.js +106 -105
  57. package/dist/index.d.ts +3 -3
  58. package/dist/index.js +5 -3
  59. package/dist/live-view/index.d.ts +4 -1
  60. package/dist/live-view/index.js +5 -0
  61. package/dist/live-view/protocol.d.ts +39 -7
  62. package/dist/live-view/protocol.js +2 -0
  63. package/dist/live-view/provider.d.ts +2 -2
  64. package/dist/live-view/provider.js +2 -2
  65. package/dist/live-view/server.d.ts +55 -2
  66. package/dist/live-view/server.js +282 -35
  67. package/dist/live-view/stream.js +16 -3
  68. package/dist/live-view/viewer.js +106 -13
  69. package/dist/providers/cdp.d.ts +0 -1
  70. package/dist/providers/cdp.js +35 -13
  71. package/dist/providers/chrome-args.d.ts +3 -0
  72. package/dist/providers/chrome-args.js +13 -2
  73. package/dist/providers/profiles.d.ts +1 -15
  74. package/dist/providers/profiles.js +1 -64
  75. package/dist/providers/shared.d.ts +1 -47
  76. package/dist/providers/shared.js +1 -82
  77. package/dist/providers/worker-extension.d.ts +20 -1
  78. package/dist/providers/worker-extension.js +86 -7
  79. package/dist/testing/backend.d.ts +6 -24
  80. package/dist/testing/backend.js +7 -30
  81. package/dist/vault-session.d.ts +4 -7
  82. package/dist/vault-session.js +26 -81
  83. package/dist/vendor/browser-use-pi/ax.d.ts +106 -0
  84. package/dist/vendor/browser-use-pi/ax.js +642 -0
  85. package/dist/vendor/browser-use-pi/cdp.d.ts +19 -0
  86. package/dist/vendor/browser-use-pi/cdp.js +106 -0
  87. package/dist/vendor/browser-use-pi/page.d.ts +29 -0
  88. package/dist/vendor/browser-use-pi/page.js +99 -0
  89. package/package.json +15 -46
  90. package/src/vendor/browser-use-pi/UPSTREAM.json +25 -0
  91. package/src/vendor/stagehand-facade/UPSTREAM.json +0 -4
  92. package/dist/coding-agent-local.d.ts +0 -12
  93. package/dist/coding-agent-local.js +0 -72
  94. package/dist/coding-agent.d.ts +0 -134
  95. package/dist/coding-agent.js +0 -641
  96. package/dist/core/sites.d.ts +0 -33
  97. package/dist/core/sites.js +0 -104
  98. package/dist/driver/extension-worker.d.ts +0 -9
  99. package/dist/driver/extension-worker.js +0 -185
  100. package/dist/durable/web.d.ts +0 -47
  101. package/dist/durable/web.js +0 -41
  102. package/dist/providers/assigned.d.ts +0 -18
  103. package/dist/providers/assigned.js +0 -75
  104. package/dist/providers/browserbase-net.d.ts +0 -12
  105. package/dist/providers/browserbase-net.js +0 -95
  106. package/dist/providers/browserbase.d.ts +0 -169
  107. package/dist/providers/browserbase.js +0 -319
  108. package/dist/providers/kernel.d.ts +0 -58
  109. package/dist/providers/kernel.js +0 -291
  110. package/dist/recorder/credential.d.ts +0 -9
  111. package/dist/recorder/credential.js +0 -49
  112. package/dist/recorder/follow.d.ts +0 -36
  113. package/dist/recorder/follow.js +0 -163
  114. package/dist/recorder/frames.d.ts +0 -87
  115. package/dist/recorder/frames.js +0 -377
  116. package/dist/recorder/index.d.ts +0 -4
  117. package/dist/recorder/index.js +0 -7
  118. package/dist/recorder/jpeg.d.ts +0 -8
  119. package/dist/recorder/jpeg.js +0 -70
  120. package/dist/recorder/track.d.ts +0 -107
  121. package/dist/recorder/track.js +0 -280
  122. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +0 -15
  123. package/dist/vendor/stagehand-facade/screenshot-transport.js +0 -51
  124. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  125. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,5 +1,20 @@
1
1
  export declare const COPY = "stagehand-extension";
2
- /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory. */
2
+ /** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
3
+ export declare const STAGEHAND_EXTENSION = "Stagehand Runtime";
4
+ /** The Stagehand release the rewrite below was written against; a test holds it to the installed one, so a bump re-reads it. */
5
+ export declare const REWRITE_FOR = "4.4.0";
6
+ /** The first line of a rewritten worker, so the copy a browser runs can be told from Stagehand's own. */
7
+ export declare const REWRITE_MARK = "// pi-browser: a released client's callback batches end with it (see NOTICE in this directory).\n";
8
+ export declare const COPY_NOTICE = "This directory is a copy of the extension in @browserbasehq/stagehand 4.4.0 (dist/extension), under\nStagehand's MIT license (LICENSE, beside this file). @parcha/pi-browser changed two files in it:\n- manifest.json: a content security policy limiting the extension's connections to its own files and one browser's\n DevTools socket.\n- service-worker.js: when the extension releases a client that went away, it now aborts that client's running callback batches,\n rather than leaving each to run until its own timeout.\n";
9
+ /** The Stagehand version installed beside this package. */
10
+ export declare const installedStagehand: () => string;
11
+ /** Stagehand's extension worker with the rewrite above. Each place it changes must appear exactly once: a worker that has moved
12
+ * any of them is refused whole, naming the place and the installed Stagehand (`installed`), and never rewritten in part. A
13
+ * refusal fails the local Chrome launch with that error (copyExtension runs before Chrome starts, and the cdp provider removes
14
+ * what the launch made): a launch never goes ahead on a copy without the rewrite, nor on Stagehand's own directory. */
15
+ export declare function endBatchesOnRelease(worker: string, installed?: string): string;
16
+ /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory, its worker rewritten (above), with Stagehand's LICENSE
17
+ * and a NOTICE naming what changed. The worker is rewritten before anything is copied, so a refused one leaves no copy. */
3
18
  export declare function copyExtension(into: string, source?: string): Promise<string>;
4
19
  /** The policy for the extension's pages and worker: its own files, and the browser's DevTools socket by its whole URL path. A
5
20
  * manifest that already sets one is left alone only when it is exactly this one (an earlier load of this copy wrote it and failed
@@ -12,3 +27,7 @@ export declare function loadConfined(copy: string, devtoolsUrl: string): Promise
12
27
  /** Whether the browser already holds, enabled, the extension with this id: the one a copy's path implies, never another that
13
28
  * merely carries Stagehand's name (an earlier, unconfined copy would be taken for the lease's own). */
14
29
  export declare function isLoaded(devtoolsUrl: string, id: string): Promise<boolean>;
30
+ /** Stagehand finds its extension by name and refuses a browser that holds two enabled, so every other extension carrying that
31
+ * name (an earlier, unconfined copy) is uninstalled: the one Stagehand finds is then the lease's own copy, `id`. Disabled ones
32
+ * go too, so none can be enabled again beside it. */
33
+ export declare function soleStagehand(devtoolsUrl: string, id: string): Promise<void>;
@@ -2,17 +2,85 @@
2
2
  // connect to nothing but the extension's own files and the browser's DevTools socket. Run code executes in that worker with
3
3
  // the extension's host permissions, so the browser itself refuses what the observer can only watch. A copy, because the
4
4
  // manifest is Stagehand's bytes and a directory shared by every lease cannot name this lease's socket; created before the
5
- // browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to.
5
+ // browser starts, because its path decides the extension's id and so the one Origin the browser's socket is opened to. The
6
+ // copy's worker also carries one rewrite, so a process that dies inside a run can be reattached at once (endBatchesOnRelease).
7
+ import { readFileSync } from "node:fs";
6
8
  import { cp, readFile, writeFile } from "node:fs/promises";
7
9
  import path from "node:path";
8
- import { cdpCall } from "./cdp-call.js";
10
+ import { fileURLToPath } from "node:url";
11
+ import { cdpCall } from "../core/cdp-call.js";
12
+ import { BrowserFailureError } from "../core/custody.js";
13
+ import { browserFailure } from "../core/failures.js";
9
14
  import { extensionDirectory, extensionOrigin } from "./chrome-args.js";
10
15
  export const COPY = "stagehand-extension";
16
+ /** The name Stagehand's extension carries, which is how Stagehand finds it in a browser. */
17
+ export const STAGEHAND_EXTENSION = "Stagehand Runtime";
11
18
  const LOAD_MS = 20_000;
12
- /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory. */
19
+ /** The Stagehand release the rewrite below was written against; a test holds it to the installed one, so a bump re-reads it. */
20
+ export const REWRITE_FOR = "4.4.0";
21
+ const WORKER = "service-worker.js";
22
+ /** The first line of a rewritten worker, so the copy a browser runs can be told from Stagehand's own. */
23
+ export const REWRITE_MARK = "// pi-browser: a released client's callback batches end with it (see NOTICE in this directory).\n";
24
+ export const COPY_NOTICE = `This directory is a copy of the extension in @browserbasehq/stagehand ${REWRITE_FOR} (dist/extension), under
25
+ Stagehand's MIT license (LICENSE, beside this file). @parcha/pi-browser changed two files in it:
26
+ - manifest.json: a content security policy limiting the extension's connections to its own files and one browser's
27
+ DevTools socket.
28
+ - ${WORKER}: when the extension releases a client that went away, it now aborts that client's running callback batches,
29
+ rather than leaving each to run until its own timeout.
30
+ `;
31
+ // Stagehand's extension keeps a dead client's callback batch running until the batch's own timeout, and holds the next client's
32
+ // stagehand.init behind it: releasing the client (ClientLifecycle.lost, then RPCClient.releaseClient) does not reach the batch's
33
+ // AbortController (createCallbackBatchController), while disposing the instance waits for every request in flight, the batch
34
+ // among them, and init queues behind that disposal. A process that dies inside a run is reattached only after its last batch's
35
+ // deadline (60 s by default), as long as Stagehand's own init deadline. The rewrite has releaseClient abort the running batches.
36
+ // That alone frees init (lines in Stagehand 4.4.0's dist/extension/service-worker.js): run() races the callback against its
37
+ // abort (:14696), so it rejects at once; only the outer callback_batch request holds the instance (:13368), the commands a batch
38
+ // sends taking none; its error reply throws, the client being gone (:13224), and its finally still releases the instance. One
39
+ // client is attached at a time and the router serves whichever it is, so only the dead client's batches are running when its
40
+ // release comes. Delete this rewrite once Stagehand ships the same change (upstream issue to be linked here).
41
+ const EDITS = [
42
+ { name: "the batch registry",
43
+ find: "function createCallbackBatchController(router) {\n",
44
+ to: "function createCallbackBatchController(router) {\n\tconst active = new Set();\n" },
45
+ { name: "a batch's start",
46
+ find: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n",
47
+ to: "\t\tconst controller = new AbortController();\n\t\tconst timeoutId = setTimeout(() => {\n\t\t\tcontroller.abort(/* @__PURE__ */ new Error(`Stagehand callback batch timed out after ${options.timeout}ms`));\n\t\t}, options.timeout);\n\t\tactive.add(controller);\n" },
48
+ { name: "a batch's end",
49
+ find: "\t\t\tclearTimeout(timeoutId);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n",
50
+ to: "\t\t\tclearTimeout(timeoutId);\n\t\t\tactive.delete(controller);\n\t\t\tif (!controller.signal.aborted) controller.abort(/* @__PURE__ */ new Error(\"Stagehand callback batch has completed\"));\n" },
51
+ { name: "the batch controller's interface",
52
+ find: "\treturn { run };\n}\nfunction createCallbackContextFacade(",
53
+ to: "\treturn {\n\t\trun,\n\t\tabortAll(reason) {\n\t\t\tfor (const controller of active) controller.abort(reason);\n\t\t}\n\t};\n}\nfunction createCallbackContextFacade(" },
54
+ { name: "the client's release",
55
+ find: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n",
56
+ to: "\treleaseClient() {\n\t\tthis.clientConnected = false;\n\t\tthis.router.callbackBatchController.abortAll(/* @__PURE__ */ new Error(\"Stagehand client disconnected\"));\n" },
57
+ ];
58
+ /** Stagehand's package root (the module it exports is dist/index.mjs). */
59
+ const stagehandRoot = () => path.join(path.dirname(fileURLToPath(import.meta.resolve("@browserbasehq/stagehand"))), "..");
60
+ /** The Stagehand version installed beside this package. */
61
+ export const installedStagehand = () => JSON.parse(readFileSync(path.join(stagehandRoot(), "package.json"), "utf8")).version;
62
+ /** Stagehand's extension worker with the rewrite above. Each place it changes must appear exactly once: a worker that has moved
63
+ * any of them is refused whole, naming the place and the installed Stagehand (`installed`), and never rewritten in part. A
64
+ * refusal fails the local Chrome launch with that error (copyExtension runs before Chrome starts, and the cdp provider removes
65
+ * what the launch made): a launch never goes ahead on a copy without the rewrite, nor on Stagehand's own directory. */
66
+ export function endBatchesOnRelease(worker, installed = installedStagehand()) {
67
+ for (const edit of EDITS) {
68
+ const at = worker.indexOf(edit.find);
69
+ if (at >= 0 && worker.indexOf(edit.find, at + 1) < 0)
70
+ continue;
71
+ throw new BrowserFailureError(browserFailure("browser_unavailable", `Stagehand's extension worker (${WORKER}, Stagehand ${installed}) has ${at < 0 ? "no" : "more than one"} match for ${edit.name}, which pi-browser rewrites so a gone client's callback batches end with it; the rewrite was written against Stagehand ${REWRITE_FOR}. No browser was started.`));
72
+ }
73
+ return REWRITE_MARK + EDITS.reduce((text, edit) => text.replace(edit.find, () => edit.to), worker);
74
+ }
75
+ /** `<into>/stagehand-extension`, a copy of Stagehand's extension directory, its worker rewritten (above), with Stagehand's LICENSE
76
+ * and a NOTICE naming what changed. The worker is rewritten before anything is copied, so a refused one leaves no copy. */
13
77
  export async function copyExtension(into, source = extensionDirectory()) {
78
+ const worker = endBatchesOnRelease(await readFile(path.join(source, WORKER), "utf8"));
14
79
  const copy = path.join(into, COPY);
15
80
  await cp(source, copy, { recursive: true, dereference: true });
81
+ await writeFile(path.join(copy, WORKER), worker);
82
+ await cp(path.join(stagehandRoot(), "LICENSE"), path.join(copy, "LICENSE"));
83
+ await writeFile(path.join(copy, "NOTICE"), COPY_NOTICE);
16
84
  return copy;
17
85
  }
18
86
  /** The policy for the extension's pages and worker: its own files, and the browser's DevTools socket by its whole URL path. A
@@ -50,14 +118,25 @@ export async function loadConfined(copy, devtoolsUrl) {
50
118
  session.close();
51
119
  }
52
120
  }
53
- /** Whether the browser already holds, enabled, the extension with this id: the one a copy's path implies, never another that
54
- * merely carries Stagehand's name (an earlier, unconfined copy would be taken for the lease's own). */
55
- export async function isLoaded(devtoolsUrl, id) {
121
+ const installed = async (devtoolsUrl) => {
56
122
  const session = await cdpCall(devtoolsUrl, "Extensions.getExtensions", {}, LOAD_MS);
57
123
  try {
58
- return (session.result?.extensions ?? []).some((e) => e.id === id && e.enabled);
124
+ return (session.result?.extensions ?? []);
59
125
  }
60
126
  finally {
61
127
  session.close();
62
128
  }
129
+ };
130
+ /** Whether the browser already holds, enabled, the extension with this id: the one a copy's path implies, never another that
131
+ * merely carries Stagehand's name (an earlier, unconfined copy would be taken for the lease's own). */
132
+ export async function isLoaded(devtoolsUrl, id) {
133
+ return (await installed(devtoolsUrl)).some((e) => e.id === id && e.enabled);
134
+ }
135
+ /** Stagehand finds its extension by name and refuses a browser that holds two enabled, so every other extension carrying that
136
+ * name (an earlier, unconfined copy) is uninstalled: the one Stagehand finds is then the lease's own copy, `id`. Disabled ones
137
+ * go too, so none can be enabled again beside it. */
138
+ export async function soleStagehand(devtoolsUrl, id) {
139
+ for (const other of (await installed(devtoolsUrl)).filter((e) => e.name === STAGEHAND_EXTENSION && e.id !== id)) {
140
+ (await cdpCall(devtoolsUrl, "Extensions.uninstall", { id: other.id }, LOAD_MS)).close();
141
+ }
63
142
  }
@@ -1,20 +1,6 @@
1
1
  import { EventEmitter } from "node:events";
2
- import type { AttachTarget, BrowserProvider, ProviderCaps, RemoteFile, SearchResult } from "../core/host.js";
2
+ import type { AttachTarget, BrowserProvider, ProviderCaps, RemoteFile } from "../core/host.js";
3
3
  import { type Sentinels } from "./sentinels.js";
4
- export type FakeFetchByFormat = {
5
- markdown?: {
6
- contentType: string;
7
- content: string;
8
- } | {
9
- status: number;
10
- };
11
- raw?: {
12
- contentType: string;
13
- content: string;
14
- } | {
15
- status: number;
16
- };
17
- };
18
4
  /** A vendor SDK's failure: the HTTP status is on the error, never inside the text. */
19
5
  export declare class FakeProviderError extends Error {
20
6
  readonly status: number;
@@ -63,9 +49,6 @@ export type FakeBackendOptions = {
63
49
  caps?: Partial<ProviderCaps>;
64
50
  start?: string;
65
51
  pages?: Record<string, FixturePage>;
66
- /** A URL not listed is a 404; an object answers markdown and raw apart. */
67
- fetches?: Record<string, string | FakeFetchByFormat>;
68
- search?: SearchResult["results"];
69
52
  /** Every ledger row is also appended here as JSONL, so a killed process leaves its calls behind. */
70
53
  logFile?: string;
71
54
  connections?: BrokerConnection[];
@@ -77,7 +60,7 @@ export type FakeBackendOptions = {
77
60
  fullPageHeight?: number;
78
61
  /** What `locate` finds, by the snapshot ID or the CSS selector a caller gives: one box or several (a selector that matches more than one). Anything else matches nothing. */
79
62
  elements?: Record<string, FakeBox | FakeBox[]>;
80
- /** Device pixels per CSS pixel; a screenshot is this many times larger unless it asks for `scale: "css"`. */
63
+ /** Device pixels per CSS pixel; a screenshot is this many times larger, times the `scale` it asks for. */
81
64
  deviceScale?: number;
82
65
  };
83
66
  export type FakeBox = {
@@ -90,7 +73,7 @@ export type FakeScreenshotOptions = {
90
73
  fullPage?: boolean;
91
74
  type?: "png" | "jpeg";
92
75
  quality?: number;
93
- scale?: "css" | "device";
76
+ scale?: number;
94
77
  clip?: FakeBox;
95
78
  };
96
79
  /** A PNG or JPEG whose header declares `width` x `height`: enough for a reader that decodes the header, not a picture. */
@@ -128,7 +111,7 @@ export declare class FakeBackend {
128
111
  private delays;
129
112
  private peak;
130
113
  private echoOn;
131
- readonly opts: Required<Pick<FakeBackendOptions, "start" | "fetches" | "search" | "connections" | "downloads">> & FakeBackendOptions;
114
+ readonly opts: Required<Pick<FakeBackendOptions, "start" | "connections" | "downloads">> & FakeBackendOptions;
132
115
  constructor(options?: FakeBackendOptions);
133
116
  /** The next call of `op` is applied and recorded, then never answered. */
134
117
  hold(op: string): void;
@@ -155,8 +138,6 @@ export declare class FakeBackend {
155
138
  attaches: number;
156
139
  releases: number;
157
140
  releaseNoops: number;
158
- fetches: number;
159
- searches: number;
160
141
  dispatches: number;
161
142
  reads: number;
162
143
  peakLive: number;
@@ -227,7 +208,8 @@ export declare class FakeDriverFace {
227
208
  }): Promise<unknown>;
228
209
  /** No `dispatched` row: a read of the URL is not a read of the page. */
229
210
  url(id: string): Promise<string>;
230
- /** Header-only image of the viewport (or full page) times the device scale; each capture is a dispatched row. */
211
+ /** Header-only image of the viewport (or full page) times the device scale and the asked scale, rounded as Chrome
212
+ * rounds; each capture is a dispatched row. */
231
213
  screenshot(id: string, options?: FakeScreenshotOptions): Promise<{
232
214
  data: string;
233
215
  mimeType: string;
@@ -35,7 +35,7 @@ export function fakeImage(type, width, height) {
35
35
  ihdr[9] = 2;
36
36
  return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk("IHDR", ihdr), chunk("IEND", Buffer.alloc(0))]);
37
37
  }
38
- const DEFAULT_CAPS = { timeoutModel: "inactivity", maxLifetimeS: 3600, survivesDisconnect: false, releaseIsAsync: false, profiles: false, extension: "loaded-locally" };
38
+ const DEFAULT_CAPS = { profiles: false };
39
39
  export class FakeBackend {
40
40
  sentinels;
41
41
  pages;
@@ -62,8 +62,6 @@ export class FakeBackend {
62
62
  this.opts = {
63
63
  ...options,
64
64
  start: options.start ?? "about:blank",
65
- fetches: options.fetches ?? {},
66
- search: options.search ?? [],
67
65
  downloads: options.downloads ?? {},
68
66
  connections: options.connections ?? [{ name: "demo", startUrl: "https://login.sentinel.test/", fields: [{ name: "username", type: "text" }, { name: "password", type: "password" }, { name: "otp", type: "totp" }], allowedOrigins: ["https://login.sentinel.test"], enrollment: true }],
69
67
  };
@@ -104,7 +102,7 @@ export class FakeBackend {
104
102
  const count = (op) => this.ledger.filter((r) => r.op === op).length;
105
103
  return {
106
104
  creates: count("create"), findByTag: count("findByTag"), status: count("status"), attaches: count("attach"), releases: count("release"), releaseNoops: count("release-noop"),
107
- fetches: count("fetch"), searches: count("search"), dispatches: this.dispatched.filter((d) => d.op === "run").length, reads: this.dispatched.filter((d) => d.op === "read").length,
105
+ dispatches: this.dispatched.filter((d) => d.op === "run").length, reads: this.dispatched.filter((d) => d.op === "read").length,
108
106
  peakLive: this.peak, liveAtEnd: this.liveCount(),
109
107
  };
110
108
  }
@@ -211,26 +209,6 @@ export class FakeBackend {
211
209
  const view = b.sentinels.bbLiveViewUrl;
212
210
  return { fullscreen: view, framed: `${view}&framed=1`, pages: [{ id: "p1", url: s.url, title: b.pages[s.url]?.title ?? "", fullscreen: view }] };
213
211
  },
214
- async fetch(request, signal) {
215
- await b.before("fetch", signal);
216
- b.record("fetch", { url: request.url });
217
- await b.after("fetch");
218
- const entry = b.opts.fetches[request.url];
219
- if (entry === undefined)
220
- throw new FakeProviderError(`fetch ${request.url}: 404`, 404);
221
- if (typeof entry === "string")
222
- return { finalUrl: request.url, statusCode: 200, contentType: "text/markdown", content: entry };
223
- const answer = entry[request.format === "raw" ? "raw" : "markdown"];
224
- if (!answer || "status" in answer)
225
- throw new FakeProviderError(`fetch ${request.url}: ${answer?.status ?? 404}`, answer?.status ?? 404);
226
- return { finalUrl: request.url, statusCode: 200, contentType: answer.contentType, content: answer.content };
227
- },
228
- async search(request, signal) {
229
- await b.before("search", signal);
230
- b.record("search", { query: request.query });
231
- await b.after("search");
232
- return { results: b.opts.search.slice(0, request.n) };
233
- },
234
212
  downloads: {
235
213
  async list(_ref) { return Object.entries(b.opts.downloads).map(([name, body]) => ({ name, sizeBytes: Buffer.byteLength(body), modifiedAt: null })); },
236
214
  async read(_ref, fileName, maxBytes) {
@@ -299,8 +277,6 @@ export function remoteProvider(url, options = {}) {
299
277
  attach: (ref, signal) => call("attach", [ref], signal),
300
278
  release: (ref, signal) => call("release", [ref], signal),
301
279
  liveView: (ref) => call("liveView", [ref]),
302
- fetch: (request, signal) => call("fetch", [request], signal),
303
- search: (request, signal) => call("search", [request], signal),
304
280
  };
305
281
  }
306
282
  /** Counts a fill before the provider is touched and never repeats an unknown one; its failures carry only codes. */
@@ -393,13 +369,14 @@ export class FakeDriverFace {
393
369
  await this.b.before("driver.url");
394
370
  return this.session(id).url;
395
371
  }
396
- /** Header-only image of the viewport (or full page) times the device scale; each capture is a dispatched row. */
372
+ /** Header-only image of the viewport (or full page) times the device scale and the asked scale, rounded as Chrome
373
+ * rounds; each capture is a dispatched row. */
397
374
  async screenshot(id, options = {}) {
398
375
  await this.call(id, "screenshot", "screenshot", { options });
399
376
  const { viewport = { width: 1288, height: 711 }, fullPageHeight = 8319, deviceScale = 1 } = this.b.opts;
400
- const factor = options.scale === "css" ? 1 : deviceScale;
401
- const width = (options.clip ? options.clip.width : viewport.width) * factor;
402
- const height = (options.clip ? options.clip.height : options.fullPage ? fullPageHeight : viewport.height) * factor;
377
+ const factor = deviceScale * (options.scale ?? 1);
378
+ const width = Math.round((options.clip ? options.clip.width : viewport.width) * factor);
379
+ const height = Math.round((options.clip ? options.clip.height : options.fullPage ? fullPageHeight : viewport.height) * factor);
403
380
  const type = options.type ?? "jpeg";
404
381
  await this.b.after("driver.screenshot");
405
382
  return { data: fakeImage(type, width, height).toString("base64"), mimeType: `image/${type}`, width, height };
@@ -28,23 +28,20 @@ export declare function vaultRuntime(options: VaultOptions, track: (secret: stri
28
28
  }): VaultRuntime | null;
29
29
  /** Waits, up to `ms`, for a person to stop driving a session: a capture reads only once they have handed back. True when the gate is free. */
30
30
  export declare function untilQuiet(gate: DrivingGate | null, ms?: number): Promise<boolean>;
31
- /** `vaulted`: this session was created under the host's vault plan (a context kind asked the provider for a saved context or profile), so it may be captured; a session that
32
- * started with no target cannot be given one later, because its provider holds no context for it. `fresh`: nothing was kept, so a new context was made and its id is
33
- * given to the vault right after the create (a restart then still finds it). */
31
+ /** `vaulted`: this session was created under the host's vault plan, with a target. */
34
32
  export type RestorePlan = {
35
33
  spec: SessionSpec;
36
34
  afterAttach: ((target: AttachTarget) => Promise<void>) | null;
37
35
  vaulted: boolean;
38
- fresh: boolean;
39
36
  /** Set when the vault may hold a saved sign-in this session did not take (the read failed, or what it holds could not be used here): this session is NOT captured, so it
40
37
  * can never replace what is saved. The text is the warning given once at the first capture. */
41
38
  holdBack?: string;
42
39
  };
43
- /** What the create does with the vault: the spec the provider is asked for (a kept context or profile for Browserbase and Kernel) and a step that runs after the
44
- * browser is attached and before the driver is (a local Chrome's cookies and local storage). The record the adapter stores is made from the ORIGINAL spec, never this one. */
40
+ /** What the create does with the vault: a step that runs after the browser is attached and before the driver is (a local Chrome's cookies and local storage).
41
+ * The spec is the one given, and the record the adapter stores is made from it. */
45
42
  export declare function planRestore(rt: VaultRuntime | null, target: VaultTarget | undefined, provider: BrowserProvider, spec: SessionSpec): Promise<RestorePlan>;
46
43
  export type CaptureOptions = {
47
- /** Whether the session was created under the vault plan (RestorePlan.vaulted). A context kind session that was not cannot be captured. */
44
+ /** Whether the session was created under the vault plan (RestorePlan.vaulted). */
48
45
  vaulted: boolean;
49
46
  /** The session's driving gate, read when the capture runs: a person who begins driving while the browser is being read voids that read. */
50
47
  gate?: () => DrivingGate | null;
@@ -1,13 +1,11 @@
1
1
  // How an adapter uses a host's session vault (core/vault.ts): restore a kept sign-in when a session is created, before the driver attaches, and capture
2
- // it when the session is released or a person hands it back. The state stays in memory and crosses only the host's port: nothing here logs a value, and
3
- // a provider's context id is registered with the run's redactor the moment it is seen. A restore or capture that fails never fails the browser: the session
2
+ // it when the session is released or a person hands it back. Only a local Chrome's state is kept (its cookies and local storage, over CDP). The state
3
+ // stays in memory and crosses only the host's port: nothing here logs a value. A restore or capture that fails never fails the browser: the session
4
4
  // starts signed out, or ends without a fresh capture, and a process warning says which, with no value in it.
5
- import { randomBytes } from "node:crypto";
6
5
  import { BrowserFailureError } from "./core/custody.js";
7
6
  import { browserFailure } from "./core/failures.js";
8
- import { MIN_REDACTED_VALUE_LENGTH } from "./core/redact.js";
9
7
  import { keptFor } from "./core/driving.js";
10
- import { clampSessionCookieAgeMs, coversEveryOrigin, vaultTarget } from "./core/vault.js";
8
+ import { clampSessionCookieAgeMs, vaultTarget } from "./core/vault.js";
11
9
  import { captureCdpState, connectCdp, restoreCdpState } from "./providers/cdp-session.js";
12
10
  /** `null` when the host gave no vault. A bad age cap throws here, so a host learns at setup. */
13
11
  export function vaultRuntime(options, track, warn, now = () => new Date(), limits = {}) {
@@ -37,21 +35,12 @@ async function within(work, ms, onTimeout = () => { }) {
37
35
  }
38
36
  }
39
37
  const refused = (message) => new BrowserFailureError(browserFailure("refused", message));
40
- /** A secret too short for the redactor to scrub is not used as one: the redactor ignores values under its minimum, so it would leak. */
41
- function trackSecret(rt, secret, what) {
42
- if (secret.length < MIN_REDACTED_VALUE_LENGTH) {
43
- rt.warn(`the session vault's ${what} is too short for the redactor to scrub, so it is not used`);
44
- return false;
45
- }
46
- rt.track(secret);
47
- return true;
48
- }
49
38
  const HELD_FAILED = "the vault could not be read at the start, so a saved sign-in may exist under this key and is left untouched: this session's sign-in is not captured";
50
39
  const HELD_UNUSED = "the vault holds a saved sign-in this session could not use, and it is left untouched: this session's sign-in is not captured";
51
- /** What the create does with the vault: the spec the provider is asked for (a kept context or profile for Browserbase and Kernel) and a step that runs after the
52
- * browser is attached and before the driver is (a local Chrome's cookies and local storage). The record the adapter stores is made from the ORIGINAL spec, never this one. */
40
+ /** What the create does with the vault: a step that runs after the browser is attached and before the driver is (a local Chrome's cookies and local storage).
41
+ * The spec is the one given, and the record the adapter stores is made from it. */
53
42
  export async function planRestore(rt, target, provider, spec) {
54
- const plain = { spec, afterAttach: null, vaulted: false, fresh: false };
43
+ const plain = { spec, afterAttach: null, vaulted: false };
55
44
  if (!rt || !target)
56
45
  return plain;
57
46
  let checked;
@@ -66,8 +55,6 @@ export async function planRestore(rt, target, provider, spec) {
66
55
  rt.warn("this browser provider cannot keep a session in a vault (a Chrome attached by endpoint is offered only when the host sets ownBrowser: true), so nothing was restored or will be captured");
67
56
  return plain;
68
57
  }
69
- if (vault.kind === "context" && vault.contextIdsInClear)
70
- throw refused("browser vault: this provider writes its context ids to a clear file, so a vault cannot use it. Give it a profile store that keeps ids in memory (memoryProfileStore). No session was started.");
71
58
  // A vault that stops answering never holds the session back: it starts signed out.
72
59
  let kept = null;
73
60
  let holdBack;
@@ -78,40 +65,17 @@ export async function planRestore(rt, target, provider, spec) {
78
65
  holdBack = HELD_FAILED;
79
66
  rt.warn(`the session vault could not restore (${kindOf(error)}); the session starts signed out`);
80
67
  }
81
- if (vault.kind === "context") {
82
- if (kept && (kept.kind !== "provider-context" || kept.provider !== vault.provider)) {
83
- rt.warn(`the vault holds a ${kept.kind} state this ${vault.provider} provider cannot use; it was ignored`);
84
- kept = null;
85
- holdBack = HELD_UNUSED;
86
- }
87
- // A context is a whole browser profile: it comes back only for a request that covers every origin it was saved for, never for some of them.
88
- if (kept?.kind === "provider-context" && !coversEveryOrigin(checked.origins, kept.origins)) {
89
- rt.warn("the vault holds a context whose saved origins this request does not cover every origin of (or records none); it was not restored");
90
- kept = null;
91
- holdBack = HELD_UNUSED;
92
- }
93
- if (kept?.kind === "provider-context" && !trackSecret(rt, kept.contextId, "context id")) {
94
- kept = null;
95
- holdBack = HELD_UNUSED;
96
- }
97
- if (kept?.kind === "provider-context")
98
- return { spec: vault.provider === "browserbase" ? { ...spec, contextId: kept.contextId, profile: undefined } : { ...spec, profile: { name: kept.contextId, save: true } }, afterAttach: null, vaulted: true, fresh: false };
99
- // A saved sign-in may exist that this session did not take: nothing persists for it, and it is never captured.
100
- if (holdBack)
101
- return { spec, afterAttach: null, vaulted: true, fresh: false, holdBack };
102
- // Nothing kept: a context that persists is made for this session, its id held in memory and given to the vault right after the create.
103
- return { spec: { ...spec, contextId: undefined, profile: { name: `vault-${randomBytes(9).toString("hex")}`, save: true } }, afterAttach: null, vaulted: true, fresh: true };
104
- }
105
68
  if (!kept)
106
69
  return { ...plain, vaulted: true, ...(holdBack ? { holdBack } : {}) };
107
- if (kept.kind !== "cdp") {
108
- rt.warn(`the vault holds a ${kept.kind} state a local Chrome cannot use; it was ignored`);
70
+ // A host's vault may hold a state of a kind this package does not keep (a hosted vendor's context, from before): left untouched, never replaced.
71
+ const kind = kept.kind;
72
+ if (kind !== "cdp") {
73
+ rt.warn(`the vault holds a ${typeof kind === "string" ? kind.slice(0, 40) : "different"} state a local Chrome cannot use; it was ignored`);
109
74
  return { ...plain, vaulted: true, holdBack: HELD_UNUSED };
110
75
  }
111
76
  return {
112
77
  spec,
113
78
  vaulted: true,
114
- fresh: false,
115
79
  afterAttach: async (attached) => {
116
80
  let link;
117
81
  try {
@@ -148,13 +112,6 @@ export function captureFor(rt, target, provider, ref, options = { vaulted: true
148
112
  }
149
113
  return;
150
114
  }
151
- if (vault.kind === "context" && !options.vaulted) {
152
- if (!warnedLate) {
153
- warnedLate = true;
154
- rt.warn("this session started with no vault target, so its provider holds no saved context for it: its sign-in cannot be kept. Set the target before the session starts");
155
- }
156
- return;
157
- }
158
115
  const stop = new AbortController();
159
116
  let link;
160
117
  // Numbered when it starts: an older capture that is still reading when a newer one of the same key begins writes nothing.
@@ -168,38 +125,26 @@ export function captureFor(rt, target, provider, ref, options = { vaulted: true
168
125
  if ((rt.latest.get(key) ?? 0) < attempt)
169
126
  rt.latest.set(key, attempt);
170
127
  const capturedAt = rt.now();
128
+ const gate = options.gate?.() ?? null;
129
+ let interrupted = false;
171
130
  let state;
172
- if (vault.kind === "context") {
173
- const id = vault.contextOf(ref);
174
- if (!id) {
175
- rt.warn("this provider no longer knows the context this session runs on (the run restarted), so its sign-in was not captured; the context the vault holds stands");
131
+ const off = gate?.onChange((now) => { if (now === "person")
132
+ interrupted = true; });
133
+ try {
134
+ const attached = await provider.attach(ref, stop.signal);
135
+ link = await connectCdp(attached.sdkCdpUrl);
136
+ if (stop.signal.aborted) {
137
+ link.close();
176
138
  return;
177
139
  }
178
- if (!trackSecret(rt, id, "context id"))
179
- return;
180
- state = { kind: "provider-context", capturedAt: capturedAt.toISOString(), provider: vault.provider, contextId: id, origins: [...checked.origins] };
140
+ state = await captureCdpState(link, checked.origins, capturedAt);
181
141
  }
182
- else {
183
- const gate = options.gate?.() ?? null;
184
- let interrupted = false;
185
- const off = gate?.onChange((now) => { if (now === "person")
186
- interrupted = true; });
187
- try {
188
- const attached = await provider.attach(ref, stop.signal);
189
- link = await connectCdp(attached.sdkCdpUrl);
190
- if (stop.signal.aborted) {
191
- link.close();
192
- return;
193
- }
194
- state = await captureCdpState(link, checked.origins, capturedAt);
195
- }
196
- finally {
197
- off?.();
198
- }
199
- if (interrupted || (gate && keptFor(gate) === "person_driving")) {
200
- rt.warn("a person began driving while the session was being read, so that capture was discarded; the last capture stands");
201
- return;
202
- }
142
+ finally {
143
+ off?.();
144
+ }
145
+ if (interrupted || (gate && keptFor(gate) === "person_driving")) {
146
+ rt.warn("a person began driving while the session was being read, so that capture was discarded; the last capture stands");
147
+ return;
203
148
  }
204
149
  // Nothing is written once the deadline has passed or a newer capture of this key has begun: an older read never replaces a newer one.
205
150
  if (stop.signal.aborted || rt.latest.get(key) !== attempt)
@@ -0,0 +1,106 @@
1
+ import type { CDP } from "./cdp.js";
2
+ import type { Page } from "./page.js";
3
+ type Probe = {
4
+ idle: number;
5
+ ready: string;
6
+ url: string;
7
+ title: string;
8
+ n: number;
9
+ doc: number;
10
+ };
11
+ /** A snapshot id is stale or never was: the driver turns it into the package's own words. */
12
+ export declare class UnknownIdError extends Error {
13
+ readonly id: string;
14
+ constructor(id: string);
15
+ }
16
+ /** Snapshot and id-based actions on Chrome's accessibility tree. */
17
+ export declare class AxHelpers {
18
+ private page;
19
+ private browser;
20
+ constructor(page: () => Page, browser: () => CDP);
21
+ private inflight;
22
+ private lastNet;
23
+ private tracked;
24
+ private dialogs;
25
+ private observing;
26
+ /** Role and name of every backend id in the last snapshot: marks new ids and names targets in action lines. */
27
+ private last;
28
+ /** The last snapshot's displayed ids, each to its backend node id; none before the first snapshot or after forget(). */
29
+ private ids;
30
+ /** The document and address the last snapshot was taken on. */
31
+ taken: {
32
+ doc: number;
33
+ url: string;
34
+ } | undefined;
35
+ /** Track in-flight requests per page session from CDP Network events (no page patching), and accept dialogs. */
36
+ private trackNetwork;
37
+ /** URL, title, document identity, a counter of DOM mutations (style aside) and form input/change events. */
38
+ probe(page?: Page): Promise<Probe>;
39
+ /**
40
+ * Event-based wait, never a fixed sleep: document parsed, no fresh in-flight requests (older than 1.5 s are treated as
41
+ * long-poll/analytics), and no DOM mutation for quietMs. Bounded by capMs.
42
+ */
43
+ settle(options?: {
44
+ capMs?: number;
45
+ quietMs?: number;
46
+ page?: Page;
47
+ since?: number;
48
+ }): Promise<{
49
+ why: string;
50
+ pending: number;
51
+ ms: number;
52
+ probe: Probe;
53
+ } | {
54
+ why: string;
55
+ pending: number;
56
+ ms: number;
57
+ probe?: undefined;
58
+ }>;
59
+ private flushDialogs;
60
+ /**
61
+ * Text actually shown, lowercased with whitespace collapsed. The AX tree keeps opacity:0 text (pre-rendered success
62
+ * banners), which agents then report as success; checkVisibility with checkOpacity drops it.
63
+ */
64
+ private visibleText;
65
+ /**
66
+ * AX trees of the main frame and, with `frames`, of every same-process child frame. A child frame whose tree cannot be
67
+ * read (a cross-origin frame Chrome runs in another process) is returned as `unread`, never dropped unsaid.
68
+ */
69
+ private capture;
70
+ /** The page as one list in page order: `[frame-node] role "name" = value states`, ## headings and visible text. */
71
+ snapshot(options?: {
72
+ includeIframes?: boolean;
73
+ max?: number;
74
+ }): Promise<string>;
75
+ /** Drops the snapshot's ids: an action by any of them then fails as a stale snapshot. */
76
+ forget(): void;
77
+ /** Whether there is a snapshot to act on. */
78
+ get hydrated(): boolean;
79
+ /** The backend node id a displayed id names in the latest snapshot; throws UnknownIdError for any other. */
80
+ nodeOf(id: string): number;
81
+ private onNode;
82
+ private describe;
83
+ /** Scroll into view and return a clickable, unobstructed center point, or throw a precise reason. */
84
+ point(page: Page, id: number, editableCover?: boolean): Promise<{
85
+ x: number;
86
+ y: number;
87
+ covered: boolean;
88
+ }>;
89
+ /** Runs one action on a displayed id and returns one line: navigated to <url> / page changed / no change. */
90
+ private act;
91
+ change(before: Probe | undefined, after?: Probe): Promise<string>;
92
+ click(display: string): Promise<string>;
93
+ hover(display: string): Promise<string>;
94
+ /** Picks a native select's option by its label or value, or each of several in a multiple select. */
95
+ select(display: string, values: string | string[]): Promise<string>;
96
+ /** Replaces a field's text (Pi's type): a native date or time input by its value, any other by click, select-all and keys. */
97
+ fill(display: string, text: string): Promise<string>;
98
+ /** Types at the end of a field's whole text, as keys would; `delayMs` between characters, as paced typing asks. */
99
+ type(display: string, text: string, delayMs?: number): Promise<string>;
100
+ /** Clicks the element, then presses a key on it: a name (Enter, Tab, Escape, ArrowDown, ...) or one character, each
101
+ * with any of the modifiers Shift, Control (Ctrl), Alt and Meta (Command, Cmd) before it: Shift+Tab, Control+A. */
102
+ press(display: string, key: string): Promise<string>;
103
+ private enter;
104
+ private key;
105
+ }
106
+ export {};