@parcha/pi-browser 0.0.0-stage → 0.1.0-beta.13

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 (104) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +33 -0
  4. package/README.md +329 -2
  5. package/dist/coding-agent-local.d.ts +16 -0
  6. package/dist/coding-agent-local.js +138 -0
  7. package/dist/coding-agent.d.ts +78 -0
  8. package/dist/coding-agent.js +446 -0
  9. package/dist/core/contract.d.ts +26 -0
  10. package/dist/core/contract.js +154 -0
  11. package/dist/core/custody.d.ts +111 -0
  12. package/dist/core/custody.js +122 -0
  13. package/dist/core/decisions.d.ts +43 -0
  14. package/dist/core/decisions.js +4 -0
  15. package/dist/core/downloads.d.ts +35 -0
  16. package/dist/core/downloads.js +131 -0
  17. package/dist/core/effects.d.ts +63 -0
  18. package/dist/core/effects.js +256 -0
  19. package/dist/core/evidence.d.ts +43 -0
  20. package/dist/core/evidence.js +6 -0
  21. package/dist/core/failures.d.ts +28 -0
  22. package/dist/core/failures.js +59 -0
  23. package/dist/core/find.d.ts +32 -0
  24. package/dist/core/find.js +179 -0
  25. package/dist/core/guard.d.ts +6 -0
  26. package/dist/core/guard.js +24 -0
  27. package/dist/core/host.d.ts +279 -0
  28. package/dist/core/host.js +2 -0
  29. package/dist/core/images.d.ts +37 -0
  30. package/dist/core/images.js +60 -0
  31. package/dist/core/lease.d.ts +16 -0
  32. package/dist/core/lease.js +30 -0
  33. package/dist/core/receipts.d.ts +19 -0
  34. package/dist/core/receipts.js +22 -0
  35. package/dist/core/redact.d.ts +13 -0
  36. package/dist/core/redact.js +83 -0
  37. package/dist/core/session-control.d.ts +25 -0
  38. package/dist/core/session-control.js +75 -0
  39. package/dist/core/sites.d.ts +33 -0
  40. package/dist/core/sites.js +102 -0
  41. package/dist/core/tools.d.ts +37 -0
  42. package/dist/core/tools.js +170 -0
  43. package/dist/core/uri.d.ts +11 -0
  44. package/dist/core/uri.js +37 -0
  45. package/dist/core/usage.d.ts +38 -0
  46. package/dist/core/usage.js +44 -0
  47. package/dist/core/web.d.ts +98 -0
  48. package/dist/core/web.js +327 -0
  49. package/dist/driver/stagehand.d.ts +25 -0
  50. package/dist/driver/stagehand.js +141 -0
  51. package/dist/durable-result.d.ts +6 -0
  52. package/dist/durable-result.js +2 -0
  53. package/dist/durable.d.ts +75 -0
  54. package/dist/durable.js +484 -0
  55. package/dist/index.d.ts +18 -0
  56. package/dist/index.js +19 -0
  57. package/dist/providers/browserbase-net.d.ts +13 -0
  58. package/dist/providers/browserbase-net.js +96 -0
  59. package/dist/providers/browserbase.d.ts +152 -0
  60. package/dist/providers/browserbase.js +262 -0
  61. package/dist/providers/cdp-call.d.ts +6 -0
  62. package/dist/providers/cdp-call.js +25 -0
  63. package/dist/providers/cdp.d.ts +48 -0
  64. package/dist/providers/cdp.js +353 -0
  65. package/dist/providers/http.d.ts +2 -0
  66. package/dist/providers/http.js +21 -0
  67. package/dist/providers/kernel.d.ts +49 -0
  68. package/dist/providers/kernel.js +246 -0
  69. package/dist/providers/shared.d.ts +47 -0
  70. package/dist/providers/shared.js +82 -0
  71. package/dist/recorder/credential.d.ts +9 -0
  72. package/dist/recorder/credential.js +49 -0
  73. package/dist/recorder/follow.d.ts +26 -0
  74. package/dist/recorder/follow.js +138 -0
  75. package/dist/recorder/frames.d.ts +80 -0
  76. package/dist/recorder/frames.js +309 -0
  77. package/dist/recorder/index.d.ts +3 -0
  78. package/dist/recorder/index.js +6 -0
  79. package/dist/recorder/jpeg.d.ts +5 -0
  80. package/dist/recorder/jpeg.js +34 -0
  81. package/dist/store.d.ts +56 -0
  82. package/dist/store.js +196 -0
  83. package/dist/testing/backend.d.ts +231 -0
  84. package/dist/testing/backend.js +414 -0
  85. package/dist/testing/driver.d.ts +28 -0
  86. package/dist/testing/driver.js +32 -0
  87. package/dist/testing/index.d.ts +4 -0
  88. package/dist/testing/index.js +4 -0
  89. package/dist/testing/pages.d.ts +3 -0
  90. package/dist/testing/pages.js +10 -0
  91. package/dist/testing/sentinels.d.ts +29 -0
  92. package/dist/testing/sentinels.js +38 -0
  93. package/dist/vendor/stagehand-facade/contract.d.ts +348 -0
  94. package/dist/vendor/stagehand-facade/contract.js +155 -0
  95. package/dist/vendor/stagehand-facade/runtime.d.ts +90 -0
  96. package/dist/vendor/stagehand-facade/runtime.js +1640 -0
  97. package/dist/vendor/stagehand-facade/screenshot-transport.d.ts +15 -0
  98. package/dist/vendor/stagehand-facade/screenshot-transport.js +51 -0
  99. package/dist/vendor/stagehand-facade/tools.d.ts +31 -0
  100. package/dist/vendor/stagehand-facade/tools.js +139 -0
  101. package/dist/web.d.ts +41 -0
  102. package/dist/web.js +38 -0
  103. package/package.json +123 -4
  104. package/src/vendor/stagehand-facade/UPSTREAM.json +24 -0
