browser-use-sdk 3.5.0 → 3.6.0

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.
package/README.md CHANGED
@@ -24,6 +24,18 @@ const result = await client.run("Find the top 3 trending repos on GitHub today")
24
24
  console.log(result.output);
25
25
  ```
26
26
 
27
+ ## v3 Bring Your Own LLM Key
28
+
29
+ Add your provider API key in Browser Use project settings, then enable BYOK for v3 agent runs:
30
+
31
+ ```typescript
32
+ import { BrowserUse } from "browser-use-sdk/v3";
33
+
34
+ const client = new BrowserUse({ useOwnKey: true });
35
+ const result = await client.run("Find the top 3 trending repos on GitHub today");
36
+ console.log(result.output);
37
+ ```
38
+
27
39
  ## Docs
28
40
 
29
41
  [docs.browser-use.com](https://docs.browser-use.com)
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/errors.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/core/errors.ts
2
2
  var BrowserUseError = class extends Error {
3
3
 
4
4
 
@@ -16,11 +16,17 @@ var HttpClient = class {
16
16
 
17
17
 
18
18
 
19
+
20
+
19
21
  constructor(options) {
20
22
  this.apiKey = options.apiKey;
21
23
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
22
24
  this.maxRetries = _nullishCoalesce(options.maxRetries, () => ( 3));
23
25
  this.timeout = _nullishCoalesce(options.timeout, () => ( 3e4));
26
+ this.fetchPromise = Promise.resolve(
27
+ _nullishCoalesce(options.fetch, () => ( ((input, init) => fetch(input, init))))
28
+ );
29
+ this.useApiKeyHeader = options.apiKey !== "";
24
30
  }
25
31
  async request(method, path, options) {
26
32
  const url = new URL(`${this.baseUrl}${path}`);
@@ -31,9 +37,10 @@ var HttpClient = class {
31
37
  }
32
38
  }
33
39
  }
34
- const headers = {
35
- "X-Browser-Use-API-Key": this.apiKey
36
- };
40
+ const headers = {};
41
+ if (this.useApiKeyHeader) {
42
+ headers["X-Browser-Use-API-Key"] = this.apiKey;
43
+ }
37
44
  if (_optionalChain([options, 'optionalAccess', _2 => _2.body]) !== void 0) {
38
45
  headers["Content-Type"] = "application/json";
39
46
  }
@@ -46,7 +53,8 @@ var HttpClient = class {
46
53
  const timeoutId = _optionalChain([options, 'optionalAccess', _3 => _3.signal]) ? void 0 : setTimeout(() => controller.abort(), this.timeout);
47
54
  const signal = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.signal]), () => ( controller.signal));
48
55
  try {
49
- const response = await fetch(url.toString(), {
56
+ const fetchImpl = await this.fetchPromise;
57
+ const response = await fetchImpl(url.toString(), {
50
58
  method,
51
59
  headers,
52
60
  body: _optionalChain([options, 'optionalAccess', _5 => _5.body]) !== void 0 ? JSON.stringify(options.body) : void 0,
@@ -66,7 +74,7 @@ var HttpClient = class {
66
74
  let errorBody;
67
75
  try {
68
76
  errorBody = await response.json();
69
- } catch (e) {
77
+ } catch (e2) {
70
78
  }
71
79
  const raw = typeof errorBody === "object" && errorBody !== null ? "message" in errorBody ? errorBody.message : "detail" in errorBody ? errorBody.detail : void 0 : void 0;
72
80
  const message = raw === void 0 ? `HTTP ${response.status}` : typeof raw === "string" ? raw : JSON.stringify(raw);
@@ -92,8 +100,43 @@ var HttpClient = class {
92
100
  }
93
101
  };
94
102
 
103
+ // src/core/x402.ts
104
+ var X402_BASE_URL_DEFAULT = "https://x402.api.browser-use.com/api/v3";
105
+ var X402_BASE_URL_DEFAULT_V2 = "https://x402.api.browser-use.com/api/v2";
106
+ var MISSING_X402 = "x402 mode requires the optional peer deps. Install them with: npm install @x402/fetch @x402/evm viem (or the equivalent for pnpm/yarn).";
107
+ async function x402ClientFromPrivateKey(privateKey) {
108
+ let viem;
109
+ let fetchPkg;
110
+ let evmPkg;
111
+ try {
112
+ viem = await Promise.resolve().then(() => _interopRequireWildcard(require("viem/accounts")));
113
+ fetchPkg = await Promise.resolve().then(() => _interopRequireWildcard(require("@x402/fetch")));
114
+ evmPkg = await Promise.resolve().then(() => _interopRequireWildcard(require("@x402/evm")));
115
+ } catch (e) {
116
+ throw new Error(MISSING_X402);
117
+ }
118
+ const key = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
119
+ const signer = viem.privateKeyToAccount(key);
120
+ const client = new fetchPkg.x402Client();
121
+ client.register("eip155:*", new evmPkg.ExactEvmScheme(signer));
122
+ return client;
123
+ }
124
+ async function wrapFetchWithX402(fetch2, x402Client) {
125
+ let fetchPkg;
126
+ try {
127
+ fetchPkg = await Promise.resolve().then(() => _interopRequireWildcard(require("@x402/fetch")));
128
+ } catch (e) {
129
+ throw new Error(MISSING_X402);
130
+ }
131
+ return fetchPkg.wrapFetchWithPayment(fetch2, x402Client);
132
+ }
133
+
134
+
135
+
136
+
137
+
95
138
 
96
139
 
97
140
 
98
- exports.BrowserUseError = BrowserUseError; exports.HttpClient = HttpClient;
99
- //# sourceMappingURL=chunk-JT4IL3IZ.cjs.map
141
+ exports.BrowserUseError = BrowserUseError; exports.HttpClient = HttpClient; exports.X402_BASE_URL_DEFAULT = X402_BASE_URL_DEFAULT; exports.X402_BASE_URL_DEFAULT_V2 = X402_BASE_URL_DEFAULT_V2; exports.x402ClientFromPrivateKey = x402ClientFromPrivateKey; exports.wrapFetchWithX402 = wrapFetchWithX402;
142
+ //# sourceMappingURL=chunk-4BAZFOC2.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/chunk-4BAZFOC2.cjs","../src/core/errors.ts","../src/core/http.ts","../src/core/x402.ts"],"names":[],"mappings":"AAAA;ACAO,IAAM,gBAAA,EAAN,MAAA,QAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,WAAA,CAAY,UAAA,EAAoB,OAAA,EAAiB,MAAA,EAAkB;AACjE,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,KAAA,EAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,WAAA,EAAa,UAAA;AAClB,IAAA,IAAA,CAAK,OAAA,EAAS,MAAA;AAAA,EAChB;AACF,CAAA;ADCA;AACA;AEKO,IAAM,WAAA,EAAN,MAAiB;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,WAAA,CAAY,OAAA,EAA4B;AACtC,IAAA,IAAA,CAAK,OAAA,EAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,QAAA,EAAU,OAAA,CAAQ,OAAA,CAAQ,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AACjD,IAAA,IAAA,CAAK,WAAA,mBAAa,OAAA,CAAQ,UAAA,UA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AA;AAC5C,IAAA;AACzB,EAAA;AACF;AFjDyB;AACA;AGpFZ;AACA;AAGX;AAKoB;AAGhB,EAAA;AACA,EAAA;AACA,EAAA;AACA,EAAA;AAEkB,IAAA;AAEH,IAAA;AAEF,IAAA;AACL,EAAA;AACM,IAAA;AAClB,EAAA;AAEuB,EAAA;AACH,EAAA;AACD,EAAA;AACH,EAAA;AACT,EAAA;AACT;AAGsB;AAIhB,EAAA;AACA,EAAA;AAEe,IAAA;AACP,EAAA;AACM,IAAA;AAClB,EAAA;AACgB,EAAA;AAClB;AHoEyB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/chunk-4BAZFOC2.cjs","sourcesContent":[null,"export class BrowserUseError extends Error {\n readonly statusCode: number;\n readonly detail: unknown;\n\n constructor(statusCode: number, message: string, detail?: unknown) {\n super(message);\n this.name = \"BrowserUseError\";\n this.statusCode = statusCode;\n this.detail = detail;\n }\n}\n","import { BrowserUseError } from \"./errors.js\";\nimport type { FetchLike } from \"./x402.js\";\n\nexport interface HttpClientOptions {\n apiKey: string;\n baseUrl: string;\n maxRetries?: number;\n timeout?: number;\n /**\n * Optional custom fetch implementation. May be a sync value or a Promise\n * (for lazy resolution of e.g. x402-wrapped fetch). When set, replaces\n * `globalThis.fetch`. The `X-Browser-Use-API-Key` header is still sent if\n * `apiKey` is non-empty (top-up mode in x402); pass `apiKey: \"\"` to omit.\n */\n fetch?: FetchLike | Promise<FetchLike>;\n}\n\nexport class HttpClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly maxRetries: number;\n private readonly timeout: number;\n private readonly fetchPromise: Promise<FetchLike>;\n private readonly useApiKeyHeader: boolean;\n\n constructor(options: HttpClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.maxRetries = options.maxRetries ?? 3;\n this.timeout = options.timeout ?? 30_000;\n this.fetchPromise = Promise.resolve(\n options.fetch ?? ((input, init) => fetch(input, init)),\n );\n // Send the API key header whenever apiKey is non-empty. In x402 mode\n // an empty apiKey means \"accountless\" (wallet is identity); a non-empty\n // apiKey means \"top up the existing key's project\".\n this.useApiKeyHeader = options.apiKey !== \"\";\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n query?: Record<string, unknown>;\n signal?: AbortSignal;\n },\n ): Promise<T> {\n const url = new URL(`${this.baseUrl}${path}`);\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n const headers: Record<string, string> = {};\n if (this.useApiKeyHeader) {\n headers[\"X-Browser-Use-API-Key\"] = this.apiKey;\n }\n if (options?.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n const delay = Math.min(1000 * 2 ** (attempt - 1), 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const controller = new AbortController();\n const timeoutId = options?.signal\n ? undefined\n : setTimeout(() => controller.abort(), this.timeout);\n\n // Combine user signal with internal timeout when both are present\n const signal = options?.signal ?? controller.signal;\n\n try {\n const fetchImpl = await this.fetchPromise;\n const response = await fetchImpl(url.toString(), {\n method,\n headers,\n body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n if (response.status === 204) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n const shouldRetry =\n response.status === 429 &&\n attempt < this.maxRetries;\n\n if (shouldRetry) {\n continue;\n }\n\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n /* ignore parse errors */\n }\n const raw =\n typeof errorBody === \"object\" && errorBody !== null\n ? \"message\" in errorBody\n ? (errorBody as Record<string, unknown>).message\n : \"detail\" in errorBody\n ? (errorBody as Record<string, unknown>).detail\n : undefined\n : undefined;\n const message =\n raw === undefined\n ? `HTTP ${response.status}`\n : typeof raw === \"string\"\n ? raw\n : JSON.stringify(raw);\n throw new BrowserUseError(response.status, message, errorBody);\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n }\n\n throw new Error(\"Unreachable: retry loop exhausted\");\n }\n\n get<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"GET\", path, { query });\n }\n\n post<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"POST\", path, { body, query });\n }\n\n patch<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body, query });\n }\n\n delete<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"DELETE\", path, { query });\n }\n}\n","/**\n * Helpers for the optional x402 (pay-per-request) integration.\n *\n * x402 is an HTTP payment protocol: instead of an API key, requests are\n * authenticated by signing a small USDC payment. See the docs at\n * `cloud/guides/x402` and https://www.x402.org for details.\n *\n * The peer deps `@x402/fetch`, `@x402/evm`, and `viem` are optional. They are\n * imported lazily so users who only use API-key auth never pay the cost.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type X402Client = any;\nexport type FetchLike = (\n input: RequestInfo | URL,\n init?: RequestInit,\n) => Promise<Response>;\n\nexport const X402_BASE_URL_DEFAULT = \"https://x402.api.browser-use.com/api/v3\";\nexport const X402_BASE_URL_DEFAULT_V2 = \"https://x402.api.browser-use.com/api/v2\";\n\nconst MISSING_X402 =\n \"x402 mode requires the optional peer deps. Install them with: \" +\n \"npm install @x402/fetch @x402/evm viem \" +\n \"(or the equivalent for pnpm/yarn).\";\n\n/** Build a ready-to-use x402 client from an EVM private key (`0x...`). */\nexport async function x402ClientFromPrivateKey(\n privateKey: `0x${string}` | string,\n): Promise<X402Client> {\n let viem;\n let fetchPkg;\n let evmPkg;\n try {\n // @ts-ignore - optional peer dep, may not be installed\n viem = await import(\"viem/accounts\");\n // @ts-ignore - optional peer dep, may not be installed\n fetchPkg = await import(\"@x402/fetch\");\n // @ts-ignore - optional peer dep, may not be installed\n evmPkg = await import(\"@x402/evm\");\n } catch (e) {\n throw new Error(MISSING_X402);\n }\n\n const key = privateKey.startsWith(\"0x\") ? privateKey : `0x${privateKey}`;\n const signer = viem.privateKeyToAccount(key as `0x${string}`);\n const client = new fetchPkg.x402Client();\n client.register(\"eip155:*\", new evmPkg.ExactEvmScheme(signer));\n return client;\n}\n\n/** Wrap a fetch with x402 payment handling. */\nexport async function wrapFetchWithX402(\n fetch: FetchLike,\n x402Client: X402Client,\n): Promise<FetchLike> {\n let fetchPkg;\n try {\n // @ts-ignore - optional peer dep, may not be installed\n fetchPkg = await import(\"@x402/fetch\");\n } catch (e) {\n throw new Error(MISSING_X402);\n }\n return fetchPkg.wrapFetchWithPayment(fetch, x402Client);\n}\n"]}
@@ -16,11 +16,17 @@ var HttpClient = class {
16
16
  baseUrl;
17
17
  maxRetries;
18
18
  timeout;
19
+ fetchPromise;
20
+ useApiKeyHeader;
19
21
  constructor(options) {
20
22
  this.apiKey = options.apiKey;
21
23
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
22
24
  this.maxRetries = options.maxRetries ?? 3;
23
25
  this.timeout = options.timeout ?? 3e4;
26
+ this.fetchPromise = Promise.resolve(
27
+ options.fetch ?? ((input, init) => fetch(input, init))
28
+ );
29
+ this.useApiKeyHeader = options.apiKey !== "";
24
30
  }
25
31
  async request(method, path, options) {
26
32
  const url = new URL(`${this.baseUrl}${path}`);
@@ -31,9 +37,10 @@ var HttpClient = class {
31
37
  }
32
38
  }
33
39
  }
