@parcha/pi-browser 0.1.0-beta.34 → 0.1.0-beta.36

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 (54) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +23 -44
  3. package/dist/core/contract.d.ts +9 -6
  4. package/dist/core/contract.js +8 -29
  5. package/dist/core/driving-guard.d.ts +1 -1
  6. package/dist/core/driving-guard.js +1 -1
  7. package/dist/core/evidence.d.ts +1 -1
  8. package/dist/core/files.d.ts +3 -0
  9. package/dist/core/files.js +4 -1
  10. package/dist/core/host.d.ts +1 -75
  11. package/dist/core/images.d.ts +32 -4
  12. package/dist/core/images.js +81 -16
  13. package/dist/core/redact.d.ts +0 -2
  14. package/dist/core/redact.js +0 -32
  15. package/dist/core/session-control.d.ts +0 -2
  16. package/dist/core/session-control.js +0 -5
  17. package/dist/core/tools.js +4 -1
  18. package/dist/core/usage.d.ts +0 -2
  19. package/dist/core/usage.js +0 -2
  20. package/dist/core/vault.d.ts +0 -10
  21. package/dist/core/vault.js +0 -13
  22. package/dist/core/web.d.ts +2 -111
  23. package/dist/core/web.js +0 -443
  24. package/dist/driver/cdp.js +3 -3
  25. package/dist/driver/page-driver.js +7 -3
  26. package/dist/durable.d.ts +6 -12
  27. package/dist/durable.js +31 -84
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +3 -1
  30. package/dist/providers/cdp.js +2 -2
  31. package/dist/providers/profiles.d.ts +1 -15
  32. package/dist/providers/profiles.js +1 -64
  33. package/dist/providers/shared.d.ts +1 -47
  34. package/dist/providers/shared.js +1 -82
  35. package/dist/providers/worker-extension.js +1 -1
  36. package/dist/testing/backend.d.ts +6 -24
  37. package/dist/testing/backend.js +7 -30
  38. package/dist/vault-session.d.ts +4 -7
  39. package/dist/vault-session.js +26 -81
  40. package/dist/vendor/browser-use-pi/page.d.ts +3 -12
  41. package/dist/vendor/browser-use-pi/page.js +6 -19
  42. package/package.json +3 -16
  43. package/dist/core/sites.d.ts +0 -33
  44. package/dist/core/sites.js +0 -104
  45. package/dist/durable/web.d.ts +0 -47
  46. package/dist/durable/web.js +0 -41
  47. package/dist/providers/browserbase-net.d.ts +0 -12
  48. package/dist/providers/browserbase-net.js +0 -95
  49. package/dist/providers/browserbase.d.ts +0 -169
  50. package/dist/providers/browserbase.js +0 -319
  51. package/dist/providers/kernel.d.ts +0 -58
  52. package/dist/providers/kernel.js +0 -291
  53. /package/dist/{providers → core}/cdp-call.d.ts +0 -0
  54. /package/dist/{providers → core}/cdp-call.js +0 -0