@@ -0,0 +1,353 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { mkdir, open, readdir, readFile, readlink, rm, stat, writeFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { BrowserFailureError } from "../core/custody.js";
5
+ import { cdpCall } from "./cdp-call.js";
6
+ /** Stagehand 4.1.0's DEFAULT_CHROME_FLAGS (packages/sdk-ts/src/browser/localBrowser.ts, MIT, see NOTICE). Without them
7
+ * Stagehand.create takes about 24 s on a local Chrome instead of under 100 ms. */
8
+ const CHROME_FLAGS = [
9
+ "--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider,CalculateNativeWinOcclusion,InterestFeedContentSuggestions,CertificateTransparencyComponentUpdater,AutofillServerCommunication,PrivacySandboxSettings4,RenderDocument",
10
+ "--disable-component-extensions-with-background-pages",
11
+ "--disable-background-networking",
12
+ "--disable-component-update",
13
+ "--disable-client-side-phishing-detection",
14
+ "--disable-sync",
15
+ "--metrics-recording-only",
16
+ "--disable-default-apps",
17
+ "--mute-audio",
18
+ "--no-default-browser-check",
19
+ "--no-first-run",
20
+ "--disable-backgrounding-occluded-windows",
21
+ "--disable-renderer-backgrounding",
22
+ "--disable-background-timer-throttling",
23
+ "--disable-ipc-flooding-protection",
24
+ "--password-store=basic",
25
+ "--use-mock-keychain",
26
+ "--force-fieldtrials=*BackgroundTracing/default/",
27
+ "--disable-hang-monitor",
28
+ "--disable-prompt-on-repost",
29
+ "--disable-domain-reliability",
30
+ "--propagate-iph-for-testing",
31
+ "--enable-unsafe-extension-debugging",
32
+ "--remote-allow-origins=*",
33
+ "--enable-features=WebMCPTesting,DevToolsWebMCPSupport",
34
+ ];
35
+ const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 86_400, survivesDisconnect: true, releaseIsAsync: false, extension: "loaded-locally" };
36
+ const downloadsDir = (profileRoot, tag) => path.join(profileDir(profileRoot, tag) + ".downloads");
37
+ const READY_MS = 20_000;
38
+ /** The browser is gone and directories it used are not: a profile left behind holds the session's cookies, so a release that cannot remove
39
+ * one says so, naming every one still there (`dirs`, the first as `dir`), and is asked again. `original` is the failure of the launch that
40
+ * was being undone, when there was one. */
41
+ export class ProfileNotRemovedError extends Error {
42
+ dirs;
43
+ cause;
44
+ original;
45
+ code = "profile_not_removed";
46
+ dir;
47
+ constructor(dirs, cause, original) {
48
+ super(`the browser is gone but ${dirs.length === 1 ? "its directory" : "its directories"} ${dirs.join(" and ")} could not be removed (${cause instanceof Error ? cause.message : String(cause)}); ${dirs.length === 1 ? "it" : "they"} may hold the session's cookies, so remove ${dirs.length === 1 ? "it" : "them"} by hand${original === undefined ? "" : `; the launch had also failed: ${original instanceof Error ? original.message : String(original)}`}`);
49
+ this.dirs = dirs;
50
+ this.cause = cause;
51
+ this.original = original;
52
+ this.name = "ProfileNotRemovedError";
53
+ this.dir = dirs[0];
54
+ }
55
+ }
56
+ /** What a retry can cure: a file that arrived in the directory, or a handle or lock that is let go (the codes Node's own rm retries). */
57
+ const RETRYABLE = new Set(["ENOTEMPTY", "EBUSY", "EMFILE", "ENFILE", "EPERM"]);
58
+ const REMOVAL_RETRIES = 5;
59
+ const REMOVAL_DELAY_MS = 100;
60
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
61
+ /** Removes a directory tree; what is still there afterwards is the caller's to report, never to swallow. A browser's last writes can land after its
62
+ * process is killed (its other processes are still exiting), and a directory a file arrives in while it is being removed fails with ENOTEMPTY: the
63
+ * removal is tried again, waiting a little longer each time (100, 200, ... 500 ms, about a second and a half in all). A failure a retry cannot cure
64
+ * (EACCES, say) is reported at once. (A link is unlinked, not followed.) */
65
+ async function removeTree(dir, remove) {
66
+ for (let attempt = 0;; attempt += 1) {
67
+ try {
68
+ await remove(dir, { recursive: true, force: true });
69
+ return null;
70
+ }
71
+ catch (failure) {
72
+ const error = failure instanceof Error ? failure : new Error(String(failure));
73
+ if (attempt >= REMOVAL_RETRIES || !RETRYABLE.has(error.code ?? ""))
74
+ return { dir, error };
75
+ await sleep(REMOVAL_DELAY_MS * (attempt + 1));
76
+ }
77
+ }
78
+ }
79
+ /** Every directory is tried, whatever the others did; what is left is reported together. */
80
+ async function removeAll(dirs, remove) {
81
+ const left = [];
82
+ for (const dir of dirs) {
83
+ const stuck = await removeTree(dir, remove);
84
+ if (stuck)
85
+ left.push(stuck);
86
+ }
87
+ return left.length > 0 ? { dirs: left.map((l) => l.dir), error: left[0].error } : null;
88
+ }
89
+ /** The extension inside the browser dials the URL it is given, so it must be a `ws://` debugger URL. */
90
+ async function debuggerUrl(endpoint, signal) {
91
+ if (/^wss?:/i.test(endpoint))
92
+ return endpoint;
93
+ const found = await (await fetch(new URL("/json/version", endpoint), signal ? { signal } : {})).json();
94
+ if (!found.webSocketDebuggerUrl)
95
+ throw new Error("the endpoint did not report a debugger URL");
96
+ return found.webSocketDebuggerUrl;
97
+ }
98
+ /** Only the Chrome running on that profile writes `DevToolsActivePort`, so it names that Chrome and no other browser on
99
+ * a port. */
100
+ async function ownDebugger(profile) {
101
+ const [port, browser] = (await readFile(path.join(profile, "DevToolsActivePort"), "utf8").catch(() => "")).split("\n");
102
+ return /^\d+$/.test(port ?? "") && browser?.startsWith("/devtools/browser/") ? { port: Number(port), path: browser.trim() } : null;
103
+ }
104
+ const answeringPath = async (port) => debuggerUrl(`http://127.0.0.1:${port}`).then((url) => new URL(url).pathname, () => null);
105
+ /** A port that takes the probe and does not answer within this may still be a live browser's. */
106
+ const PROBE_MS = 2_000;
107
+ /** A release that does not own the lease's browser left its profile: the port the profile names took the probe and did
108
+ * not answer, so a live browser may still run on it. Asked again once that port answers or closes, the release decides. */
109
+ export class ProfileOwnershipUnclearError extends Error {
110
+ dir;
111
+ port;
112
+ code = "profile_ownership_unclear";
113
+ constructor(dir, port) {
114
+ super(`the profile ${dir} was left: port ${port}, which it names, took the browser probe and did not answer within ${PROBE_MS} ms, so a live browser may still run on it; release again once that port answers or closes`);
115
+ this.dir = dir;
116
+ this.port = port;
117
+ this.name = "ProfileOwnershipUnclearError";
118
+ }
119
+ }
120
+ /** `local:<pid>:<port>:<tag>`. The pid is signalled only while the browser on that port reports it as its own, and the
121
+ * profile removed is the id's own tag's, so a ref pairing one lease's id with another's tag touches nothing. */
122
+ const parse = (id) => { const m = /^local:(\d+):(\d+):([A-Za-z0-9_.-]+)$/.exec(id); return m ? { pid: Number(m[1]), port: Number(m[2]), tag: m[3] } : null; };
123
+ /** A lease tag names a directory under the profile root, so it is one path segment: no separators, never `.` or `..`. */
124
+ const SAFE_TAG = /^[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}$/;
125
+ const profileDir = (root, tag) => {
126
+ if (!SAFE_TAG.test(tag))
127
+ throw new Error("a cdp lease tag is one path segment of [A-Za-z0-9_.-]");
128
+ return path.join(root, tag);
129
+ };
130
+ /** Signal 0 only asks; EPERM means the process exists under another user. */
131
+ const alive = (pid) => { try {
132
+ process.kill(pid, 0);
133
+ return true;
134
+ }
135
+ catch (error) {
136
+ return error.code === "EPERM";
137
+ } };
138
+ /** The browser entry of `SystemInfo.getProcessInfo`, which every OS gives (a /proc command line exists only on Linux). */
139
+ async function browserPid(port, timeoutMs = 2_000) {
140
+ try {
141
+ const url = await Promise.race([debuggerUrl(`http://127.0.0.1:${port}`), sleep(timeoutMs).then(() => { throw new Error("no answer"); })]);
142
+ const session = await cdpCall(url, "SystemInfo.getProcessInfo", {}, timeoutMs);
143
+ session.close();
144
+ const browser = session.result?.processInfo?.find((p) => p.type === "browser");
145
+ return typeof browser?.id === "number" ? browser.id : null;
146
+ }
147
+ catch {
148
+ return null;
149
+ }
150
+ }
151
+ /** Chrome's singleton socket directory under TMPDIR outlives every Chrome exit, a clean one included; the profile's link
152
+ * names it. */
153
+ async function singletonDir(profile) {
154
+ const socket = await readlink(path.join(profile, "SingletonSocket")).catch(() => null);
155
+ const dir = socket && path.basename(socket) === "SingletonSocket" ? path.dirname(socket) : null;
156
+ return dir && /^\.?(org\.chromium\.Chromium|com\.google\.Chrome)\.[A-Za-z0-9]{6}$/.test(path.basename(dir)) ? dir : null;
157
+ }
158
+ async function killTree(pid) {
159
+ if (process.platform === "win32")
160
+ return void (await new Promise((resolve) => execFile("taskkill", ["/pid", String(pid), "/T", "/F"], () => resolve())));
161
+ try {
162
+ process.kill(-pid, "SIGKILL");
163
+ }
164
+ catch {
165
+ try {
166
+ process.kill(pid, "SIGKILL");
167
+ }
168
+ catch { }
169
+ }
170
+ }
171
+ /** `internals` is for tests: the removal a release uses. */
172
+ export function cdpProvider(options, internals = {}) {
173
+ const remove = internals.remove ?? ((dir, opts) => rm(dir, opts));
174
+ const downloads = "chrome" in options ? localDownloads(options.chrome.profileRoot) : undefined;
175
+ // So a release can wait for the exit it caused: an unreaped child still answers `kill 0`.
176
+ const children = new Map();
177
+ /** A socket directory a release could not remove: the profile's link that named it may go with the profile, so the next release of the
178
+ * lease in this process is told it here. (A restarted process has the report's text.) */
179
+ const socketsLeft = new Map();
180
+ /** A spawned Chrome whose handle we hold is ours (a handle cannot name a recycled pid); after a restart, only while
181
+ * the browser on the recorded port reports that pid. */
182
+ const isOurs = async ({ pid, port }) => {
183
+ const child = children.get(pid);
184
+ if (child)
185
+ return child.exitCode === null && child.signalCode === null;
186
+ return alive(pid) && (await browserPid(port)) === pid;
187
+ };
188
+ return {
189
+ name: "cdp",
190
+ caps: CAPS,
191
+ ...(downloads ? { downloads } : {}),
192
+ async create(spec) {
193
+ if ("endpoint" in options)
194
+ return { id: `endpoint:${spec.tag}`, tag: spec.tag };
195
+ const { executablePath, profileRoot, headless = true, args = [] } = options.chrome;
196
+ const sandbox = options.chrome.sandbox ?? process.env.PI_BROWSER_NO_SANDBOX !== "1";
197
+ const dir = profileDir(profileRoot, spec.tag);
198
+ await mkdir(path.join(dir, "Default"), { recursive: true });
199
+ await mkdir(downloadsDir(profileRoot, spec.tag), { recursive: true });
200
+ await writeFile(path.join(dir, "Default", "Preferences"), JSON.stringify({ download: { default_directory: downloadsDir(profileRoot, spec.tag), prompt_for_download: false }, savefile: { default_directory: downloadsDir(profileRoot, spec.tag) } }));
201
+ // A file left by an earlier Chrome on this profile names a browser that is not this one.
202
+ await rm(path.join(dir, "DevToolsActivePort"), { force: true });
203
+ const child = spawn(executablePath, [
204
+ ...CHROME_FLAGS, ...(sandbox ? [] : ["--no-sandbox"]), ...(headless ? ["--headless=new"] : []), "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", `--user-data-dir=${dir}`,
205
+ `--window-size=${spec.viewport.width},${spec.viewport.height}`, ...args, "about:blank",
206
+ ], { stdio: "ignore", detached: true });
207
+ // A Chrome that cannot start emits `error`, which unhandled would end the host: it rejects create instead.
208
+ let failed = null;
209
+ child.once("error", (error) => { failed = error; });
210
+ child.once("exit", (code, signal) => {
211
+ // A Chrome that cannot start its sandbox aborts (SIGABRT) before it opens a port: the signal is the fact, never
212
+ // Chrome's words.
213
+ failed ??= sandbox && signal === "SIGABRT"
214
+ ? new BrowserFailureError({ ok: false, code: "browser_unavailable", retryable: false, effect: "none", message: `Chrome exited before it opened its debugging port (SIGABRT); on a system that cannot start Chrome's sandbox (root, a container, restricted user namespaces) start it with sandbox: false or PI_BROWSER_NO_SANDBOX=1` })
215
+ : new Error(`Chrome exited before it opened its debugging port (${signal ?? code})`);
216
+ });
217
+ if (child.pid === undefined) {
218
+ await sleep(0);
219
+ const left = await removeAll([dir, downloadsDir(profileRoot, spec.tag)], remove);
220
+ const why = failed ?? new Error("Chrome could not be started");
221
+ throw left ? new ProfileNotRemovedError(left.dirs, left.error, why) : why;
222
+ }
223
+ child.unref();
224
+ children.set(child.pid, child);
225
+ // The lease is that Chrome only once the browser answering on the port is the one its profile file names, so a
226
+ // port another browser holds is never taken for it.
227
+ try {
228
+ for (const deadline = Date.now() + READY_MS;; await sleep(100)) {
229
+ if (failed)
230
+ throw failed;
231
+ const own = await ownDebugger(dir);
232
+ if (own && (await answeringPath(own.port)) === own.path)
233
+ return { id: `local:${child.pid}:${own.port}:${spec.tag}`, tag: spec.tag };
234
+ if (Date.now() > deadline)
235
+ throw new Error("Chrome did not open its debugging port");
236
+ }
237
+ }
238
+ catch (error) {
239
+ const kept = await this.release({ id: `local:${child.pid}:0:${spec.tag}`, tag: spec.tag }).then(() => null, (failure) => failure);
240
+ const left = await removeAll([downloadsDir(profileRoot, spec.tag)], remove);
241
+ if (kept && !(kept instanceof ProfileNotRemovedError))
242
+ throw kept;
243
+ const dirs = [...(kept instanceof ProfileNotRemovedError ? kept.dirs : []), ...(left?.dirs ?? [])];
244
+ throw dirs.length > 0 ? new ProfileNotRemovedError(dirs, kept instanceof ProfileNotRemovedError ? kept.cause : left.error, error) : error;
245
+ }
246
+ },
247
+ async findByTag() { return []; },
248
+ async status(ref) {
249
+ const local = parse(ref.id);
250
+ // A local-shaped id this provider cannot read names no process it can vouch for: gone, never "running" unchecked.
251
+ if (!local)
252
+ return ref.id.startsWith("local:") ? "gone" : "running";
253
+ return (await isOurs(local)) ? "running" : "gone";
254
+ },
255
+ async attach(ref) {
256
+ if ("endpoint" in options)
257
+ return { sdkCdpUrl: await debuggerUrl(options.endpoint), ...(options.extensionId ? { extensionId: options.extensionId } : {}) };
258
+ const local = parse(ref.id);
259
+ if (!local)
260
+ throw new Error("not a cdp lease");
261
+ const own = await ownDebugger(profileDir(options.chrome.profileRoot, local.tag));
262
+ if (!own || own.port !== local.port)
263
+ throw new Error("this lease's profile records a different browser than the one its id names");
264
+ const url = await debuggerUrl(`http://127.0.0.1:${local.port}`);
265
+ if (new URL(url).pathname !== own.path)
266
+ throw new Error(`the browser on port ${local.port} is not the browser this lease's profile records`);
267
+ return { sdkCdpUrl: url };
268
+ },
269
+ async release(ref) {
270
+ const local = parse(ref.id);
271
+ if (!local || local.tag !== ref.tag)
272
+ return;
273
+ const ours = await isOurs(local);
274
+ // A profile that a live browser this ref does not name still runs on is that browser's: nothing is removed. A port
275
+ // that holds the probe past PROBE_MS cannot be ruled out, so the profile stays and the release says so.
276
+ if (!ours && !("endpoint" in options) && SAFE_TAG.test(local.tag)) {
277
+ const dir = profileDir(options.chrome.profileRoot, local.tag);
278
+ const own = await ownDebugger(dir);
279
+ if (own) {
280
+ const answer = await debuggerUrl(`http://127.0.0.1:${own.port}`, AbortSignal.timeout(PROBE_MS))
281
+ .then((url) => new URL(url).pathname, (error) => (error instanceof Error && error.name === "TimeoutError" ? undefined : null));
282
+ if (answer === own.path)
283
+ return;
284
+ if (answer === undefined)
285
+ throw new ProfileOwnershipUnclearError(dir, own.port);
286
+ }
287
+ }
288
+ if (ours) {
289
+ await killTree(local.pid);
290
+ const child = children.get(local.pid);
291
+ children.delete(local.pid);
292
+ // The child is unref'd, so a bare wait on its exit could let a process whose last await is this release end
293
+ // early (exit 13): a timer keeps the loop alive. Without a handle the pid is polled until gone.
294
+ if (child && child.exitCode === null && child.signalCode === null)
295
+ await new Promise((resolve) => { const timer = setTimeout(resolve, 5_000); child.once("exit", () => { clearTimeout(timer); resolve(); }); });
296
+ else
297
+ for (const deadline = Date.now() + 5_000; alive(local.pid) && Date.now() < deadline;)
298
+ await sleep(50);
299
+ }
300
+ // The profile goes even after a crash; a tag that is not one path segment names nothing this provider made, so
301
+ // nothing is removed.
302
+ if (!("endpoint" in options) && SAFE_TAG.test(local.tag)) {
303
+ const dir = profileDir(options.chrome.profileRoot, local.tag);
304
+ const socketDir = (await singletonDir(dir)) ?? socketsLeft.get(local.tag) ?? null;
305
+ // Both are always tried, the profile first named: the profile's link is the only place the socket directory's name is read, so it is
306
+ // reported here with the profile's, not left for a later release to miss.
307
+ const left = await removeAll([dir, ...(socketDir ? [socketDir] : [])], remove);
308
+ if (socketDir && left?.dirs.includes(socketDir))
309
+ socketsLeft.set(local.tag, socketDir);
310
+ else
311
+ socketsLeft.delete(local.tag);
312
+ if (left)
313
+ throw new ProfileNotRemovedError(left.dirs, left.error);
314
+ }
315
+ },
316
+ };
317
+ }
318
+ /** Finished files only: Chrome writes `.crdownload` while it works. */
319
+ function localDownloads(profileRoot) {
320
+ const inside = (ref, name) => { if (name !== path.basename(name) || !name)
321
+ throw new Error("not a download name"); return path.join(downloadsDir(profileRoot, ref.tag), name); };
322
+ return {
323
+ async list(ref) {
324
+ const dir = downloadsDir(profileRoot, ref.tag);
325
+ const rows = [];
326
+ for (const name of await readdir(dir).catch(() => [])) {
327
+ if (name.endsWith(".crdownload") || name.startsWith("."))
328
+ continue;
329
+ const info = await stat(path.join(dir, name)).catch(() => null);
330
+ if (info?.isFile())
331
+ rows.push({ name, sizeBytes: info.size, modifiedAt: info.mtime.toISOString() });
332
+ }
333
+ return rows.sort((a, b) => a.name.localeCompare(b.name));
334
+ },
335
+ async read(ref, name, maxBytes) {
336
+ const file = await open(inside(ref, name), "r");
337
+ return (async function* () {
338
+ try {
339
+ let total = 0;
340
+ for await (const chunk of file.createReadStream()) {
341
+ total += chunk.byteLength;
342
+ if (total > maxBytes)
343
+ throw new Error(`larger than the ${maxBytes}-byte limit`);
344
+ yield chunk;
345
+ }
346
+ }
347
+ finally {
348
+ await file.close().catch(() => undefined);
349
+ }
350
+ })();
351
+ },
352
+ };
353
+ }
@@ -0,0 +1,2 @@
1
+ export declare function directFetch(): Promise<((input: any, init?: any) => Promise<any>) | undefined>;
2
+ export declare function closeDirectFetch(): Promise<void>;
@@ -0,0 +1,21 @@
1
+ import nodeModule from "node:module";
2
+ const require = nodeModule.createRequire(import.meta.url);
3
+ let undiciModule;
4
+ /** Loaded on first use, so a process that never reaches a provider never loads undici. */
5
+ const undiciDoor = () => (undiciModule ??= require("undici"));
6
+ let directAgent;
7
+ export async function directFetch() {
8
+ try {
9
+ const undici = undiciDoor();
10
+ // Userland undici refuses a request body it must stream (the extension upload's multipart file) without `duplex`.
11
+ return (input, init = {}) => undici.fetch(input, { ...init, dispatcher: (directAgent ??= new undici.Agent()), ...(init.body ? { duplex: "half" } : {}) });
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ }
17
+ export async function closeDirectFetch() {
18
+ const agent = directAgent;
19
+ directAgent = undefined;
20
+ await agent?.close();
21
+ }
@@ -0,0 +1,49 @@
1
+ import type { BrowserProvider, SessionSpec } from "../core/host.js";
2
+ export declare const KERNEL_BASE_URL = "https://api.onkernel.com";
3
+ export declare const KERNEL_IDLE_MIN_S = 10;
4
+ export declare const KERNEL_IDLE_MAX_S = 259200;
5
+ type HttpFetch = (input: string, init: {
6
+ method: string;
7
+ headers: Record<string, string>;
8
+ body?: Uint8Array | string;
9
+ signal?: AbortSignal;
10
+ }) => Promise<Response>;
11
+ export type KernelOptions = {
12
+ /** KERNEL_API_KEY and KERNEL_BASE_URL (default https://api.onkernel.com). Default: process.env. */
13
+ env?: NodeJS.ProcessEnv;
14
+ /** Kernel's stealth mode, which also turns on its CAPTCHA solver and its stealth proxy. Default false. */
15
+ stealth?: boolean;
16
+ headless?: boolean;
17
+ /** Default: one stored with the same bytes, else uploaded once per process and account. */
18
+ extension?: () => Promise<KernelExtensionRef>;
19
+ confirm?: {
20
+ polls: number;
21
+ intervalMs: number;
22
+ };
23
+ sleep?: (ms: number) => Promise<void>;
24
+ /** Default: a direct undici Agent that never uses HTTP(S)_PROXY; a host behind a proxy passes its own. */
25
+ fetch?: HttpFetch;
26
+ };
27
+ export type KernelProvider = BrowserProvider & {
28
+ readonly name: "kernel";
29
+ };
30
+ export type KernelExtensionRef = {
31
+ id: string;
32
+ } | {
33
+ name: string;
34
+ };
35
+ /** The call and the HTTP status, plus Kernel's error code when it is a plain identifier. Kernel's message is never
36
+ * copied: an echo of the request could carry the key or a URL. */
37
+ export declare class KernelError extends Error {
38
+ readonly status: number | undefined;
39
+ constructor(call: string, status: number | undefined, code?: string, options?: {
40
+ cause?: unknown;
41
+ });
42
+ }
43
+ export declare function kernelCreateBody(spec: SessionSpec, options?: {
44
+ stealth?: boolean;
45
+ headless?: boolean;
46
+ extension?: KernelExtensionRef;
47
+ }): Record<string, unknown>;
48
+ export declare function kernelProvider(options?: KernelOptions): KernelProvider;
49
+ export {};