34
- const headers = {
35
- "X-Browser-Use-API-Key": this.apiKey
36
- };
40
+ const headers = {};
41
+ if (this.useApiKeyHeader) {
42
+ headers["X-Browser-Use-API-Key"] = this.apiKey;
43
+ }
37
44
  if (options?.body !== void 0) {
38
45
  headers["Content-Type"] = "application/json";
39
46
  }
@@ -46,7 +53,8 @@ var HttpClient = class {
46
53
  const timeoutId = options?.signal ? void 0 : setTimeout(() => controller.abort(), this.timeout);
47
54
  const signal = options?.signal ?? controller.signal;
48
55
  try {
49
- const response = await fetch(url.toString(), {
56
+ const fetchImpl = await this.fetchPromise;
57
+ const response = await fetchImpl(url.toString(), {
50
58
  method,
51
59
  headers,
52
60
  body: options?.body !== void 0 ? JSON.stringify(options.body) : void 0,
@@ -92,8 +100,43 @@ var HttpClient = class {
92
100
  }
93
101
  };
94
102
 
103
+ // src/core/x402.ts
104
+ var X402_BASE_URL_DEFAULT = "https://x402.api.browser-use.com/api/v3";
105
+ var X402_BASE_URL_DEFAULT_V2 = "https://x402.api.browser-use.com/api/v2";
106
+ var MISSING_X402 = "x402 mode requires the optional peer deps. Install them with: npm install @x402/fetch @x402/evm viem (or the equivalent for pnpm/yarn).";
107
+ async function x402ClientFromPrivateKey(privateKey) {
108
+ let viem;
109
+ let fetchPkg;
110
+ let evmPkg;
111
+ try {
112
+ viem = await import("viem/accounts");
113
+ fetchPkg = await import("@x402/fetch");
114
+ evmPkg = await import("@x402/evm");
115
+ } catch (e) {
116
+ throw new Error(MISSING_X402);
117
+ }
118
+ const key = privateKey.startsWith("0x") ? privateKey : `0x${privateKey}`;
119
+ const signer = viem.privateKeyToAccount(key);
120
+ const client = new fetchPkg.x402Client();
121
+ client.register("eip155:*", new evmPkg.ExactEvmScheme(signer));
122
+ return client;
123
+ }
124
+ async function wrapFetchWithX402(fetch2, x402Client) {
125
+ let fetchPkg;
126
+ try {
127
+ fetchPkg = await import("@x402/fetch");
128
+ } catch (e) {
129
+ throw new Error(MISSING_X402);
130
+ }
131
+ return fetchPkg.wrapFetchWithPayment(fetch2, x402Client);
132
+ }
133
+
95
134
  export {
96
135
  BrowserUseError,
97
- HttpClient
136
+ HttpClient,
137
+ X402_BASE_URL_DEFAULT,
138
+ X402_BASE_URL_DEFAULT_V2,
139
+ x402ClientFromPrivateKey,
140
+ wrapFetchWithX402
98
141
  };
99
- //# sourceMappingURL=chunk-6TSB5AIP.js.map
142
+ //# sourceMappingURL=chunk-SKUINUZ4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/errors.ts","../src/core/http.ts","../src/core/x402.ts"],"sourcesContent":["export class BrowserUseError extends Error {\n readonly statusCode: number;\n readonly detail: unknown;\n\n constructor(statusCode: number, message: string, detail?: unknown) {\n super(message);\n this.name = \"BrowserUseError\";\n this.statusCode = statusCode;\n this.detail = detail;\n }\n}\n","import { BrowserUseError } from \"./errors.js\";\nimport type { FetchLike } from \"./x402.js\";\n\nexport interface HttpClientOptions {\n apiKey: string;\n baseUrl: string;\n maxRetries?: number;\n timeout?: number;\n /**\n * Optional custom fetch implementation. May be a sync value or a Promise\n * (for lazy resolution of e.g. x402-wrapped fetch). When set, replaces\n * `globalThis.fetch`. The `X-Browser-Use-API-Key` header is still sent if\n * `apiKey` is non-empty (top-up mode in x402); pass `apiKey: \"\"` to omit.\n */\n fetch?: FetchLike | Promise<FetchLike>;\n}\n\nexport class HttpClient {\n private readonly apiKey: string;\n private readonly baseUrl: string;\n private readonly maxRetries: number;\n private readonly timeout: number;\n private readonly fetchPromise: Promise<FetchLike>;\n private readonly useApiKeyHeader: boolean;\n\n constructor(options: HttpClientOptions) {\n this.apiKey = options.apiKey;\n this.baseUrl = options.baseUrl.replace(/\\/+$/, \"\");\n this.maxRetries = options.maxRetries ?? 3;\n this.timeout = options.timeout ?? 30_000;\n this.fetchPromise = Promise.resolve(\n options.fetch ?? ((input, init) => fetch(input, init)),\n );\n // Send the API key header whenever apiKey is non-empty. In x402 mode\n // an empty apiKey means \"accountless\" (wallet is identity); a non-empty\n // apiKey means \"top up the existing key's project\".\n this.useApiKeyHeader = options.apiKey !== \"\";\n }\n\n async request<T>(\n method: string,\n path: string,\n options?: {\n body?: unknown;\n query?: Record<string, unknown>;\n signal?: AbortSignal;\n },\n ): Promise<T> {\n const url = new URL(`${this.baseUrl}${path}`);\n if (options?.query) {\n for (const [key, value] of Object.entries(options.query)) {\n if (value !== undefined && value !== null) {\n url.searchParams.set(key, String(value));\n }\n }\n }\n\n const headers: Record<string, string> = {};\n if (this.useApiKeyHeader) {\n headers[\"X-Browser-Use-API-Key\"] = this.apiKey;\n }\n if (options?.body !== undefined) {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n for (let attempt = 0; attempt <= this.maxRetries; attempt++) {\n if (attempt > 0) {\n const delay = Math.min(1000 * 2 ** (attempt - 1), 10_000);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const controller = new AbortController();\n const timeoutId = options?.signal\n ? undefined\n : setTimeout(() => controller.abort(), this.timeout);\n\n // Combine user signal with internal timeout when both are present\n const signal = options?.signal ?? controller.signal;\n\n try {\n const fetchImpl = await this.fetchPromise;\n const response = await fetchImpl(url.toString(), {\n method,\n headers,\n body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,\n signal,\n });\n\n clearTimeout(timeoutId);\n\n if (response.ok) {\n if (response.status === 204) {\n return undefined as T;\n }\n return (await response.json()) as T;\n }\n\n const shouldRetry =\n response.status === 429 &&\n attempt < this.maxRetries;\n\n if (shouldRetry) {\n continue;\n }\n\n let errorBody: unknown;\n try {\n errorBody = await response.json();\n } catch {\n /* ignore parse errors */\n }\n const raw =\n typeof errorBody === \"object\" && errorBody !== null\n ? \"message\" in errorBody\n ? (errorBody as Record<string, unknown>).message\n : \"detail\" in errorBody\n ? (errorBody as Record<string, unknown>).detail\n : undefined\n : undefined;\n const message =\n raw === undefined\n ? `HTTP ${response.status}`\n : typeof raw === \"string\"\n ? raw\n : JSON.stringify(raw);\n throw new BrowserUseError(response.status, message, errorBody);\n } catch (error) {\n clearTimeout(timeoutId);\n throw error;\n }\n }\n\n throw new Error(\"Unreachable: retry loop exhausted\");\n }\n\n get<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"GET\", path, { query });\n }\n\n post<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"POST\", path, { body, query });\n }\n\n patch<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"PATCH\", path, { body, query });\n }\n\n delete<T>(path: string, query?: Record<string, unknown>): Promise<T> {\n return this.request<T>(\"DELETE\", path, { query });\n }\n}\n","/**\n * Helpers for the optional x402 (pay-per-request) integration.\n *\n * x402 is an HTTP payment protocol: instead of an API key, requests are\n * authenticated by signing a small USDC payment. See the docs at\n * `cloud/guides/x402` and https://www.x402.org for details.\n *\n * The peer deps `@x402/fetch`, `@x402/evm`, and `viem` are optional. They are\n * imported lazily so users who only use API-key auth never pay the cost.\n */\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type X402Client = any;\nexport type FetchLike = (\n input: RequestInfo | URL,\n init?: RequestInit,\n) => Promise<Response>;\n\nexport const X402_BASE_URL_DEFAULT = \"https://x402.api.browser-use.com/api/v3\";\nexport const X402_BASE_URL_DEFAULT_V2 = \"https://x402.api.browser-use.com/api/v2\";\n\nconst MISSING_X402 =\n \"x402 mode requires the optional peer deps. Install them with: \" +\n \"npm install @x402/fetch @x402/evm viem \" +\n \"(or the equivalent for pnpm/yarn).\";\n\n/** Build a ready-to-use x402 client from an EVM private key (`0x...`). */\nexport async function x402ClientFromPrivateKey(\n privateKey: `0x${string}` | string,\n): Promise<X402Client> {\n let viem;\n let fetchPkg;\n let evmPkg;\n try {\n // @ts-ignore - optional peer dep, may not be installed\n viem = await import(\"viem/accounts\");\n // @ts-ignore - optional peer dep, may not be installed\n fetchPkg = await import(\"@x402/fetch\");\n // @ts-ignore - optional peer dep, may not be installed\n evmPkg = await import(\"@x402/evm\");\n } catch (e) {\n throw new Error(MISSING_X402);\n }\n\n const key = privateKey.startsWith(\"0x\") ? privateKey : `0x${privateKey}`;\n const signer = viem.privateKeyToAccount(key as `0x${string}`);\n const client = new fetchPkg.x402Client();\n client.register(\"eip155:*\", new evmPkg.ExactEvmScheme(signer));\n return client;\n}\n\n/** Wrap a fetch with x402 payment handling. */\nexport async function wrapFetchWithX402(\n fetch: FetchLike,\n x402Client: X402Client,\n): Promise<FetchLike> {\n let fetchPkg;\n try {\n // @ts-ignore - optional peer dep, may not be installed\n fetchPkg = await import(\"@x402/fetch\");\n } catch (e) {\n throw new Error(MISSING_X402);\n }\n return fetchPkg.wrapFetchWithPayment(fetch, x402Client);\n}\n"],"mappings":";AAAO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EAChC;AAAA,EACA;AAAA,EAET,YAAY,YAAoB,SAAiB,QAAkB;AACjE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,SAAS;AAAA,EAChB;AACF;;;ACOO,IAAM,aAAN,MAAiB;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,SAA4B;AACtC,SAAK,SAAS,QAAQ;AACtB,SAAK,UAAU,QAAQ,QAAQ,QAAQ,QAAQ,EAAE;AACjD,SAAK,aAAa,QAAQ,cAAc;AACxC,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,eAAe,QAAQ;AAAA,MAC1B,QAAQ,UAAU,CAAC,OAAO,SAAS,MAAM,OAAO,IAAI;AAAA,IACtD;AAIA,SAAK,kBAAkB,QAAQ,WAAW;AAAA,EAC5C;AAAA,EAEA,MAAM,QACJ,QACA,MACA,SAKY;AACZ,UAAM,MAAM,IAAI,IAAI,GAAG,KAAK,OAAO,GAAG,IAAI,EAAE;AAC5C,QAAI,SAAS,OAAO;AAClB,iBAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,KAAK,GAAG;AACxD,YAAI,UAAU,UAAa,UAAU,MAAM;AACzC,cAAI,aAAa,IAAI,KAAK,OAAO,KAAK,CAAC;AAAA,QACzC;AAAA,MACF;AAAA,IACF;AAEA,UAAM,UAAkC,CAAC;AACzC,QAAI,KAAK,iBAAiB;AACxB,cAAQ,uBAAuB,IAAI,KAAK;AAAA,IAC1C;AACA,QAAI,SAAS,SAAS,Q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 * Helpers for the optional x402 (pay-per-request) integration.
3
+ *
4
+ * x402 is an HTTP payment protocol: instead of an API key, requests are
5
+ * authenticated by signing a small USDC payment. See the docs at
6
+ * `cloud/guides/x402` and https://www.x402.org for details.
7
+ *
8
+ * The peer deps `@x402/fetch`, `@x402/evm`, and `viem` are optional. They are
9
+ * imported lazily so users who only use API-key auth never pay the cost.
10
+ */
11
+ type X402Client = any;
12
+ type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
13
+
14
+ interface HttpClientOptions {
15
+ apiKey: string;
16
+ baseUrl: string;
17
+ maxRetries?: number;
18
+ timeout?: number;
19
+ /**
20
+ * Optional custom fetch implementation. May be a sync value or a Promise
21
+ * (for lazy resolution of e.g. x402-wrapped fetch). When set, replaces
22
+ * `globalThis.fetch`. The `X-Browser-Use-API-Key` header is still sent if
23
+ * `apiKey` is non-empty (top-up mode in x402); pass `apiKey: ""` to omit.
24
+ */
25
+ fetch?: FetchLike | Promise<FetchLike>;
26
+ }
27
+ declare class HttpClient {
28
+ private readonly apiKey;
29
+ private readonly baseUrl;
30
+ private readonly maxRetries;
31
+ private readonly timeout;
32
+ private readonly fetchPromise;
33
+ private readonly useApiKeyHeader;
34
+ constructor(options: HttpClientOptions);
35
+ request<T>(method: string, path: string, options?: {
36
+ body?: unknown;
37
+ query?: Record<string, unknown>;
38
+ signal?: AbortSignal;
39
+ }): Promise<T>;
40
+ get<T>(path: string, query?: Record<string, unknown>): Promise<T>;
41
+ post<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
42
+ patch<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
43
+ delete<T>(path: string, query?: Record<string, unknown>): Promise<T>;
44
+ }
45
+
46
+ declare class BrowserUseError extends Error {
47
+ readonly statusCode: number;
48
+ readonly detail: unknown;
49
+ constructor(statusCode: number, message: string, detail?: unknown);
50
+ }
51
+
52
+ export { BrowserUseError as B, HttpClient as H, type X402Client as X };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Helpers for the optional x402 (pay-per-request) integration.
3
+ *
4
+ * x402 is an HTTP payment protocol: instead of an API key, requests are
5
+ * authenticated by signing a small USDC payment. See the docs at
6
+ * `cloud/guides/x402` and https://www.x402.org for details.
7
+ *
8
+ * The peer deps `@x402/fetch`, `@x402/evm`, and `viem` are optional. They are
9
+ * imported lazily so users who only use API-key auth never pay the cost.
10
+ */
11
+ type X402Client = any;
12
+ type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
13
+
14
+ interface HttpClientOptions {
15
+ apiKey: string;
16
+ baseUrl: string;
17
+ maxRetries?: number;
18
+ timeout?: number;
19
+ /**
20
+ * Optional custom fetch implementation. May be a sync value or a Promise
21
+ * (for lazy resolution of e.g. x402-wrapped fetch). When set, replaces
22
+ * `globalThis.fetch`. The `X-Browser-Use-API-Key` header is still sent if
23
+ * `apiKey` is non-empty (top-up mode in x402); pass `apiKey: ""` to omit.
24
+ */
25
+ fetch?: FetchLike | Promise<FetchLike>;
26
+ }
27
+ declare class HttpClient {
28
+ private readonly apiKey;
29
+ private readonly baseUrl;
30
+ private readonly maxRetries;
31
+ private readonly timeout;
32
+ private readonly fetchPromise;
33
+ private readonly useApiKeyHeader;
34
+ constructor(options: HttpClientOptions);
35
+ request<T>(method: string, path: string, options?: {
36
+ body?: unknown;
37
+ query?: Record<string, unknown>;
38
+ signal?: AbortSignal;
39
+ }): Promise<T>;
40
+ get<T>(path: string, query?: Record<string, unknown>): Promise<T>;
41
+ post<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
42
+ patch<T>(path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;
43
+ delete<T>(path: string, query?: Record<string, unknown>): Promise<T>;
44
+ }
45
+
46
+ declare class BrowserUseError extends Error {
47
+ readonly statusCode: number;
48
+ readonly detail: unknown;
49
+ constructor(statusCode: number, message: string, detail?: unknown);
50
+ }
51
+
52
+ export { BrowserUseError as B, HttpClient as H, type X402Client as X };
package/dist/index.cjs CHANGED
@@ -1,7 +1,10 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
2
 
3
3
 
4
- var _chunkJT4IL3IZcjs = require('./chunk-JT4IL3IZ.cjs');
4
+
5
+
6
+
7
+ var _chunk4BAZFOC2cjs = require('./chunk-4BAZFOC2.cjs');
5
8
 
6
9
  // src/v2/client.ts
7
10
  var _zod = require('zod');
@@ -398,18 +401,36 @@ var BrowserUse = class {
398
401
 
399
402
 
400
403
  constructor(options = {}) {
401
- const apiKey = _nullishCoalesce(_nullishCoalesce(options.apiKey, () => ( process.env.BROWSER_USE_API_KEY)), () => ( ""));
402
- if (!apiKey) {
403
- throw new Error(
404
- "No API key provided. Pass apiKey or set BROWSER_USE_API_KEY."
405
- );
404
+ const x402PrivateKey = _nullishCoalesce(options.x402PrivateKey, () => ( process.env.BROWSER_USE_X402_PRIVATE_KEY));
405
+ if (options.x402 || x402PrivateKey) {
406
+ const topupKey = _nullishCoalesce(_nullishCoalesce(options.apiKey, () => ( process.env.BROWSER_USE_API_KEY)), () => ( ""));
407
+ const fetchPromise = (async () => {
408
+ const x402Client = await _asyncNullishCoalesce(options.x402, async () => ( await _chunk4BAZFOC2cjs.x402ClientFromPrivateKey.call(void 0, x402PrivateKey)));
409
+ return _chunk4BAZFOC2cjs.wrapFetchWithX402.call(void 0, globalThis.fetch, x402Client);
410
+ })();
411
+ fetchPromise.catch(() => {
412
+ });
413
+ this.http = new (0, _chunk4BAZFOC2cjs.HttpClient)({
414
+ apiKey: topupKey,
415
+ baseUrl: _nullishCoalesce(options.baseUrl, () => ( _chunk4BAZFOC2cjs.X402_BASE_URL_DEFAULT_V2)),
416
+ maxRetries: options.maxRetries,
417
+ timeout: options.timeout,
418
+ fetch: fetchPromise
419
+ });
420
+ } else {
421
+ const apiKey = _nullishCoalesce(_nullishCoalesce(options.apiKey, () => ( process.env.BROWSER_USE_API_KEY)), () => ( ""));
422
+ if (!apiKey) {
423
+ throw new Error(
424
+ "No credentials provided. Pass apiKey / set BROWSER_USE_API_KEY, or pass x402PrivateKey / set BROWSER_USE_X402_PRIVATE_KEY for pay-per-request access via USDC."
425
+ );
426
+ }
427
+ this.http = new (0, _chunk4BAZFOC2cjs.HttpClient)({
428
+ apiKey,
429
+ baseUrl: _nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL)),
430
+ maxRetries: options.maxRetries,
431
+ timeout: options.timeout
432
+ });
406
433
  }
407
- this.http = new (0, _chunkJT4IL3IZcjs.HttpClient)({
408
- apiKey,
409
- baseUrl: _nullishCoalesce(options.baseUrl, () => ( DEFAULT_BASE_URL)),
410
- maxRetries: options.maxRetries,
411
- timeout: options.timeout
412
- });
413
434
  this.billing = new Billing(this.http);
414
435
  this.tasks = new Tasks(this.http);
415
436
  this.sessions = new Sessions(this.http);
@@ -441,5 +462,5 @@ var BrowserUse = class {
441
462
 
442
463
 
443
464
 
444
- exports.Billing = Billing; exports.BrowserUse = BrowserUse; exports.BrowserUseError = _chunkJT4IL3IZcjs.BrowserUseError; exports.Browsers = Browsers; exports.Files = Files; exports.Marketplace = Marketplace; exports.Profiles = Profiles; exports.Sessions = Sessions; exports.Skills = Skills; exports.TaskRun = TaskRun; exports.Tasks = Tasks;
465
+ exports.Billing = Billing; exports.BrowserUse = BrowserUse; exports.BrowserUseError = _chunk4BAZFOC2cjs.BrowserUseError; exports.Browsers = Browsers; exports.Files = Files; exports.Marketplace = Marketplace; exports.Profiles = Profiles; exports.Sessions = Sessions; exports.Skills = Skills; exports.TaskRun = TaskRun; exports.Tasks = Tasks;
445
466
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/index.cjs","../src/v2/client.ts","../src/v2/resources/billing.ts","../src/v2/resources/browsers.ts","../src/v2/resources/files.ts","../src/v2/resources/marketplace.ts","../src/v2/resources/profiles.ts","../src/v2/resources/sessions.ts","../src/v2/resources/skills.ts","../src/v2/helpers.ts","../src/v2/resources/tasks.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,0BAAkB;ADOlB;AACA;AEHO,IAAM,QAAA,EAAN,MAAc;AAAA,EACnB,WAAA,CAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,CAAA,KAAA,EAAA,IAAA;AAAA,EAAmB;AAAA;AAAA,EAGhD,OAAA,CAAA,EAAgC;AAC9B,IAAA,OAAO,IAAA,CAAK,IAAA,CAAK,GAAA,CAAiB,kBAAkB,CAAA;AAAA,EACtD;AACF,CAAA;AFMA;AACA;AGIO,IAAM,SAAA,EAAN,MAAe;AAAA,EACpB,WAAA,CAA6B,IAAA,EAAkB;AAAlB,IAAA,IAAA,C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A;AACA;AACA","file":"/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/index.cjs","sourcesContent":[null,"import { z } from \"zod\";\nimport { HttpClient } from \"../core/http.js\";\nimport { Billing } from \"./resources/billing.js\";\nimport { Browsers } from \"./resources/browsers.js\";\nimport { Files } from \"./resources/files.js\";\nimport { Marketplace } from \"./resources/marketplace.js\";\nimport { Profiles } from \"./resources/profiles.js\";\nimport { Sessions } from \"./resources/sessions.js\";\nimport { Skills } from \"./resources/skills.js\";\nimport { Tasks } from \"./resources/tasks.js\";\nimport { TaskRun } from \"./helpers.js\";\nimport type { CreateTaskBody } from \"./resources/tasks.js\";\nimport type { RunOptions } from \"./helpers.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.browser-use.com/api/v2\";\n\nexport interface BrowserUseOptions {\n apiKey?: string;\n baseUrl?: string;\n maxRetries?: number;\n timeout?: number;\n}\n\nexport type RunTaskOptions = Partial<Omit<CreateTaskBody, \"task\">> &\n RunOptions & { schema?: z.ZodType };\n\nexport class BrowserUse {\n readonly billing: Billing;\n readonly tasks: Tasks;\n readonly sessions: Sessions;\n readonly files: Files;\n readonly profiles: Profiles;\n readonly browsers: Browsers;\n readonly skills: Skills;\n readonly marketplace: Marketplace;\n\n private readonly http: HttpClient;\n\n constructor(options: BrowserUseOptions = {}) {\n const apiKey =\n options.apiKey ?? process.env.BROWSER_USE_API_KEY ?? \"\";\n if (!apiKey) {\n throw new Error(\n \"No API key provided. Pass apiKey or set BROWSER_USE_API_KEY.\",\n );\n }\n this.http = new HttpClient({\n apiKey,\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n maxRetries: options.maxRetries,\n timeout: options.timeout,\n });\n\n this.billing = new Billing(this.http);\n this.tasks = new Tasks(this.http);\n this.sessions = new Sessions(this.http);\n this.files = new Files(this.http);\n this.profiles = new Profiles(this.http);\n this.browsers = new Browsers(this.http);\n this.skills = new Skills(this.http);\n this.marketplace = new Marketplace(this.http);\n }\n\n /**\n * Run an AI agent task.\n *\n * ```ts\n * // Simple — just get the output\n * const output = await client.run(\"Find the top HN post\");\n *\n * // Structured output (Zod)\n * const data = await client.run(\"Find product info\", { schema: ProductSchema });\n *\n * // Step-by-step progress\n * for await (const step of client.run(\"Go to google.com\")) {\n * console.log(`[${step.number}] ${step.nextGoal}`);\n * }\n * ```\n */\n run(task: string, options?: Omit<RunTaskOptions, \"schema\">): TaskRun<string>;\n run<T extends z.ZodType>(task: string, options: RunTaskOptions & { schema: T }): TaskRun<z.output<T>>;\n run(task: string, options?: RunTaskOptions): TaskRun<any> {\n const { schema, timeout, interval, ...rest } = options ?? {};\n const body: CreateTaskBody = { task, ...rest };\n if (schema) {\n body.structuredOutput = JSON.stringify(z.toJSONSchema(schema));\n }\n const promise = this.tasks.create(body);\n return new TaskRun(promise, this.tasks, schema, { timeout, interval });\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype AccountView = components[\"schemas\"][\"AccountView\"];\n\nexport class Billing {\n constructor(private readonly http: HttpClient) {}\n\n /** Get authenticated account billing information including credit balance. */\n account(): Promise<AccountView> {\n return this.http.get<AccountView>(\"/billing/account\");\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\n/** All fields are optional (server applies defaults); body itself is required by the spec. */\nexport type CreateBrowserBody = Partial<components[\"schemas\"][\"CreateBrowserSessionRequest\"]>;\ntype BrowserSessionItemView = components[\"schemas\"][\"BrowserSessionItemView\"];\ntype BrowserSessionListResponse = components[\"schemas\"][\"BrowserSessionListResponse\"];\ntype BrowserSessionView = components[\"schemas\"][\"BrowserSessionView\"];\ntype UpdateBrowserSessionRequest = components[\"schemas\"][\"UpdateBrowserSessionRequest\"];\ntype BrowserDownloadListResponse = components[\"schemas\"][\"BrowserDownloadListResponse\"];\n\nexport interface BrowserListParams {\n pageSize?: number;\n pageNumber?: number;\n filterBy?: string;\n}\n\nexport interface BrowserDownloadsParams {\n limit?: number;\n cursor?: string;\n includeUrls?: boolean;\n}\n\nexport class Browsers {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new browser session. */\n create(body: CreateBrowserBody = {}): Promise<BrowserSessionItemView> {\n if (body.proxyCountryCode) {\n body = { ...body, proxyCountryCode: body.proxyCountryCode.toLowerCase() as any };\n }\n return this.http.post<BrowserSessionItemView>(\"/browsers\", body);\n }\n\n /** List browser sessions with optional filtering. */\n list(params?: BrowserListParams): Promise<BrowserSessionListResponse> {\n return this.http.get<BrowserSessionListResponse>(\n \"/browsers\",\n params as Record<string, unknown>,\n );\n }\n\n /** Get detailed browser session information. */\n get(sessionId: string): Promise<BrowserSessionView> {\n return this.http.get<BrowserSessionView>(`/browsers/${sessionId}`);\n }\n\n /** Update a browser session (generic PATCH). */\n update(sessionId: string, body: UpdateBrowserSessionRequest): Promise<BrowserSessionView> {\n return this.http.patch<BrowserSessionView>(`/browsers/${sessionId}`, body);\n }\n\n /** Stop a browser session. */\n stop(sessionId: string): Promise<BrowserSessionView> {\n return this.update(sessionId, { action: \"stop\" });\n }\n\n /** List files the browser downloaded to S3 during the session. */\n downloads(sessionId: string, params?: BrowserDownloadsParams): Promise<BrowserDownloadListResponse> {\n return this.http.get<BrowserDownloadListResponse>(\n `/browsers/${sessionId}/downloads`,\n params as Record<string, unknown>,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype UploadFileRequest = components[\"schemas\"][\"UploadFileRequest\"];\ntype UploadFilePresignedUrlResponse = components[\"schemas\"][\"UploadFilePresignedUrlResponse\"];\ntype TaskOutputFileResponse = components[\"schemas\"][\"TaskOutputFileResponse\"];\n\nexport class Files {\n constructor(private readonly http: HttpClient) {}\n\n /** Generate a presigned URL for uploading files to an agent session. */\n sessionUrl(sessionId: string, body: UploadFileRequest): Promise<UploadFilePresignedUrlResponse> {\n return this.http.post<UploadFilePresignedUrlResponse>(\n `/files/sessions/${sessionId}/presigned-url`,\n body,\n );\n }\n\n /** Generate a presigned URL for uploading files to a browser session. */\n browserUrl(sessionId: string, body: UploadFileRequest): Promise<UploadFilePresignedUrlResponse> {\n return this.http.post<UploadFilePresignedUrlResponse>(\n `/files/browsers/${sessionId}/presigned-url`,\n body,\n );\n }\n\n /** Get secure download URL for a task output file. */\n taskOutput(taskId: string, fileId: string): Promise<TaskOutputFileResponse> {\n return this.http.get<TaskOutputFileResponse>(\n `/files/tasks/${taskId}/output-files/${fileId}`,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype ExecuteSkillRequest = components[\"schemas\"][\"ExecuteSkillRequest\"];\ntype ExecuteSkillResponse = components[\"schemas\"][\"ExecuteSkillResponse\"];\ntype MarketplaceSkillListResponse = components[\"schemas\"][\"MarketplaceSkillListResponse\"];\ntype MarketplaceSkillResponse = components[\"schemas\"][\"MarketplaceSkillResponse\"];\ntype SkillResponse = components[\"schemas\"][\"SkillResponse\"];\n\nexport interface MarketplaceListParams {\n pageSize?: number;\n pageNumber?: number;\n query?: string;\n category?: string;\n fromDate?: string;\n toDate?: string;\n}\n\nexport class Marketplace {\n constructor(private readonly http: HttpClient) {}\n\n /** List all public skills in the marketplace. */\n list(params?: MarketplaceListParams): Promise<MarketplaceSkillListResponse> {\n return this.http.get<MarketplaceSkillListResponse>(\n \"/marketplace/skills\",\n params as Record<string, unknown>,\n );\n }\n\n /** Get details of a specific marketplace skill by slug. */\n get(skillSlug: string): Promise<MarketplaceSkillResponse> {\n return this.http.get<MarketplaceSkillResponse>(`/marketplace/skills/${skillSlug}`);\n }\n\n /** Clone a public marketplace skill to your project. */\n clone(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/marketplace/skills/${skillId}/clone`);\n }\n\n /** Execute a marketplace skill. */\n execute(skillId: string, body: ExecuteSkillRequest): Promise<ExecuteSkillResponse> {\n return this.http.post<ExecuteSkillResponse>(\n `/marketplace/skills/${skillId}/execute`,\n body,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype ProfileCreateRequest = components[\"schemas\"][\"ProfileCreateRequest\"];\ntype ProfileListResponse = components[\"schemas\"][\"ProfileListResponse\"];\ntype ProfileUpdateRequest = components[\"schemas\"][\"ProfileUpdateRequest\"];\ntype ProfileView = components[\"schemas\"][\"ProfileView\"];\n\nexport interface ProfileListParams {\n pageSize?: number;\n pageNumber?: number;\n query?: string;\n}\n\nexport class Profiles {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new browser profile. */\n create(body?: ProfileCreateRequest): Promise<ProfileView> {\n return this.http.post<ProfileView>(\"/profiles\", body);\n }\n\n /** List profiles with pagination. */\n list(params?: ProfileListParams): Promise<ProfileListResponse> {\n return this.http.get<ProfileListResponse>(\"/profiles\", params as Record<string, unknown>);\n }\n\n /** Get profile details. */\n get(profileId: string): Promise<ProfileView> {\n return this.http.get<ProfileView>(`/profiles/${profileId}`);\n }\n\n /** Update a browser profile. */\n update(profileId: string, body: ProfileUpdateRequest): Promise<ProfileView> {\n return this.http.patch<ProfileView>(`/profiles/${profileId}`, body);\n }\n\n /** Delete a browser profile. */\n delete(profileId: string): Promise<void> {\n return this.http.delete<void>(`/profiles/${profileId}`);\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\n/** User-facing body: all fields are optional (API has defaults). */\ntype CreateSessionBody = Partial<components[\"schemas\"][\"CreateSessionRequest\"]>;\ntype SessionItemView = components[\"schemas\"][\"SessionItemView\"];\ntype SessionListResponse = components[\"schemas\"][\"SessionListResponse\"];\ntype SessionView = components[\"schemas\"][\"SessionView\"];\ntype ShareView = components[\"schemas\"][\"ShareView\"];\ntype UpdateSessionRequest = components[\"schemas\"][\"UpdateSessionRequest\"];\n\nexport interface SessionListParams {\n pageSize?: number;\n pageNumber?: number;\n filterBy?: string;\n}\n\nexport class Sessions {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new session. */\n create(body?: CreateSessionBody): Promise<SessionItemView> {\n if (body?.proxyCountryCode) {\n body = { ...body, proxyCountryCode: body.proxyCountryCode.toLowerCase() as any };\n }\n return this.http.post<SessionItemView>(\"/sessions\", body);\n }\n\n /** List sessions with optional filtering. */\n list(params?: SessionListParams): Promise<SessionListResponse> {\n return this.http.get<SessionListResponse>(\"/sessions\", params as Record<string, unknown>);\n }\n\n /** Get detailed session information. */\n get(sessionId: string): Promise<SessionView> {\n return this.http.get<SessionView>(`/sessions/${sessionId}`);\n }\n\n /** Update a session (generic PATCH). */\n update(sessionId: string, body: UpdateSessionRequest): Promise<SessionView> {\n return this.http.patch<SessionView>(`/sessions/${sessionId}`, body);\n }\n\n /** Stop a session and all its running tasks. */\n stop(sessionId: string): Promise<SessionView> {\n return this.update(sessionId, { action: \"stop\" });\n }\n\n /** Delete a session with all its tasks. */\n delete(sessionId: string): Promise<void> {\n return this.http.delete<void>(`/sessions/${sessionId}`);\n }\n\n /** Get public share information for a session. */\n getShare(sessionId: string): Promise<ShareView> {\n return this.http.get<ShareView>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Create or return existing public share for a session. */\n createShare(sessionId: string): Promise<ShareView> {\n return this.http.post<ShareView>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Remove public share for a session. */\n deleteShare(sessionId: string): Promise<void> {\n return this.http.delete<void>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Purge all session data (ZDR projects only). */\n purge(sessionId: string): Promise<void> {\n return this.http.post<void>(`/sessions/${sessionId}/purge`);\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype CreateSkillRequest = components[\"schemas\"][\"CreateSkillRequest\"];\ntype CreateSkillResponse = components[\"schemas\"][\"CreateSkillResponse\"];\ntype ExecuteSkillRequest = components[\"schemas\"][\"ExecuteSkillRequest\"];\ntype ExecuteSkillResponse = components[\"schemas\"][\"ExecuteSkillResponse\"];\ntype RefineSkillRequest = components[\"schemas\"][\"RefineSkillRequest\"];\ntype RefineSkillResponse = components[\"schemas\"][\"RefineSkillResponse\"];\ntype SkillExecutionListResponse = components[\"schemas\"][\"SkillExecutionListResponse\"];\ntype SkillExecutionOutputResponse = components[\"schemas\"][\"SkillExecutionOutputResponse\"];\ntype SkillListResponse = components[\"schemas\"][\"SkillListResponse\"];\ntype SkillResponse = components[\"schemas\"][\"SkillResponse\"];\ntype UpdateSkillRequest = components[\"schemas\"][\"UpdateSkillRequest\"];\n\nexport interface SkillListParams {\n pageSize?: number;\n pageNumber?: number;\n isPublic?: boolean;\n isEnabled?: boolean;\n category?: string;\n query?: string;\n fromDate?: string;\n toDate?: string;\n}\n\nexport interface SkillExecutionListParams {\n pageSize?: number;\n pageNumber?: number;\n}\n\nexport class Skills {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new skill via automated generation. */\n create(body: CreateSkillRequest): Promise<CreateSkillResponse> {\n return this.http.post<CreateSkillResponse>(\"/skills\", body);\n }\n\n /** List all skills owned by the project. */\n list(params?: SkillListParams): Promise<SkillListResponse> {\n return this.http.get<SkillListResponse>(\"/skills\", params as Record<string, unknown>);\n }\n\n /** Get details of a specific skill. */\n get(skillId: string): Promise<SkillResponse> {\n return this.http.get<SkillResponse>(`/skills/${skillId}`);\n }\n\n /** Delete a skill. */\n delete(skillId: string): Promise<void> {\n return this.http.delete<void>(`/skills/${skillId}`);\n }\n\n /** Update skill metadata. */\n update(skillId: string, body: UpdateSkillRequest): Promise<SkillResponse> {\n return this.http.patch<SkillResponse>(`/skills/${skillId}`, body);\n }\n\n /** Cancel the current in-progress generation for a skill. */\n cancel(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/skills/${skillId}/cancel`);\n }\n\n /** Execute a skill with the provided parameters. */\n execute(skillId: string, body: ExecuteSkillRequest): Promise<ExecuteSkillResponse> {\n return this.http.post<ExecuteSkillResponse>(`/skills/${skillId}/execute`, body);\n }\n\n /** Refine a skill based on feedback. */\n refine(skillId: string, body: RefineSkillRequest): Promise<RefineSkillResponse> {\n return this.http.post<RefineSkillResponse>(`/skills/${skillId}/refine`, body);\n }\n\n /** Rollback to the previous version. */\n rollback(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/skills/${skillId}/rollback`);\n }\n\n /** List executions for a specific skill. */\n executions(skillId: string, params?: SkillExecutionListParams): Promise<SkillExecutionListResponse> {\n return this.http.get<SkillExecutionListResponse>(\n `/skills/${skillId}/executions`,\n params as Record<string, unknown>,\n );\n }\n\n /** Get presigned URL for downloading skill execution output. */\n executionOutput(skillId: string, executionId: string): Promise<SkillExecutionOutputResponse> {\n return this.http.get<SkillExecutionOutputResponse>(\n `/skills/${skillId}/executions/${executionId}/output`,\n );\n }\n}\n","import type { z } from \"zod\";\nimport type { components } from \"../generated/v2/types.js\";\nimport type { Tasks } from \"./resources/tasks.js\";\n\ntype TaskCreatedResponse = components[\"schemas\"][\"TaskCreatedResponse\"];\ntype TaskStepView = components[\"schemas\"][\"TaskStepView\"];\ntype TaskView = components[\"schemas\"][\"TaskView\"];\n\nexport const TERMINAL_STATUSES = new Set([\"finished\", \"stopped\"]);\n\n/** Task result with typed output. All TaskView fields are directly accessible. */\nexport type TaskResult<T = string | null> = Omit<TaskView, \"output\"> & { output: T };\n\nexport interface RunOptions {\n /** Maximum time to wait in milliseconds. Default: 300_000 (5 min). */\n timeout?: number;\n /** Polling interval in milliseconds. Default: 2_000. */\n interval?: number;\n}\n\n/**\n * Lazy task handle returned by `client.run()`.\n *\n * - `await client.run(...)` polls the lightweight status endpoint, returns a `TaskResult`.\n * - `for await (const step of client.run(...))` polls the full task, yields new steps.\n */\nexport class TaskRun<T = string> implements PromiseLike<TaskResult<T>> {\n private readonly _createPromise: Promise<TaskCreatedResponse>;\n private readonly _tasks: Tasks;\n private readonly _schema?: z.ZodType<T>;\n private readonly _timeout: number;\n private readonly _interval: number;\n\n private _taskId: string | null = null;\n private _result: TaskResult<T> | null = null;\n\n constructor(\n createPromise: Promise<TaskCreatedResponse>,\n tasks: Tasks,\n schema?: z.ZodType<T>,\n options?: RunOptions,\n ) {\n this._createPromise = createPromise;\n this._tasks = tasks;\n this._schema = schema;\n this._timeout = options?.timeout ?? 300_000;\n this._interval = options?.interval ?? 2_000;\n }\n\n /** Task ID (available after creation resolves). */\n get taskId(): string | null {\n return this._taskId;\n }\n\n /** Full task result (available after awaiting or iterating to completion). */\n get result(): TaskResult<T> | null {\n return this._result;\n }\n\n /** Enable `await client.run(...)` — polls status endpoint, returns TaskResult. */\n then<R1 = TaskResult<T>, R2 = never>(\n onFulfilled?: ((value: TaskResult<T>) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this._waitForOutput().then(onFulfilled, onRejected);\n }\n\n /** Enable `for await (const step of client.run(...))` — polls full task, yields new steps. */\n async *[Symbol.asyncIterator](): AsyncGenerator<TaskStepView> {\n const taskId = await this._ensureTaskId();\n let seen = 0;\n const deadline = Date.now() + this._timeout;\n\n while (Date.now() < deadline) {\n const task = await this._tasks.get(taskId);\n\n for (let i = seen; i < task.steps.length; i++) {\n yield task.steps[i];\n }\n seen = task.steps.length;\n\n if (TERMINAL_STATUSES.has(task.status)) {\n this._result = this._buildResult(task);\n return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(this._interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${this._timeout}ms`);\n }\n\n private async _ensureTaskId(): Promise<string> {\n if (this._taskId) return this._taskId;\n const created = await this._createPromise;\n this._taskId = created.id;\n return this._taskId;\n }\n\n /** Poll lightweight status endpoint until terminal, return TaskResult. */\n private async _waitForOutput(): Promise<TaskResult<T>> {\n const taskId = await this._ensureTaskId();\n const deadline = Date.now() + this._timeout;\n\n while (Date.now() < deadline) {\n const status = await this._tasks.status(taskId);\n if (TERMINAL_STATUSES.has(status.status)) {\n const task = await this._tasks.get(taskId);\n this._result = this._buildResult(task);\n return this._result;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(this._interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${this._timeout}ms`);\n }\n\n private _buildResult(task: TaskView): TaskResult<T> {\n const output = this._parseOutput(task.output);\n return { ...task, output };\n }\n\n private _parseOutput(output: string | null | undefined): T {\n if (output == null) return null as T;\n if (!this._schema) return output as unknown as T;\n return this._schema.parse(JSON.parse(output));\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\nimport { TERMINAL_STATUSES } from \"../helpers.js\";\n\n/** User-facing body: only `task` is required; everything else has API defaults. */\nexport type CreateTaskBody = Pick<components[\"schemas\"][\"CreateTaskRequest\"], \"task\"> &\n Partial<Omit<components[\"schemas\"][\"CreateTaskRequest\"], \"task\">>;\ntype TaskCreatedResponse = components[\"schemas\"][\"TaskCreatedResponse\"];\ntype TaskListResponse = components[\"schemas\"][\"TaskListResponse\"];\ntype TaskLogFileResponse = components[\"schemas\"][\"TaskLogFileResponse\"];\ntype TaskStatusView = components[\"schemas\"][\"TaskStatusView\"];\ntype TaskView = components[\"schemas\"][\"TaskView\"];\ntype UpdateTaskRequest = components[\"schemas\"][\"UpdateTaskRequest\"];\n\nexport interface TaskListParams {\n pageSize?: number;\n pageNumber?: number;\n sessionId?: string;\n filterBy?: string;\n after?: string;\n before?: string;\n}\n\nexport class Tasks {\n constructor(private readonly http: HttpClient) {}\n\n /** Create and start a new AI agent task. */\n create(body: CreateTaskBody): Promise<TaskCreatedResponse> {\n return this.http.post<TaskCreatedResponse>(\"/tasks\", body);\n }\n\n /** List tasks with optional filtering. */\n list(params?: TaskListParams): Promise<TaskListResponse> {\n return this.http.get<TaskListResponse>(\"/tasks\", params as Record<string, unknown>);\n }\n\n /** Get detailed task information. */\n get(taskId: string): Promise<TaskView> {\n return this.http.get<TaskView>(`/tasks/${taskId}`);\n }\n\n /** Update a task (generic PATCH). */\n update(taskId: string, body: UpdateTaskRequest): Promise<TaskView> {\n return this.http.patch<TaskView>(`/tasks/${taskId}`, body);\n }\n\n /** Stop a running task. */\n stop(taskId: string): Promise<TaskView> {\n return this.update(taskId, { action: \"stop\" });\n }\n\n /** Stop a running task and its associated browser session. */\n stopTaskAndSession(taskId: string): Promise<TaskView> {\n return this.update(taskId, { action: \"stop_task_and_session\" });\n }\n\n /** Get lightweight task status (optimized for polling). */\n status(taskId: string): Promise<TaskStatusView> {\n return this.http.get<TaskStatusView>(`/tasks/${taskId}/status`);\n }\n\n /** Get secure download URL for task execution logs. */\n logs(taskId: string): Promise<TaskLogFileResponse> {\n return this.http.get<TaskLogFileResponse>(`/tasks/${taskId}/logs`);\n }\n\n /** Poll until a task reaches a terminal status, then return the full TaskView. */\n async wait(taskId: string, opts?: { timeout?: number; interval?: number }): Promise<TaskView> {\n const timeout = opts?.timeout ?? 300_000;\n const interval = opts?.interval ?? 2_000;\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const status = await this.status(taskId);\n if (TERMINAL_STATUSES.has(status.status)) {\n return this.get(taskId);\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${timeout}ms`);\n }\n}\n"]}
1
+ {"version":3,"sources":["/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/index.cjs","../src/v2/client.ts","../src/v2/resources/billing.ts","../src/v2/resources/browsers.ts","../src/v2/resources/files.ts","../src/v2/resources/marketplace.ts","../src/v2/resources/profiles.ts","../src/v2/resources/sessions.ts","../src/v2/resources/skills.ts","../src/v2/helpers.ts","../src/v2/resources/tasks.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACRA,0BAAkB;ADUlB;AACA;AENO,IAA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,QAAA;AACnC,MAAA;AAGsB,MAAA;AAAE,MAAA;AACA,MAAA;AACjB,QAAA;AACoB,QAAA;AACR,QAAA;AACH,QAAA;AACV,QAAA;AACR,MAAA;AACI,IAAA;AAEuB,MAAA;AACf,MAAA;AACD,QAAA;AACR,UAAA;AAGF,QAAA;AACF,MAAA;AAC2B,MAAA;AACzB,QAAA;AAC4B,QAAA;AACR,QAAA;AACH,QAAA;AAClB,MAAA;AACH,IAAA;AAEoC,IAAA;AACJ,IAAA;AACM,IAAA;AACN,IAAA;AACM,IAAA;AACA,IAAA;AACJ,IAAA;AACU,IAAA;AAC9C,EAAA;AAoB0D,EAAA;AACb,IAAA;AACE,IAAA;AACjC,IAAA;AAC+B,MAAA;AAC3C,IAAA;AACsC,IAAA;AACE,IAAA;AAC1C,EAAA;AACF;ADuUgD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/sauravpanda/Github/LLMs/Browser-Use/sdk/browser-use-node/dist/index.cjs","sourcesContent":[null,"import { z } from \"zod\";\nimport { HttpClient } from \"../core/http.js\";\nimport {\n X402_BASE_URL_DEFAULT_V2,\n type X402Client,\n wrapFetchWithX402,\n x402ClientFromPrivateKey,\n} from \"../core/x402.js\";\nimport { Billing } from \"./resources/billing.js\";\nimport { Browsers } from \"./resources/browsers.js\";\nimport { Files } from \"./resources/files.js\";\nimport { Marketplace } from \"./resources/marketplace.js\";\nimport { Profiles } from \"./resources/profiles.js\";\nimport { Sessions } from \"./resources/sessions.js\";\nimport { Skills } from \"./resources/skills.js\";\nimport { Tasks } from \"./resources/tasks.js\";\nimport { TaskRun } from \"./helpers.js\";\nimport type { CreateTaskBody } from \"./resources/tasks.js\";\nimport type { RunOptions } from \"./helpers.js\";\n\nconst DEFAULT_BASE_URL = \"https://api.browser-use.com/api/v2\";\n\nexport interface BrowserUseOptions {\n apiKey?: string;\n baseUrl?: string;\n maxRetries?: number;\n timeout?: number;\n /** Pre-built x402 client for pay-per-request authentication. */\n x402?: X402Client;\n /** EVM wallet private key for x402 mode (also reads `BROWSER_USE_X402_PRIVATE_KEY`). */\n x402PrivateKey?: string;\n}\n\nexport type RunTaskOptions = Partial<Omit<CreateTaskBody, \"task\">> &\n RunOptions & { schema?: z.ZodType };\n\nexport class BrowserUse {\n readonly billing: Billing;\n readonly tasks: Tasks;\n readonly sessions: Sessions;\n readonly files: Files;\n readonly profiles: Profiles;\n readonly browsers: Browsers;\n readonly skills: Skills;\n readonly marketplace: Marketplace;\n\n private readonly http: HttpClient;\n\n constructor(options: BrowserUseOptions = {}) {\n const x402PrivateKey =\n options.x402PrivateKey ?? process.env.BROWSER_USE_X402_PRIVATE_KEY;\n\n if (options.x402 || x402PrivateKey) {\n // Top-up mode: when apiKey is also set, forward it as a header so the\n // backend credits the API key's project instead of one keyed to the wallet.\n const topupKey = options.apiKey ?? process.env.BROWSER_USE_API_KEY ?? \"\";\n const fetchPromise = (async () => {\n const x402Client = options.x402 ?? (await x402ClientFromPrivateKey(x402PrivateKey!));\n return wrapFetchWithX402(globalThis.fetch, x402Client);\n })();\n // Suppress unhandled-rejection warnings if the user constructs the client\n // but never makes a request\n fetchPromise.catch(() => {});\n this.http = new HttpClient({\n apiKey: topupKey,\n baseUrl: options.baseUrl ?? X402_BASE_URL_DEFAULT_V2,\n maxRetries: options.maxRetries,\n timeout: options.timeout,\n fetch: fetchPromise,\n });\n } else {\n const apiKey =\n options.apiKey ?? process.env.BROWSER_USE_API_KEY ?? \"\";\n if (!apiKey) {\n throw new Error(\n \"No credentials provided. Pass apiKey / set BROWSER_USE_API_KEY, \" +\n \"or pass x402PrivateKey / set BROWSER_USE_X402_PRIVATE_KEY for \" +\n \"pay-per-request access via USDC.\",\n );\n }\n this.http = new HttpClient({\n apiKey,\n baseUrl: options.baseUrl ?? DEFAULT_BASE_URL,\n maxRetries: options.maxRetries,\n timeout: options.timeout,\n });\n }\n\n this.billing = new Billing(this.http);\n this.tasks = new Tasks(this.http);\n this.sessions = new Sessions(this.http);\n this.files = new Files(this.http);\n this.profiles = new Profiles(this.http);\n this.browsers = new Browsers(this.http);\n this.skills = new Skills(this.http);\n this.marketplace = new Marketplace(this.http);\n }\n\n /**\n * Run an AI agent task.\n *\n * ```ts\n * // Simple — just get the output\n * const output = await client.run(\"Find the top HN post\");\n *\n * // Structured output (Zod)\n * const data = await client.run(\"Find product info\", { schema: ProductSchema });\n *\n * // Step-by-step progress\n * for await (const step of client.run(\"Go to google.com\")) {\n * console.log(`[${step.number}] ${step.nextGoal}`);\n * }\n * ```\n */\n run(task: string, options?: Omit<RunTaskOptions, \"schema\">): TaskRun<string>;\n run<T extends z.ZodType>(task: string, options: RunTaskOptions & { schema: T }): TaskRun<z.output<T>>;\n run(task: string, options?: RunTaskOptions): TaskRun<any> {\n const { schema, timeout, interval, ...rest } = options ?? {};\n const body: CreateTaskBody = { task, ...rest };\n if (schema) {\n body.structuredOutput = JSON.stringify(z.toJSONSchema(schema));\n }\n const promise = this.tasks.create(body);\n return new TaskRun(promise, this.tasks, schema, { timeout, interval });\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype AccountView = components[\"schemas\"][\"AccountView\"];\n\nexport class Billing {\n constructor(private readonly http: HttpClient) {}\n\n /** Get authenticated account billing information including credit balance. */\n account(): Promise<AccountView> {\n return this.http.get<AccountView>(\"/billing/account\");\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\n/** All fields are optional (server applies defaults); body itself is required by the spec. */\nexport type CreateBrowserBody = Partial<components[\"schemas\"][\"CreateBrowserSessionRequest\"]>;\ntype BrowserSessionItemView = components[\"schemas\"][\"BrowserSessionItemView\"];\ntype BrowserSessionListResponse = components[\"schemas\"][\"BrowserSessionListResponse\"];\ntype BrowserSessionView = components[\"schemas\"][\"BrowserSessionView\"];\ntype UpdateBrowserSessionRequest = components[\"schemas\"][\"UpdateBrowserSessionRequest\"];\ntype BrowserDownloadListResponse = components[\"schemas\"][\"BrowserDownloadListResponse\"];\n\nexport interface BrowserListParams {\n pageSize?: number;\n pageNumber?: number;\n filterBy?: string;\n}\n\nexport interface BrowserDownloadsParams {\n limit?: number;\n cursor?: string;\n includeUrls?: boolean;\n}\n\nexport class Browsers {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new browser session. */\n create(body: CreateBrowserBody = {}): Promise<BrowserSessionItemView> {\n if (body.proxyCountryCode) {\n body = { ...body, proxyCountryCode: body.proxyCountryCode.toLowerCase() as any };\n }\n return this.http.post<BrowserSessionItemView>(\"/browsers\", body);\n }\n\n /** List browser sessions with optional filtering. */\n list(params?: BrowserListParams): Promise<BrowserSessionListResponse> {\n return this.http.get<BrowserSessionListResponse>(\n \"/browsers\",\n params as Record<string, unknown>,\n );\n }\n\n /** Get detailed browser session information. */\n get(sessionId: string): Promise<BrowserSessionView> {\n return this.http.get<BrowserSessionView>(`/browsers/${sessionId}`);\n }\n\n /** Update a browser session (generic PATCH). */\n update(sessionId: string, body: UpdateBrowserSessionRequest): Promise<BrowserSessionView> {\n return this.http.patch<BrowserSessionView>(`/browsers/${sessionId}`, body);\n }\n\n /** Stop a browser session. */\n stop(sessionId: string): Promise<BrowserSessionView> {\n return this.update(sessionId, { action: \"stop\" });\n }\n\n /** List files the browser downloaded to S3 during the session. */\n downloads(sessionId: string, params?: BrowserDownloadsParams): Promise<BrowserDownloadListResponse> {\n return this.http.get<BrowserDownloadListResponse>(\n `/browsers/${sessionId}/downloads`,\n params as Record<string, unknown>,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype UploadFileRequest = components[\"schemas\"][\"UploadFileRequest\"];\ntype UploadFilePresignedUrlResponse = components[\"schemas\"][\"UploadFilePresignedUrlResponse\"];\ntype TaskOutputFileResponse = components[\"schemas\"][\"TaskOutputFileResponse\"];\n\nexport class Files {\n constructor(private readonly http: HttpClient) {}\n\n /** Generate a presigned URL for uploading files to an agent session. */\n sessionUrl(sessionId: string, body: UploadFileRequest): Promise<UploadFilePresignedUrlResponse> {\n return this.http.post<UploadFilePresignedUrlResponse>(\n `/files/sessions/${sessionId}/presigned-url`,\n body,\n );\n }\n\n /** Generate a presigned URL for uploading files to a browser session. */\n browserUrl(sessionId: string, body: UploadFileRequest): Promise<UploadFilePresignedUrlResponse> {\n return this.http.post<UploadFilePresignedUrlResponse>(\n `/files/browsers/${sessionId}/presigned-url`,\n body,\n );\n }\n\n /** Get secure download URL for a task output file. */\n taskOutput(taskId: string, fileId: string): Promise<TaskOutputFileResponse> {\n return this.http.get<TaskOutputFileResponse>(\n `/files/tasks/${taskId}/output-files/${fileId}`,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype ExecuteSkillRequest = components[\"schemas\"][\"ExecuteSkillRequest\"];\ntype ExecuteSkillResponse = components[\"schemas\"][\"ExecuteSkillResponse\"];\ntype MarketplaceSkillListResponse = components[\"schemas\"][\"MarketplaceSkillListResponse\"];\ntype MarketplaceSkillResponse = components[\"schemas\"][\"MarketplaceSkillResponse\"];\ntype SkillResponse = components[\"schemas\"][\"SkillResponse\"];\n\nexport interface MarketplaceListParams {\n pageSize?: number;\n pageNumber?: number;\n query?: string;\n category?: string;\n fromDate?: string;\n toDate?: string;\n}\n\nexport class Marketplace {\n constructor(private readonly http: HttpClient) {}\n\n /** List all public skills in the marketplace. */\n list(params?: MarketplaceListParams): Promise<MarketplaceSkillListResponse> {\n return this.http.get<MarketplaceSkillListResponse>(\n \"/marketplace/skills\",\n params as Record<string, unknown>,\n );\n }\n\n /** Get details of a specific marketplace skill by slug. */\n get(skillSlug: string): Promise<MarketplaceSkillResponse> {\n return this.http.get<MarketplaceSkillResponse>(`/marketplace/skills/${skillSlug}`);\n }\n\n /** Clone a public marketplace skill to your project. */\n clone(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/marketplace/skills/${skillId}/clone`);\n }\n\n /** Execute a marketplace skill. */\n execute(skillId: string, body: ExecuteSkillRequest): Promise<ExecuteSkillResponse> {\n return this.http.post<ExecuteSkillResponse>(\n `/marketplace/skills/${skillId}/execute`,\n body,\n );\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype ProfileCreateRequest = components[\"schemas\"][\"ProfileCreateRequest\"];\ntype ProfileListResponse = components[\"schemas\"][\"ProfileListResponse\"];\ntype ProfileUpdateRequest = components[\"schemas\"][\"ProfileUpdateRequest\"];\ntype ProfileView = components[\"schemas\"][\"ProfileView\"];\n\nexport interface ProfileListParams {\n pageSize?: number;\n pageNumber?: number;\n query?: string;\n}\n\nexport class Profiles {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new browser profile. */\n create(body?: ProfileCreateRequest): Promise<ProfileView> {\n return this.http.post<ProfileView>(\"/profiles\", body);\n }\n\n /** List profiles with pagination. */\n list(params?: ProfileListParams): Promise<ProfileListResponse> {\n return this.http.get<ProfileListResponse>(\"/profiles\", params as Record<string, unknown>);\n }\n\n /** Get profile details. */\n get(profileId: string): Promise<ProfileView> {\n return this.http.get<ProfileView>(`/profiles/${profileId}`);\n }\n\n /** Update a browser profile. */\n update(profileId: string, body: ProfileUpdateRequest): Promise<ProfileView> {\n return this.http.patch<ProfileView>(`/profiles/${profileId}`, body);\n }\n\n /** Delete a browser profile. */\n delete(profileId: string): Promise<void> {\n return this.http.delete<void>(`/profiles/${profileId}`);\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\n/** User-facing body: all fields are optional (API has defaults). */\ntype CreateSessionBody = Partial<components[\"schemas\"][\"CreateSessionRequest\"]>;\ntype SessionItemView = components[\"schemas\"][\"SessionItemView\"];\ntype SessionListResponse = components[\"schemas\"][\"SessionListResponse\"];\ntype SessionView = components[\"schemas\"][\"SessionView\"];\ntype ShareView = components[\"schemas\"][\"ShareView\"];\ntype UpdateSessionRequest = components[\"schemas\"][\"UpdateSessionRequest\"];\n\nexport interface SessionListParams {\n pageSize?: number;\n pageNumber?: number;\n filterBy?: string;\n}\n\nexport class Sessions {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new session. */\n create(body?: CreateSessionBody): Promise<SessionItemView> {\n if (body?.proxyCountryCode) {\n body = { ...body, proxyCountryCode: body.proxyCountryCode.toLowerCase() as any };\n }\n return this.http.post<SessionItemView>(\"/sessions\", body);\n }\n\n /** List sessions with optional filtering. */\n list(params?: SessionListParams): Promise<SessionListResponse> {\n return this.http.get<SessionListResponse>(\"/sessions\", params as Record<string, unknown>);\n }\n\n /** Get detailed session information. */\n get(sessionId: string): Promise<SessionView> {\n return this.http.get<SessionView>(`/sessions/${sessionId}`);\n }\n\n /** Update a session (generic PATCH). */\n update(sessionId: string, body: UpdateSessionRequest): Promise<SessionView> {\n return this.http.patch<SessionView>(`/sessions/${sessionId}`, body);\n }\n\n /** Stop a session and all its running tasks. */\n stop(sessionId: string): Promise<SessionView> {\n return this.update(sessionId, { action: \"stop\" });\n }\n\n /** Delete a session with all its tasks. */\n delete(sessionId: string): Promise<void> {\n return this.http.delete<void>(`/sessions/${sessionId}`);\n }\n\n /** Get public share information for a session. */\n getShare(sessionId: string): Promise<ShareView> {\n return this.http.get<ShareView>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Create or return existing public share for a session. */\n createShare(sessionId: string): Promise<ShareView> {\n return this.http.post<ShareView>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Remove public share for a session. */\n deleteShare(sessionId: string): Promise<void> {\n return this.http.delete<void>(`/sessions/${sessionId}/public-share`);\n }\n\n /** Purge all session data (ZDR projects only). */\n purge(sessionId: string): Promise<void> {\n return this.http.post<void>(`/sessions/${sessionId}/purge`);\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\n\ntype CreateSkillRequest = components[\"schemas\"][\"CreateSkillRequest\"];\ntype CreateSkillResponse = components[\"schemas\"][\"CreateSkillResponse\"];\ntype ExecuteSkillRequest = components[\"schemas\"][\"ExecuteSkillRequest\"];\ntype ExecuteSkillResponse = components[\"schemas\"][\"ExecuteSkillResponse\"];\ntype RefineSkillRequest = components[\"schemas\"][\"RefineSkillRequest\"];\ntype RefineSkillResponse = components[\"schemas\"][\"RefineSkillResponse\"];\ntype SkillExecutionListResponse = components[\"schemas\"][\"SkillExecutionListResponse\"];\ntype SkillExecutionOutputResponse = components[\"schemas\"][\"SkillExecutionOutputResponse\"];\ntype SkillListResponse = components[\"schemas\"][\"SkillListResponse\"];\ntype SkillResponse = components[\"schemas\"][\"SkillResponse\"];\ntype UpdateSkillRequest = components[\"schemas\"][\"UpdateSkillRequest\"];\n\nexport interface SkillListParams {\n pageSize?: number;\n pageNumber?: number;\n isPublic?: boolean;\n isEnabled?: boolean;\n category?: string;\n query?: string;\n fromDate?: string;\n toDate?: string;\n}\n\nexport interface SkillExecutionListParams {\n pageSize?: number;\n pageNumber?: number;\n}\n\nexport class Skills {\n constructor(private readonly http: HttpClient) {}\n\n /** Create a new skill via automated generation. */\n create(body: CreateSkillRequest): Promise<CreateSkillResponse> {\n return this.http.post<CreateSkillResponse>(\"/skills\", body);\n }\n\n /** List all skills owned by the project. */\n list(params?: SkillListParams): Promise<SkillListResponse> {\n return this.http.get<SkillListResponse>(\"/skills\", params as Record<string, unknown>);\n }\n\n /** Get details of a specific skill. */\n get(skillId: string): Promise<SkillResponse> {\n return this.http.get<SkillResponse>(`/skills/${skillId}`);\n }\n\n /** Delete a skill. */\n delete(skillId: string): Promise<void> {\n return this.http.delete<void>(`/skills/${skillId}`);\n }\n\n /** Update skill metadata. */\n update(skillId: string, body: UpdateSkillRequest): Promise<SkillResponse> {\n return this.http.patch<SkillResponse>(`/skills/${skillId}`, body);\n }\n\n /** Cancel the current in-progress generation for a skill. */\n cancel(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/skills/${skillId}/cancel`);\n }\n\n /** Execute a skill with the provided parameters. */\n execute(skillId: string, body: ExecuteSkillRequest): Promise<ExecuteSkillResponse> {\n return this.http.post<ExecuteSkillResponse>(`/skills/${skillId}/execute`, body);\n }\n\n /** Refine a skill based on feedback. */\n refine(skillId: string, body: RefineSkillRequest): Promise<RefineSkillResponse> {\n return this.http.post<RefineSkillResponse>(`/skills/${skillId}/refine`, body);\n }\n\n /** Rollback to the previous version. */\n rollback(skillId: string): Promise<SkillResponse> {\n return this.http.post<SkillResponse>(`/skills/${skillId}/rollback`);\n }\n\n /** List executions for a specific skill. */\n executions(skillId: string, params?: SkillExecutionListParams): Promise<SkillExecutionListResponse> {\n return this.http.get<SkillExecutionListResponse>(\n `/skills/${skillId}/executions`,\n params as Record<string, unknown>,\n );\n }\n\n /** Get presigned URL for downloading skill execution output. */\n executionOutput(skillId: string, executionId: string): Promise<SkillExecutionOutputResponse> {\n return this.http.get<SkillExecutionOutputResponse>(\n `/skills/${skillId}/executions/${executionId}/output`,\n );\n }\n}\n","import type { z } from \"zod\";\nimport type { components } from \"../generated/v2/types.js\";\nimport type { Tasks } from \"./resources/tasks.js\";\n\ntype TaskCreatedResponse = components[\"schemas\"][\"TaskCreatedResponse\"];\ntype TaskStepView = components[\"schemas\"][\"TaskStepView\"];\ntype TaskView = components[\"schemas\"][\"TaskView\"];\n\nexport const TERMINAL_STATUSES = new Set([\"finished\", \"stopped\"]);\n\n/** Task result with typed output. All TaskView fields are directly accessible. */\nexport type TaskResult<T = string | null> = Omit<TaskView, \"output\"> & { output: T };\n\nexport interface RunOptions {\n /** Maximum time to wait in milliseconds. Default: 300_000 (5 min). */\n timeout?: number;\n /** Polling interval in milliseconds. Default: 2_000. */\n interval?: number;\n}\n\n/**\n * Lazy task handle returned by `client.run()`.\n *\n * - `await client.run(...)` polls the lightweight status endpoint, returns a `TaskResult`.\n * - `for await (const step of client.run(...))` polls the full task, yields new steps.\n */\nexport class TaskRun<T = string> implements PromiseLike<TaskResult<T>> {\n private readonly _createPromise: Promise<TaskCreatedResponse>;\n private readonly _tasks: Tasks;\n private readonly _schema?: z.ZodType<T>;\n private readonly _timeout: number;\n private readonly _interval: number;\n\n private _taskId: string | null = null;\n private _result: TaskResult<T> | null = null;\n\n constructor(\n createPromise: Promise<TaskCreatedResponse>,\n tasks: Tasks,\n schema?: z.ZodType<T>,\n options?: RunOptions,\n ) {\n this._createPromise = createPromise;\n this._tasks = tasks;\n this._schema = schema;\n this._timeout = options?.timeout ?? 300_000;\n this._interval = options?.interval ?? 2_000;\n }\n\n /** Task ID (available after creation resolves). */\n get taskId(): string | null {\n return this._taskId;\n }\n\n /** Full task result (available after awaiting or iterating to completion). */\n get result(): TaskResult<T> | null {\n return this._result;\n }\n\n /** Enable `await client.run(...)` — polls status endpoint, returns TaskResult. */\n then<R1 = TaskResult<T>, R2 = never>(\n onFulfilled?: ((value: TaskResult<T>) => R1 | PromiseLike<R1>) | null,\n onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n ): Promise<R1 | R2> {\n return this._waitForOutput().then(onFulfilled, onRejected);\n }\n\n /** Enable `for await (const step of client.run(...))` — polls full task, yields new steps. */\n async *[Symbol.asyncIterator](): AsyncGenerator<TaskStepView> {\n const taskId = await this._ensureTaskId();\n let seen = 0;\n const deadline = Date.now() + this._timeout;\n\n while (Date.now() < deadline) {\n const task = await this._tasks.get(taskId);\n\n for (let i = seen; i < task.steps.length; i++) {\n yield task.steps[i];\n }\n seen = task.steps.length;\n\n if (TERMINAL_STATUSES.has(task.status)) {\n this._result = this._buildResult(task);\n return;\n }\n\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(this._interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${this._timeout}ms`);\n }\n\n private async _ensureTaskId(): Promise<string> {\n if (this._taskId) return this._taskId;\n const created = await this._createPromise;\n this._taskId = created.id;\n return this._taskId;\n }\n\n /** Poll lightweight status endpoint until terminal, return TaskResult. */\n private async _waitForOutput(): Promise<TaskResult<T>> {\n const taskId = await this._ensureTaskId();\n const deadline = Date.now() + this._timeout;\n\n while (Date.now() < deadline) {\n const status = await this._tasks.status(taskId);\n if (TERMINAL_STATUSES.has(status.status)) {\n const task = await this._tasks.get(taskId);\n this._result = this._buildResult(task);\n return this._result;\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(this._interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${this._timeout}ms`);\n }\n\n private _buildResult(task: TaskView): TaskResult<T> {\n const output = this._parseOutput(task.output);\n return { ...task, output };\n }\n\n private _parseOutput(output: string | null | undefined): T {\n if (output == null) return null as T;\n if (!this._schema) return output as unknown as T;\n return this._schema.parse(JSON.parse(output));\n }\n}\n","import type { HttpClient } from \"../../core/http.js\";\nimport type { components } from \"../../generated/v2/types.js\";\nimport { TERMINAL_STATUSES } from \"../helpers.js\";\n\n/** User-facing body: only `task` is required; everything else has API defaults. */\nexport type CreateTaskBody = Pick<components[\"schemas\"][\"CreateTaskRequest\"], \"task\"> &\n Partial<Omit<components[\"schemas\"][\"CreateTaskRequest\"], \"task\">>;\ntype TaskCreatedResponse = components[\"schemas\"][\"TaskCreatedResponse\"];\ntype TaskListResponse = components[\"schemas\"][\"TaskListResponse\"];\ntype TaskLogFileResponse = components[\"schemas\"][\"TaskLogFileResponse\"];\ntype TaskStatusView = components[\"schemas\"][\"TaskStatusView\"];\ntype TaskView = components[\"schemas\"][\"TaskView\"];\ntype UpdateTaskRequest = components[\"schemas\"][\"UpdateTaskRequest\"];\n\nexport interface TaskListParams {\n pageSize?: number;\n pageNumber?: number;\n sessionId?: string;\n filterBy?: string;\n after?: string;\n before?: string;\n}\n\nexport class Tasks {\n constructor(private readonly http: HttpClient) {}\n\n /** Create and start a new AI agent task. */\n create(body: CreateTaskBody): Promise<TaskCreatedResponse> {\n return this.http.post<TaskCreatedResponse>(\"/tasks\", body);\n }\n\n /** List tasks with optional filtering. */\n list(params?: TaskListParams): Promise<TaskListResponse> {\n return this.http.get<TaskListResponse>(\"/tasks\", params as Record<string, unknown>);\n }\n\n /** Get detailed task information. */\n get(taskId: string): Promise<TaskView> {\n return this.http.get<TaskView>(`/tasks/${taskId}`);\n }\n\n /** Update a task (generic PATCH). */\n update(taskId: string, body: UpdateTaskRequest): Promise<TaskView> {\n return this.http.patch<TaskView>(`/tasks/${taskId}`, body);\n }\n\n /** Stop a running task. */\n stop(taskId: string): Promise<TaskView> {\n return this.update(taskId, { action: \"stop\" });\n }\n\n /** Stop a running task and its associated browser session. */\n stopTaskAndSession(taskId: string): Promise<TaskView> {\n return this.update(taskId, { action: \"stop_task_and_session\" });\n }\n\n /** Get lightweight task status (optimized for polling). */\n status(taskId: string): Promise<TaskStatusView> {\n return this.http.get<TaskStatusView>(`/tasks/${taskId}/status`);\n }\n\n /** Get secure download URL for task execution logs. */\n logs(taskId: string): Promise<TaskLogFileResponse> {\n return this.http.get<TaskLogFileResponse>(`/tasks/${taskId}/logs`);\n }\n\n /** Poll until a task reaches a terminal status, then return the full TaskView. */\n async wait(taskId: string, opts?: { timeout?: number; interval?: number }): Promise<TaskView> {\n const timeout = opts?.timeout ?? 300_000;\n const interval = opts?.interval ?? 2_000;\n const deadline = Date.now() + timeout;\n\n while (Date.now() < deadline) {\n const status = await this.status(taskId);\n if (TERMINAL_STATUSES.has(status.status)) {\n return this.get(taskId);\n }\n const remaining = deadline - Date.now();\n if (remaining <= 0) break;\n await new Promise((r) => setTimeout(r, Math.min(interval, remaining)));\n }\n\n throw new Error(`Task ${taskId} did not complete within ${timeout}ms`);\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
- import { H as HttpClient } from './errors-BtB79l7x.cjs';
3
- export { B as BrowserUseError } from './errors-BtB79l7x.cjs';
2
+ import { H as HttpClient, X as X402Client } from './errors-Bp9CqFUs.cjs';
3
+ export { B as BrowserUseError } from './errors-Bp9CqFUs.cjs';
4
4
 
5
5
  interface components {
6
6
  schemas: {
@@ -2486,6 +2486,10 @@ interface BrowserUseOptions {
2486
2486
  baseUrl?: string;
2487
2487
  maxRetries?: number;
2488
2488
  timeout?: number;
2489
+ /** Pre-built x402 client for pay-per-request authentication. */
2490
+ x402?: X402Client;
2491
+ /** EVM wallet private key for x402 mode (also reads `BROWSER_USE_X402_PRIVATE_KEY`). */
2492
+ x402PrivateKey?: string;
2489
2493
  }
2490
2494
  type RunTaskOptions = Partial<Omit<CreateTaskBody, "task">> & RunOptions & {
2491
2495
  schema?: z.ZodType;