@@ -1,12 +0,0 @@
1
- /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
2
- export declare function rewriteConnectUrl(connectUrl: string, connectBaseUrl: string | undefined | null): string;
3
- /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
4
- * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
5
- export declare function browserbaseNoProxyHosts(env: NodeJS.ProcessEnv): string[];
6
- export declare function applyBrowserbaseNoProxy(env?: NodeJS.ProcessEnv): string[];
7
- /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
8
- * it. */
9
- export declare function bindConnectDial(connectUrl: string, connectBaseUrl: string | null): void;
10
- export declare function unbindConnectDial(connectUrl: string): void;
11
- export declare function connectDialUrl(url: string): string;
12
- export declare function installWebSocketWrapper(): void;
@@ -1,95 +0,0 @@
1
- import { browserbaseHoldings } from "./shared.js";
2
- /** Rewrite a Browserbase connect URL onto the credential proxy: only `*.browserbase.com` hosts, the signing query kept. */
3
- export function rewriteConnectUrl(connectUrl, connectBaseUrl) {
4
- if (!connectUrl || !connectBaseUrl)
5
- return connectUrl;
6
- try {
7
- const target = new URL(connectBaseUrl);
8
- const u = new URL(connectUrl);
9
- if (!/(?:^|\.)browserbase\.com$/i.test(u.hostname))
10
- return connectUrl;
11
- u.protocol = target.protocol;
12
- u.host = target.host;
13
- u.pathname = target.pathname.replace(/\/$/, "") + u.pathname;
14
- return u.toString();
15
- }
16
- catch {
17
- return connectUrl;
18
- }
19
- }
20
- /** Direct, never through the HTTP(S) env proxy: it rejects CONNECT and the CDP WebSocket cannot ride it. Under `node
21
- * --use-env-proxy` NO_PROXY is re-read per request, so listing these hosts bypasses it. */
22
- export function browserbaseNoProxyHosts(env) {
23
- const hosts = new Set();
24
- for (const key of ["BROWSERBASE_BASE_URL", "BROWSERBASE_CONNECT_BASE_URL"]) {
25
- const raw = String(env[key] || "").trim();
26
- if (!raw)
27
- continue;
28
- try {
29
- hosts.add(new URL(raw).hostname);
30
- }
31
- catch { }
32
- }
33
- if (!String(env.BROWSERBASE_CONNECT_BASE_URL || "").trim())
34
- hosts.add(".browserbase.com");
35
- return [...hosts];
36
- }
37
- export function applyBrowserbaseNoProxy(env = process.env) {
38
- const hosts = browserbaseNoProxyHosts(env);
39
- if (!hosts.length)
40
- return hosts;
41
- for (const target of env === process.env ? [env] : [env, process.env]) {
42
- for (const key of ["NO_PROXY", "no_proxy"]) {
43
- const merged = String(target[key] || "").split(",").map((h) => h.trim()).filter(Boolean);
44
- for (const h of hosts)
45
- if (!merged.includes(h))
46
- merged.push(h);
47
- target[key] = merged.join(",");
48
- }
49
- }
50
- return hosts;
51
- }
52
- /** The driver keeps the raw connect URL (the extension in the cloud browser dials it back and reaches only
53
- * Browserbase); this process's socket dials the proxy, so the rewrite happens at dial time, never in a record. */
54
- /** Per-socket targets, so two providers with different proxies never send one's signed URL to the other's proxy. */
55
- const { boundDials } = browserbaseHoldings;
56
- /** A second provider binding the same URL to a different proxy is refused, never switched: the signed URL would go to
57
- * it. */
58
- export function bindConnectDial(connectUrl, connectBaseUrl) {
59
- const target = connectBaseUrl?.trim() ?? "";
60
- const bound = boundDials.get(connectUrl);
61
- if (bound !== undefined && bound !== target)
62
- throw new Error("this Browserbase session is already attached through another credential proxy");
63
- boundDials.set(connectUrl, target);
64
- }
65
- export function unbindConnectDial(connectUrl) {
66
- boundDials.delete(connectUrl);
67
- if (![...boundDials.values()].some(Boolean))
68
- restoreWebSocket();
69
- }
70
- export function connectDialUrl(url) {
71
- const bound = boundDials.get(url);
72
- if (bound !== undefined)
73
- return bound ? rewriteConnectUrl(url, bound) : url;
74
- return url;
75
- }
76
- /** Wraps the process WebSocket only while a session is bound to a proxy; the native one returns with the last binding. A wrapper
77
- * installed on top cannot be removed, so ours stays under it and, with no bindings, passes every URL through. */
78
- let wrapped = null;
79
- export function installWebSocketWrapper() {
80
- if (typeof globalThis.WebSocket !== "function" || (wrapped && globalThis.WebSocket === wrapped.wrapper))
81
- return;
82
- const original = globalThis.WebSocket;
83
- const wrapper = function (url, protocols) { return new original(connectDialUrl(String(url)), protocols); };
84
- wrapper.prototype = original.prototype;
85
- for (const k of ["CONNECTING", "OPEN", "CLOSING", "CLOSED"])
86
- wrapper[k] = original[k];
87
- globalThis.WebSocket = wrapper;
88
- wrapped = { original, wrapper };
89
- }
90
- function restoreWebSocket() {
91
- if (!wrapped || globalThis.WebSocket !== wrapped.wrapper)
92
- return;
93
- globalThis.WebSocket = wrapped.original;
94
- wrapped = null;
95
- }
@@ -1,169 +0,0 @@
1
- import type { BrowserProvider, Geo, PriceTable, SessionSpec } from "../core/host.js";
2
- import { type CdpSession } from "./cdp-call.js";
3
- import { type ProfileStore } from "./profiles.js";
4
- export { rewriteConnectUrl, browserbaseNoProxyHosts, applyBrowserbaseNoProxy } from "./browserbase-net.js";
5
- export { fileProfileStore, memoryProfileStore, type ProfileStore } from "./profiles.js";
6
- export declare const SEARCH_QUERY_MAX = 200;
7
- export declare const SEARCH_RESULTS_MAX = 25;
8
- export type BrowserbaseSdk = {
9
- sessions: {
10
- create(body: BrowserbaseSessionBody, options?: RequestOptions): Promise<{
11
- id: string;
12
- connectUrl: string;
13
- }>;
14
- list(query: {
15
- q?: string;
16
- status?: string;
17
- }, options?: RequestOptions): Promise<Array<{
18
- id: string;
19
- status?: string;
20
- userMetadata?: Record<string, unknown>;
21
- }>>;
22
- retrieve(id: string, options?: RequestOptions): Promise<{
23
- id: string;
24
- status?: string;
25
- connectUrl?: string;
26
- }>;
27
- update(id: string, body: {
28
- status: "REQUEST_RELEASE";
29
- }, options?: RequestOptions): Promise<unknown>;
30
- debug(id: string, options?: RequestOptions): Promise<{
31
- debuggerFullscreenUrl?: string;
32
- debuggerUrl?: string;
33
- pages?: Array<{
34
- id?: string;
35
- url?: string;
36
- title?: string;
37
- debuggerFullscreenUrl?: string;
38
- }>;
39
- }>;
40
- recording?: {
41
- downloads: {
42
- create(id: string): Promise<{
43
- downloads?: RecordingDownload[];
44
- }>;
45
- list(id: string): Promise<{
46
- downloads?: RecordingDownload[];
47
- }>;
48
- };
49
- };
50
- };
51
- extensions: {
52
- create(body: {
53
- file: unknown;
54
- }, options?: RequestOptions): Promise<{
55
- id: string;
56
- }>;
57
- };
58
- contexts: {
59
- create(body: {
60
- projectId?: string;
61
- }, options?: RequestOptions): Promise<{
62
- id: string;
63
- }>;
64
- };
65
- fetchAPI: {
66
- create(body: {
67
- url: string;
68
- allowRedirects?: boolean;
69
- proxies?: boolean;
70
- format?: string;
71
- }, options?: RequestOptions): Promise<FetchApiResult>;
72
- };
73
- search: {
74
- web(body: {
75
- query: string;
76
- numResults?: number;
77
- }, options?: RequestOptions): Promise<SearchApiResult>;
78
- };
79
- get<T = unknown>(path: string, options?: RequestOptions & {
80
- query?: Record<string, unknown>;
81
- headers?: Record<string, string>;
82
- __binaryResponse?: boolean;
83
- }): Promise<T>;
84
- };
85
- type FetchApiResult = {
86
- statusCode?: unknown;
87
- contentType?: unknown;
88
- content?: unknown;
89
- } | null | undefined;
90
- type SearchRow = {
91
- url?: unknown;
92
- title?: string | null;
93
- author?: string | null;
94
- publishedDate?: string | null;
95
- published?: string | null;
96
- };
97
- type SearchApiResult = {
98
- results?: SearchRow[];
99
- } | null | undefined;
100
- type BrowserbaseSessionBody = {
101
- proxies: boolean | Array<Record<string, unknown>>;
102
- timeout: number;
103
- keepAlive: boolean;
104
- browserSettings: {
105
- solveCaptchas: boolean;
106
- viewport: SessionSpec["viewport"];
107
- verified?: boolean;
108
- context?: {
109
- id: string;
110
- persist: boolean;
111
- };
112
- allowedDomains?: string[];
113
- };
114
- userMetadata: Record<string, string>;
115
- region?: string;
116
- extensionId?: string;
117
- projectId?: string;
118
- };
119
- type RequestOptions = {
120
- maxRetries?: number;
121
- timeout?: number;
122
- signal?: AbortSignal;
123
- };
124
- type RecordingDownload = {
125
- pageId?: string;
126
- status?: string;
127
- downloadUrl?: string;
128
- };
129
- export type BrowserbaseOptions = {
130
- /** Reads BROWSERBASE_API_KEY (or BB_API_KEY), _BASE_URL, _CONNECT_BASE_URL, _PROJECT_ID. Default: process.env. */
131
- env?: NodeJS.ProcessEnv;
132
- client?: BrowserbaseSdk;
133
- /** The Stagehand extension's Browserbase id. Default: uploaded once per process. */
134
- extensionId?: () => Promise<string>;
135
- prices?: Partial<PriceTable>;
136
- downloadBehavior?: (dialUrl: string) => Promise<DownloadSetting | void>;
137
- confirm?: {
138
- polls: number;
139
- intervalMs: number;
140
- };
141
- sleep?: (ms: number) => Promise<void>;
142
- /** Where profile names find their Browserbase contexts. Default: a file under the user's config directory. */
143
- profiles?: ProfileStore;
144
- /** How long a release that saved a profile waits for Browserbase to write the context back. */
145
- profileSettleMs?: number;
146
- };
147
- /** `Browser.setDownloadBehavior` lasts only as long as the socket that sent it, so the socket stays open until
148
- * `close()`. */
149
- export type DownloadSetting = Pick<CdpSession, "close" | "open">;
150
- /** Into `downloadPath` (default `downloads`, Browserbase's synced-downloads rule); the socket stays open. */
151
- export declare const setDownloadBehavior: (url: string, options?: {
152
- downloadPath?: string;
153
- timeoutMs?: number;
154
- }) => Promise<DownloadSetting>;
155
- export type BrowserbaseProvider = BrowserProvider & {
156
- readonly name: "browserbase";
157
- };
158
- /** ISO alpha-2 country, US state abbreviation, upper-case city; no two-letter country, no geolocation. */
159
- export declare function browserbaseGeolocation(raw: Partial<Geo> | null | undefined): Geo | null;
160
- export declare function proxiesField(proxies: SessionSpec["proxies"]): boolean | Array<Record<string, unknown>>;
161
- export declare function sessionCreateBody(spec: SessionSpec, extra?: {
162
- extensionId?: string;
163
- projectId?: string;
164
- context?: {
165
- id: string;
166
- persist: boolean;
167
- };
168
- }): BrowserbaseSessionBody;
169
- export declare function browserbaseProvider(options?: BrowserbaseOptions): BrowserbaseProvider;
@@ -1,319 +0,0 @@
1
- // Credentials come from the host's env and live in this module's memory only: a ref is `{ id, tag }`, and the connect
2
- // URL (it carries a signing key) is held here, found again by `retrieve` after a restart.
3
- import { createReadStream } from "node:fs";
4
- import { isRefusal } from "../core/failures.js";
5
- import { fetchUsage, resolvePrices, searchUsage } from "../core/usage.js";
6
- import { cdpCall } from "./cdp-call.js";
7
- import { applyBrowserbaseNoProxy, bindConnectDial, installWebSocketWrapper, rewriteConnectUrl, unbindConnectDial } from "./browserbase-net.js";
8
- import { directFetch } from "./http.js";
9
- import { claimWriter, fileProfileStore, freeWriter, isWriter, noteWriter } from "./profiles.js";
10
- import { accountKey, assertTag, browserbaseHoldings, defaultSleep, DEFAULT_CONFIRM, extensionArchive, nonEmpty, releaseAndConfirm, tagValue, untilAborted, uploadOnce } from "./shared.js";
11
- export { rewriteConnectUrl, browserbaseNoProxyHosts, applyBrowserbaseNoProxy } from "./browserbase-net.js";
12
- export { fileProfileStore, memoryProfileStore } from "./profiles.js";
13
- export const SEARCH_QUERY_MAX = 200;
14
- export const SEARCH_RESULTS_MAX = 25;
15
- /** Into `downloadPath` (default `downloads`, Browserbase's synced-downloads rule); the socket stays open. */
16
- export const setDownloadBehavior = (url, options = {}) => cdpCall(url, "Browser.setDownloadBehavior", { behavior: "allow", downloadPath: options.downloadPath ?? "downloads", eventsEnabled: true }, options.timeoutMs);
17
- const CAPS = { timeoutModel: "wall-clock", maxLifetimeS: 21_600, survivesDisconnect: true, releaseIsAsync: true, profiles: true, extension: "uploaded-per-launch", settings: { proxies: true, verified: true, geolocation: true, region: true, context: true },
18
- // A session is created with `allowedDomains` from the policy's allow list, which Browserbase enforces.
19
- navigationAllow: true };
20
- const notFound = (e) => e?.status === 404;
21
- /** One signal for whichever of these there is (a store may call `make` without its limit). */
22
- const stopWhen = (...signals) => { const some = signals.filter((s) => s !== undefined); return some.length > 1 ? AbortSignal.any(some) : some[0]; };
23
- /** ISO alpha-2 country, US state abbreviation, upper-case city; no two-letter country, no geolocation. */
24
- export function browserbaseGeolocation(raw) {
25
- const country = nonEmpty(raw?.country).toUpperCase();
26
- if (!/^[A-Z]{2}$/.test(country))
27
- return null;
28
- const out = { country };
29
- const state = nonEmpty(raw?.state).toUpperCase();
30
- if (/^[A-Z]{2}$/.test(state))
31
- out.state = state;
32
- const city = nonEmpty(raw?.city).toUpperCase().replace(/[\s-]+/g, "_").replace(/[^A-Z_]/g, "");
33
- if (city)
34
- out.city = city;
35
- return out;
36
- }
37
- export function proxiesField(proxies) {
38
- if (!proxies)
39
- return false;
40
- const geo = typeof proxies === "object" ? browserbaseGeolocation(proxies.geolocation) : null;
41
- return geo ? [{ type: "browserbase", geolocation: geo }] : true;
42
- }
43
- export function sessionCreateBody(spec, extra = {}) {
44
- const settings = {
45
- solveCaptchas: spec.captcha,
46
- viewport: spec.viewport,
47
- ...(spec.verified ? { verified: true } : {}),
48
- ...(extra.context ? { context: extra.context } : spec.contextId ? { context: { id: spec.contextId, persist: true } } : {}),
49
- ...(spec.navigation?.allow?.length ? { allowedDomains: spec.navigation.allow } : {}),
50
- };
51
- const userMetadata = Object.fromEntries(Object.entries(spec.metadata).map(([k, v]) => [k, tagValue(v)]));
52
- return {
53
- proxies: proxiesField(spec.proxies),
54
- timeout: spec.maxLifetimeS,
55
- // Without keepAlive Browserbase ends a session when any CDP client disconnects (a crash, a second client, a closed
56
- // observer); with it only an explicit release or the timeout does.
57
- keepAlive: true,
58
- browserSettings: settings,
59
- userMetadata: { ...userMetadata, agentrun_tag: spec.tag },
60
- ...(spec.region ? { region: spec.region } : {}),
61
- ...(extra.extensionId ? { extensionId: extra.extensionId } : {}),
62
- ...(extra.projectId ? { projectId: extra.projectId } : {}),
63
- };
64
- }
65
- const { connectUrls, settings, opening, uploads } = browserbaseHoldings;
66
- const endSetting = (id) => { settings.get(id)?.close(); settings.delete(id); };
67
- const forget = (id) => { const url = connectUrls.get(id); if (url)
68
- unbindConnectDial(url); connectUrls.delete(id); };
69
- export function browserbaseProvider(options = {}) {
70
- const env = options.env ?? process.env;
71
- const apiKey = nonEmpty(env.BROWSERBASE_API_KEY) || nonEmpty(env.BB_API_KEY);
72
- const baseUrl = nonEmpty(env.BROWSERBASE_BASE_URL) || undefined;
73
- const connectBase = nonEmpty(env.BROWSERBASE_CONNECT_BASE_URL) || null;
74
- const account = accountKey(baseUrl ?? "", apiKey);
75
- const held = (id) => `${account}|${id}`;
76
- const sleep = options.sleep ?? defaultSleep;
77
- const confirm = options.confirm ?? DEFAULT_CONFIRM;
78
- const prices = resolvePrices(options.prices);
79
- const profiles = options.profiles ?? fileProfileStore();
80
- /** The context each live session of this provider runs on, by tag: what a session vault may keep. */
81
- const contexts = new Map();
82
- let sdk = null;
83
- const client = () => (sdk ??= options.client ? Promise.resolve(options.client) : (async () => {
84
- applyBrowserbaseNoProxy(env);
85
- const mod = await import(["@browserbasehq", "sdk"].join("/"));
86
- const Browserbase = mod.default ?? mod.Browserbase;
87
- return new Browserbase({ apiKey, baseURL: baseUrl, fetch: await directFetch() });
88
- })());
89
- const extension = () => options.extensionId
90
- ? options.extensionId()
91
- : uploadOnce(uploads, account, async () => (await (await client()).extensions.create({ file: createReadStream(extensionArchive()) }, { maxRetries: 0 })).id);
92
- const contextFor = (name, projectId, signal) => profiles.resolve(held(`profile:${name}`), async (limit) => (await (await client()).contexts.create({ ...(projectId && !baseUrl && !connectBase ? { projectId } : {}) }, { maxRetries: 0, signal: stopWhen(signal, limit) })).id);
93
- const rows = async (sessionId) => {
94
- const all = [];
95
- for (let offset = 0;;) {
96
- const page = await (await client()).get("/v1/downloads", { query: { sessionId, limit: 100, offset } });
97
- const got = Array.isArray(page?.downloads) ? page.downloads : [];
98
- all.push(...got);
99
- offset += got.length;
100
- if (!got.length || offset >= Number(page?.total ?? 0))
101
- return all;
102
- }
103
- };
104
- const settling = new Set();
105
- const running = (ref) => async (signal) => { if (settling.has(ref.tag))
106
- return true; const now = await status(ref, signal); return now === "running" || now === "pending"; };
107
- /** A saving session's context is written back after it ends, and the next session must not read it before then. */
108
- const finished = async (ref) => {
109
- forget(held(ref.id));
110
- if (isWriter(ref.tag)) {
111
- settling.add(ref.tag);
112
- try {
113
- await sleep(options.profileSettleMs ?? 5_000);
114
- }
115
- finally {
116
- settling.delete(ref.tag);
117
- }
118
- }
119
- freeWriter(ref.tag);
120
- };
121
- const status = async (ref, signal) => {
122
- try {
123
- const found = await (await client()).sessions.retrieve(ref.id, { signal, timeout: 5_000 });
124
- return found.status === "RUNNING" ? "running" : found.status === "PENDING" ? "pending" : "stopped";
125
- }
126
- catch (error) {
127
- if (notFound(error))
128
- return "gone";
129
- throw error;
130
- }
131
- };
132
- return {
133
- name: "browserbase",
134
- caps: CAPS,
135
- vault: { kind: "context", provider: "browserbase", contextIdsInClear: profiles.clear === true, contextOf: (ref) => contexts.get(ref.tag) ?? null },
136
- async create(spec, signal) {
137
- const projectId = nonEmpty(env.BROWSERBASE_PROJECT_ID);
138
- if (spec.profile?.save)
139
- await claimWriter(held(`profile:${spec.profile.name}`), spec.profile.name, spec.tag, `${spec.metadata.run}|${spec.metadata.label}`, signal);
140
- // A context given by id (a vault's kept one) is written back at the end like a profile's: one session at a time saves to it, and the next waits for the write. The id is a capability, so the refusal names no id.
141
- else if (!spec.profile && spec.contextId)
142
- await claimWriter(held(`context:${spec.contextId}`), "the kept context", spec.tag, `${spec.metadata.run}|${spec.metadata.label}`, signal);
143
- let body;
144
- try {
145
- const context = spec.profile ? { id: await contextFor(spec.profile.name, projectId, signal), persist: spec.profile.save } : undefined;
146
- const usedContext = context?.id ?? spec.contextId;
147
- if (usedContext)
148
- contexts.set(spec.tag, usedContext);
149
- // Behind the credential proxy the project is inferred from the injected key and must never be named; a direct key
150
- // must name it.
151
- body = sessionCreateBody(spec, { extensionId: await extension(), ...(projectId && !baseUrl && !connectBase ? { projectId } : {}), ...(context ? { context } : {}) });
152
- }
153
- catch (error) {
154
- freeWriter(spec.tag);
155
- throw error;
156
- }
157
- // At most once: an SDK retry of a create the server already served would open a second paid browser. A failed send keeps
158
- // the profile's claim until findByTag has looked: the session may exist. A refusal (401, 403) made none, so it frees the claim.
159
- const created = await (await client()).sessions.create(body, { maxRetries: 0, signal }).catch((error) => {
160
- if (isRefusal(error))
161
- freeWriter(spec.tag);
162
- throw error;
163
- });
164
- connectUrls.set(held(created.id), created.connectUrl);
165
- noteWriter(spec.tag, running({ id: created.id, tag: spec.tag }), () => sleep(options.profileSettleMs ?? 5_000));
166
- return { id: created.id, tag: spec.tag };
167
- },
168
- async findByTag(tag, signal) {
169
- assertTag(tag);
170
- // `q` alone makes Browserbase answer 504 after 75 s; with a status it answers in about 150 ms. A create whose
171
- // answer was lost may have left the session PENDING, which still bills once it runs, so both statuses are asked.
172
- const q = `user_metadata['agentrun_tag']:'${tag}'`;
173
- const asked = await Promise.all(["RUNNING", "PENDING"].map(async (status) => (await client()).sessions.list({ status, q }, { signal })));
174
- // The query is the provider's, the match is ours: a lane that ignores `q` must never hand back someone else's
175
- // session. Both queries must answer: custody releases exactly these ids, so a failed status throws.
176
- const seen = new Set();
177
- const found = asked.flat().filter((r) => r.userMetadata?.agentrun_tag === tag && !seen.has(r.id) && seen.add(r.id)).map((r) => ({ id: r.id, tag }));
178
- if (!found.length)
179
- freeWriter(tag);
180
- for (const ref of found)
181
- if (isWriter(ref.tag))
182
- noteWriter(ref.tag, running(ref), () => sleep(options.profileSettleMs ?? 5_000));
183
- return found;
184
- },
185
- status,
186
- async attach(ref, signal) {
187
- let url = connectUrls.get(held(ref.id));
188
- if (!url) {
189
- url = (await (await client()).sessions.retrieve(ref.id, { signal })).connectUrl;
190
- if (!url)
191
- throw new Error("Browserbase session is not available for connection");
192
- connectUrls.set(held(ref.id), url);
193
- }
194
- // No `extensionId` on connect: the extension rides the create (given the upload id, connect waited 60 s for a
195
- // worker that never came).
196
- bindConnectDial(url, connectBase);
197
- if (connectBase)
198
- installWebSocketWrapper();
199
- const dial = connectBase ? rewriteConnectUrl(url, connectBase) : url;
200
- // Browserbase syncs a download only when the browser was told to save into `downloads`, which lasts as long as
201
- // that socket: one socket per session is held until release. A failure costs the files, not the session.
202
- const key = held(ref.id);
203
- if (!settings.get(key)?.open) {
204
- let pending = opening.get(key);
205
- if (!pending) {
206
- pending = (async () => { const setting = await (options.downloadBehavior ?? setDownloadBehavior)(dial).catch(() => undefined); if (setting)
207
- settings.set(key, setting); })().finally(() => opening.delete(key));
208
- opening.set(key, pending);
209
- }
210
- await pending;
211
- }
212
- return { sdkCdpUrl: url, ...(connectBase ? { dial: { url: dial } } : {}) };
213
- },
214
- async release(ref, signal) {
215
- contexts.delete(ref.tag);
216
- await opening.get(held(ref.id));
217
- endSetting(held(ref.id));
218
- await releaseAndConfirm({
219
- request: async () => {
220
- try {
221
- await (await client()).sessions.update(ref.id, { status: "REQUEST_RELEASE" }, { maxRetries: 0, signal });
222
- }
223
- catch (error) {
224
- if (notFound(error))
225
- return "gone";
226
- throw error;
227
- }
228
- },
229
- status: () => status(ref, signal),
230
- forget: () => finished(ref),
231
- confirm,
232
- sleep,
233
- stillRunning: `Browserbase session ${ref.id} still running after a release request`,
234
- });
235
- },
236
- async liveView(ref) {
237
- try {
238
- const live = await (await client()).sessions.debug(ref.id);
239
- return {
240
- fullscreen: live.debuggerFullscreenUrl ?? null,
241
- framed: live.debuggerUrl ?? null,
242
- pages: (live.pages ?? []).map((p) => ({ id: p.id ?? null, url: p.url ?? null, title: p.title ?? null, fullscreen: p.debuggerFullscreenUrl ?? null })),
243
- };
244
- }
245
- catch {
246
- return null;
247
- }
248
- },
249
- downloads: {
250
- // Browserbase suffixes each name with a timestamp, so a name is unique in a session.
251
- async list(ref) {
252
- return (await rows(ref.id)).map((d) => ({ name: d.filename, sizeBytes: d.size, modifiedAt: d.createdAt ?? null }));
253
- },
254
- async read(ref, name, maxBytes) {
255
- const row = (await rows(ref.id)).find((d) => d.filename === name);
256
- if (!row)
257
- throw new Error(`no download ${name} for session ${ref.id}`);
258
- const response = await (await client()).get(`/v1/downloads/${encodeURIComponent(row.id)}`, { headers: { Accept: "application/octet-stream" }, __binaryResponse: true });
259
- if (!response?.body)
260
- throw new Error("the download came back empty");
261
- return (async function* () {
262
- let total = 0;
263
- for await (const chunk of response.body) {
264
- total += chunk.byteLength;
265
- if (total > maxBytes)
266
- throw new Error(`larger than the ${maxBytes}-byte limit`);
267
- yield chunk;
268
- }
269
- })();
270
- },
271
- },
272
- recordings: {
273
- // One entry per rendered tab MP4 of an ended session; asking renders them, so a caller polls `list` until it
274
- // fills.
275
- async list(ref) {
276
- const rec = (await client()).sessions.recording?.downloads;
277
- if (!rec)
278
- return [];
279
- let downloads = (await rec.list(ref.id)).downloads ?? [];
280
- if (!downloads.length || downloads.some((d) => d.status === "NOT_REQUESTED"))
281
- downloads = (await rec.create(ref.id)).downloads ?? downloads;
282
- return downloads.filter((d) => d.status === "COMPLETED" && d.downloadUrl).map((d) => ({ id: String(d.pageId), startedAt: null, durationS: null }));
283
- },
284
- async open(ref, id) {
285
- const rec = (await client()).sessions.recording?.downloads;
286
- const found = (await rec?.list(ref.id))?.downloads?.find((d) => String(d.pageId) === id && d.status === "COMPLETED" && d.downloadUrl);
287
- if (!found?.downloadUrl)
288
- throw new Error(`no rendered recording ${id} for session ${ref.id}`);
289
- const response = await (await directFetch())(found.downloadUrl);
290
- if (!response.ok || !response.body)
291
- throw new Error(`recording download answered ${response.status}`);
292
- return response.body;
293
- },
294
- },
295
- async fetch(request, signal) {
296
- signal?.throwIfAborted();
297
- const result = await untilAborted((async () => (await client()).fetchAPI.create({ url: request.url, proxies: request.proxies, allowRedirects: true, format: request.format }, { signal }))(), signal);
298
- // The Fetch API reports no final URL.
299
- return { finalUrl: null, statusCode: Number(result?.statusCode) || null, contentType: typeof result?.contentType === "string" ? result.contentType : null, content: contentText(result?.content), usage: fetchUsage(prices, request.proxies) };
300
- },
301
- async search(request, signal) {
302
- signal?.throwIfAborted();
303
- // The facade validates strictly (query 1 to 200 characters, 1 to 25 results): clamp, so a long query degrades and
304
- // never throws.
305
- const query = request.query.slice(0, SEARCH_QUERY_MAX);
306
- const numResults = Math.max(1, Math.min(SEARCH_RESULTS_MAX, Math.floor(request.n) || 10));
307
- const result = await untilAborted((async () => (await client()).search.web({ query, numResults }, { signal }))(), signal);
308
- const rows = Array.isArray(result?.results) ? result.results : Array.isArray(result) ? result : [];
309
- return { results: rows.filter((r) => typeof r?.url === "string").map((r) => ({ url: r.url, title: r.title ?? null, author: r.author ?? null, published: r.publishedDate ?? r.published ?? null })), usage: searchUsage(prices) };
310
- },
311
- };
312
- }
313
- function contentText(content) {
314
- if (typeof content === "string")
315
- return content;
316
- if (Array.isArray(content))
317
- return content.map((c) => (typeof c === "string" ? c : typeof c?.text === "string" ? c.text : JSON.stringify(c))).join("\n");
318
- return content && typeof content === "object" ? JSON.stringify(content) : "";
319
- }
@@ -1,58 +0,0 @@
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
- /** What the provider reads of a reply: the global fetch's Response and undici's both have it. */
6
- type HttpReply = {
7
- ok: boolean;
8
- status: number;
9
- headers: {
10
- get(name: string): string | null;
11
- };
12
- text(): Promise<string>;
13
- };
14
- type HttpFetch = (input: string, init: {
15
- method: string;
16
- headers: Record<string, string>;
17
- body?: Uint8Array | string;
18
- signal?: AbortSignal;
19
- }) => Promise<HttpReply>;
20
- export type KernelOptions = {
21
- /** KERNEL_API_KEY and KERNEL_BASE_URL (default https://api.onkernel.com). Default: process.env. */
22
- env?: NodeJS.ProcessEnv;
23
- /** Kernel's stealth mode, which also turns on its CAPTCHA solver and its stealth proxy. Default false. */
24
- stealth?: boolean;
25
- headless?: boolean;
26
- /** Default: one stored with the same bytes, else uploaded once per process and account. */
27
- extension?: () => Promise<KernelExtensionRef>;
28
- confirm?: {
29
- polls: number;
30
- intervalMs: number;
31
- };
32
- sleep?: (ms: number) => Promise<void>;
33
- /** Default: a direct undici Agent that never uses HTTP(S)_PROXY; a host behind a proxy passes its own. */
34
- fetch?: HttpFetch;
35
- };
36
- export type KernelProvider = BrowserProvider & {
37
- readonly name: "kernel";
38
- };
39
- export type KernelExtensionRef = {
40
- id: string;
41
- } | {
42
- name: string;
43
- };
44
- /** The call and the HTTP status, plus Kernel's error code when it is a plain identifier. Kernel's message is never
45
- * copied: an echo of the request could carry the key or a URL. */
46
- export declare class KernelError extends Error {
47
- readonly status: number | undefined;
48
- constructor(call: string, status: number | undefined, code?: string, options?: {
49
- cause?: unknown;
50
- });
51
- }
52
- export declare function kernelCreateBody(spec: SessionSpec, options?: {
53
- stealth?: boolean;
54
- headless?: boolean;
55
- extension?: KernelExtensionRef;
56
- }): Record<string, unknown>;
57
- export declare function kernelProvider(options?: KernelOptions): KernelProvider;
58
- export {};