@parcha/pi-browser 0.1.0-beta.30 → 0.1.0-beta.301

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 +239 -0
  2. package/NOTICE +39 -4
  3. package/README.md +125 -236
  4. package/dist/core/contract.d.ts +17 -5
  5. package/dist/core/contract.js +36 -33
  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 +50 -17
  56. package/dist/durable.js +107 -106
  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 -640
  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,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 {};