wuying-agentbay-sdk 0.6.1 → 0.7.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/dist/index.cjs CHANGED
@@ -114,10 +114,10 @@ var require_main = __commonJS({
114
114
  "node_modules/dotenv/lib/main.js"(exports, module) {
115
115
  "use strict";
116
116
  init_cjs_shims();
117
- var fs2 = __require("fs");
118
- var path2 = __require("path");
117
+ var fs3 = __require("fs");
118
+ var path3 = __require("path");
119
119
  var os = __require("os");
120
- var crypto = __require("crypto");
120
+ var crypto2 = __require("crypto");
121
121
  var packageJson = require_package();
122
122
  var version = packageJson.version;
123
123
  var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
@@ -230,7 +230,7 @@ var require_main = __commonJS({
230
230
  if (options && options.path && options.path.length > 0) {
231
231
  if (Array.isArray(options.path)) {
232
232
  for (const filepath of options.path) {
233
- if (fs2.existsSync(filepath)) {
233
+ if (fs3.existsSync(filepath)) {
234
234
  possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
235
235
  }
236
236
  }
@@ -238,16 +238,16 @@ var require_main = __commonJS({
238
238
  possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
239
239
  }
240
240
  } else {
241
- possibleVaultPath = path2.resolve(process.cwd(), ".env.vault");
241
+ possibleVaultPath = path3.resolve(process.cwd(), ".env.vault");
242
242
  }
243
- if (fs2.existsSync(possibleVaultPath)) {
243
+ if (fs3.existsSync(possibleVaultPath)) {
244
244
  return possibleVaultPath;
245
245
  }
246
246
  return null;
247
247
  }
248
248
  __name(_vaultPath, "_vaultPath");
249
249
  function _resolveHome(envPath) {
250
- return envPath[0] === "~" ? path2.join(os.homedir(), envPath.slice(1)) : envPath;
250
+ return envPath[0] === "~" ? path3.join(os.homedir(), envPath.slice(1)) : envPath;
251
251
  }
252
252
  __name(_resolveHome, "_resolveHome");
253
253
  function _configVault(options) {
@@ -266,7 +266,7 @@ var require_main = __commonJS({
266
266
  }
267
267
  __name(_configVault, "_configVault");
268
268
  function configDotenv(options) {
269
- const dotenvPath = path2.resolve(process.cwd(), ".env");
269
+ const dotenvPath = path3.resolve(process.cwd(), ".env");
270
270
  let encoding = "utf8";
271
271
  const debug = Boolean(options && options.debug);
272
272
  const quiet = options && "quiet" in options ? options.quiet : true;
@@ -290,13 +290,13 @@ var require_main = __commonJS({
290
290
  }
291
291
  let lastError;
292
292
  const parsedAll = {};
293
- for (const path3 of optionPaths) {
293
+ for (const path4 of optionPaths) {
294
294
  try {
295
- const parsed = DotenvModule.parse(fs2.readFileSync(path3, { encoding }));
295
+ const parsed = DotenvModule.parse(fs3.readFileSync(path4, { encoding }));
296
296
  DotenvModule.populate(parsedAll, parsed, options);
297
297
  } catch (e) {
298
298
  if (debug) {
299
- _debug(`Failed to load ${path3} ${e.message}`);
299
+ _debug(`Failed to load ${path4} ${e.message}`);
300
300
  }
301
301
  lastError = e;
302
302
  }
@@ -311,7 +311,7 @@ var require_main = __commonJS({
311
311
  const shortPaths = [];
312
312
  for (const filePath of optionPaths) {
313
313
  try {
314
- const relative = path2.relative(process.cwd(), filePath);
314
+ const relative = path3.relative(process.cwd(), filePath);
315
315
  shortPaths.push(relative);
316
316
  } catch (e) {
317
317
  if (debug) {
@@ -348,7 +348,7 @@ var require_main = __commonJS({
348
348
  const authTag = ciphertext.subarray(-16);
349
349
  ciphertext = ciphertext.subarray(12, -16);
350
350
  try {
351
- const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
351
+ const aesgcm = crypto2.createDecipheriv("aes-256-gcm", key, nonce);
352
352
  aesgcm.setAuthTag(authTag);
353
353
  return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
354
354
  } catch (error) {
@@ -4150,8 +4150,8 @@ var Client = _Client;
4150
4150
  // src/config.ts
4151
4151
  init_cjs_shims();
4152
4152
  var dotenv = __toESM(require_main());
4153
- var _fs = require('fs'); var fs = _interopRequireWildcard(_fs);
4154
- var _path = require('path'); var path = _interopRequireWildcard(_path);
4153
+ var _fs = require('fs'); var fs = _interopRequireWildcard(_fs); var fs2 = _interopRequireWildcard(_fs);
4154
+ var _path = require('path'); var path = _interopRequireWildcard(_path); var path2 = _interopRequireWildcard(_path);
4155
4155
 
4156
4156
  // src/utils/logger.ts
4157
4157
  init_cjs_shims();
@@ -4194,6 +4194,28 @@ function defaultConfig() {
4194
4194
  };
4195
4195
  }
4196
4196
  __name(defaultConfig, "defaultConfig");
4197
+ var dotEnvLoaded = false;
4198
+ function loadDotEnv() {
4199
+ if (dotEnvLoaded) {
4200
+ return;
4201
+ }
4202
+ try {
4203
+ const envPath = path.resolve(process.cwd(), ".env");
4204
+ if (fs.existsSync(envPath)) {
4205
+ const envConfig = dotenv.parse(fs.readFileSync(envPath));
4206
+ for (const k in envConfig) {
4207
+ if (!process.env.hasOwnProperty(k)) {
4208
+ process.env[k] = envConfig[k];
4209
+ }
4210
+ }
4211
+ log(`Loaded .env file at: ${envPath}`);
4212
+ dotEnvLoaded = true;
4213
+ }
4214
+ } catch (error) {
4215
+ log(`Warning: Failed to load .env file: ${error}`);
4216
+ }
4217
+ }
4218
+ __name(loadDotEnv, "loadDotEnv");
4197
4219
  function loadConfig(customConfig) {
4198
4220
  if (customConfig) {
4199
4221
  return customConfig;
@@ -4214,16 +4236,16 @@ function loadConfig(customConfig) {
4214
4236
  const envPath = path.resolve(process.cwd(), ".env");
4215
4237
  if (fs.existsSync(envPath)) {
4216
4238
  const envConfig = dotenv.parse(fs.readFileSync(envPath));
4217
- for (const k in envConfig) {
4218
- if (!process.env.hasOwnProperty(k)) {
4219
- if (k === "AGENTBAY_REGION_ID") config.region_id = envConfig[k];
4220
- else if (k === "AGENTBAY_ENDPOINT") config.endpoint = envConfig[k];
4221
- else if (k === "AGENTBAY_TIMEOUT_MS") {
4222
- const timeout = parseInt(envConfig[k], 10);
4223
- if (!isNaN(timeout) && timeout > 0) {
4224
- config.timeout_ms = timeout;
4225
- }
4226
- }
4239
+ if (!process.env.AGENTBAY_REGION_ID && envConfig.AGENTBAY_REGION_ID) {
4240
+ config.region_id = envConfig.AGENTBAY_REGION_ID;
4241
+ }
4242
+ if (!process.env.AGENTBAY_ENDPOINT && envConfig.AGENTBAY_ENDPOINT) {
4243
+ config.endpoint = envConfig.AGENTBAY_ENDPOINT;
4244
+ }
4245
+ if (!process.env.AGENTBAY_TIMEOUT_MS && envConfig.AGENTBAY_TIMEOUT_MS) {
4246
+ const timeout = parseInt(envConfig.AGENTBAY_TIMEOUT_MS, 10);
4247
+ if (!isNaN(timeout) && timeout > 0) {
4248
+ config.timeout_ms = timeout;
4227
4249
  }
4228
4250
  }
4229
4251
  log(`Loaded .env file at: ${envPath}`);
@@ -5314,7 +5336,7 @@ var _ContextManager = class _ContextManager {
5314
5336
  async info() {
5315
5337
  return this.infoWithParams();
5316
5338
  }
5317
- async infoWithParams(contextId, path2, taskType) {
5339
+ async infoWithParams(contextId, path3, taskType) {
5318
5340
  const request = new GetContextInfoRequest({
5319
5341
  authorization: `Bearer ${this.session.getAPIKey()}`,
5320
5342
  sessionId: this.session.getSessionId()
@@ -5322,8 +5344,8 @@ var _ContextManager = class _ContextManager {
5322
5344
  if (contextId) {
5323
5345
  request.contextId = contextId;
5324
5346
  }
5325
- if (path2) {
5326
- request.path = path2;
5347
+ if (path3) {
5348
+ request.path = path3;
5327
5349
  }
5328
5350
  if (taskType) {
5329
5351
  request.taskType = taskType;
@@ -5373,7 +5395,7 @@ var _ContextManager = class _ContextManager {
5373
5395
  async sync() {
5374
5396
  return this.syncWithParams();
5375
5397
  }
5376
- async syncWithParams(contextId, path2, mode) {
5398
+ async syncWithParams(contextId, path3, mode) {
5377
5399
  const request = new SyncContextRequest({
5378
5400
  authorization: `Bearer ${this.session.getAPIKey()}`,
5379
5401
  sessionId: this.session.getSessionId()
@@ -5381,8 +5403,8 @@ var _ContextManager = class _ContextManager {
5381
5403
  if (contextId) {
5382
5404
  request.contextId = contextId;
5383
5405
  }
5384
- if (path2) {
5385
- request.path = path2;
5406
+ if (path3) {
5407
+ request.path = path3;
5386
5408
  }
5387
5409
  if (mode) {
5388
5410
  request.mode = mode;
@@ -5512,10 +5534,10 @@ var _FileSystem = class _FileSystem {
5512
5534
  * @param path - Path to the directory to create.
5513
5535
  * @returns BoolResult with creation result and requestId
5514
5536
  */
5515
- async createDirectory(path2) {
5537
+ async createDirectory(path3) {
5516
5538
  try {
5517
5539
  const args = {
5518
- path: path2
5540
+ path: path3
5519
5541
  };
5520
5542
  const result = await this.session.callMcpTool(
5521
5543
  "create_directory",
@@ -5550,10 +5572,10 @@ var _FileSystem = class _FileSystem {
5550
5572
  * @param dryRun - Optional: If true, preview changes without applying them.
5551
5573
  * @returns BoolResult with edit result and requestId
5552
5574
  */
5553
- async editFile(path2, edits, dryRun = false) {
5575
+ async editFile(path3, edits, dryRun = false) {
5554
5576
  try {
5555
5577
  const args = {
5556
- path: path2,
5578
+ path: path3,
5557
5579
  edits,
5558
5580
  dryRun
5559
5581
  };
@@ -5588,10 +5610,10 @@ var _FileSystem = class _FileSystem {
5588
5610
  * @param path - Path to the file or directory to inspect.
5589
5611
  * @returns FileInfoResult with file info and requestId
5590
5612
  */
5591
- async getFileInfo(path2) {
5613
+ async getFileInfo(path3) {
5592
5614
  try {
5593
5615
  const args = {
5594
- path: path2
5616
+ path: path3
5595
5617
  };
5596
5618
  const result = await this.session.callMcpTool(
5597
5619
  "get_file_info",
@@ -5634,10 +5656,10 @@ var _FileSystem = class _FileSystem {
5634
5656
  * @param path - Path to the directory to list.
5635
5657
  * @returns DirectoryListResult with directory entries and requestId
5636
5658
  */
5637
- async listDirectory(path2) {
5659
+ async listDirectory(path3) {
5638
5660
  try {
5639
5661
  const args = {
5640
- path: path2
5662
+ path: path3
5641
5663
  };
5642
5664
  const result = await this.session.callMcpTool(
5643
5665
  "list_directory",
@@ -5705,18 +5727,17 @@ var _FileSystem = class _FileSystem {
5705
5727
  }
5706
5728
  }
5707
5729
  /**
5708
- * Reads the content of a file.
5709
- * Corresponds to Python's read_file() method
5730
+ * Internal method to read a file chunk. Used for chunked file operations.
5710
5731
  *
5711
5732
  * @param path - Path to the file to read.
5712
5733
  * @param offset - Optional: Byte offset to start reading from (0-based).
5713
5734
  * @param length - Optional: Number of bytes to read. If 0, reads the entire file from offset.
5714
5735
  * @returns FileContentResult with file content and requestId
5715
5736
  */
5716
- async readFile(path2, offset = 0, length = 0) {
5737
+ async readFileChunk(path3, offset = 0, length = 0) {
5717
5738
  try {
5718
5739
  const args = {
5719
- path: path2
5740
+ path: path3
5720
5741
  };
5721
5742
  if (offset > 0) {
5722
5743
  args.offset = offset;
@@ -5782,8 +5803,8 @@ var _FileSystem = class _FileSystem {
5782
5803
  for (const line of lines) {
5783
5804
  const colonIndex = line.indexOf(":");
5784
5805
  if (colonIndex > 0 && currentPath === "" && !line.substring(0, colonIndex).includes(" ")) {
5785
- const path2 = line.substring(0, colonIndex).trim();
5786
- currentPath = path2;
5806
+ const path3 = line.substring(0, colonIndex).trim();
5807
+ currentPath = path3;
5787
5808
  if (line.length > colonIndex + 1) {
5788
5809
  const contentStart = line.substring(colonIndex + 1).trim();
5789
5810
  if (contentStart) {
@@ -5803,8 +5824,8 @@ var _FileSystem = class _FileSystem {
5803
5824
  if (currentPath) {
5804
5825
  fileContents[currentPath] = currentContent.join("\n");
5805
5826
  }
5806
- for (const path2 in fileContents) {
5807
- fileContents[path2] = fileContents[path2].replace(/\n+$/, "");
5827
+ for (const path3 in fileContents) {
5828
+ fileContents[path3] = fileContents[path3].replace(/\n+$/, "");
5808
5829
  }
5809
5830
  }
5810
5831
  return {
@@ -5830,10 +5851,10 @@ var _FileSystem = class _FileSystem {
5830
5851
  * @param excludePatterns - Optional: Array of patterns to exclude.
5831
5852
  * @returns FileSearchResult with search results and requestId
5832
5853
  */
5833
- async searchFiles(path2, pattern, excludePatterns = []) {
5854
+ async searchFiles(path3, pattern, excludePatterns = []) {
5834
5855
  try {
5835
5856
  const args = {
5836
- path: path2,
5857
+ path: path3,
5837
5858
  pattern
5838
5859
  };
5839
5860
  if (excludePatterns.length > 0) {
@@ -5870,15 +5891,14 @@ var _FileSystem = class _FileSystem {
5870
5891
  }
5871
5892
  }
5872
5893
  /**
5873
- * Writes content to a file.
5874
- * Corresponds to Python's write_file() method
5894
+ * Internal method to write a file chunk. Used for chunked file operations.
5875
5895
  *
5876
5896
  * @param path - Path to the file to write.
5877
5897
  * @param content - Content to write to the file.
5878
5898
  * @param mode - Optional: Write mode. One of "overwrite", "append", or "create_new". Default is "overwrite".
5879
5899
  * @returns BoolResult with write result and requestId
5880
5900
  */
5881
- async writeFile(path2, content, mode = "overwrite") {
5901
+ async writeFileChunk(path3, content, mode = "overwrite") {
5882
5902
  try {
5883
5903
  const validModes = ["overwrite", "append", "create_new"];
5884
5904
  if (!validModes.includes(mode)) {
@@ -5891,7 +5911,7 @@ var _FileSystem = class _FileSystem {
5891
5911
  };
5892
5912
  }
5893
5913
  const args = {
5894
- path: path2,
5914
+ path: path3,
5895
5915
  content,
5896
5916
  mode
5897
5917
  };
@@ -5920,16 +5940,15 @@ var _FileSystem = class _FileSystem {
5920
5940
  }
5921
5941
  }
5922
5942
  /**
5923
- * Reads a large file in chunks to handle size limitations of the underlying API.
5924
- * Corresponds to Python's read_large_file() method
5943
+ * Reads the contents of a file. Automatically handles large files by chunking.
5925
5944
  *
5926
5945
  * @param path - Path to the file to read.
5927
- * @param chunkSize - Optional: Size of each chunk in bytes. Default is 60KB.
5928
5946
  * @returns FileContentResult with complete file content and requestId
5929
5947
  */
5930
- async readLargeFile(path2, chunkSize = DEFAULT_CHUNK_SIZE) {
5948
+ async readFile(path3) {
5949
+ const chunkSize = DEFAULT_CHUNK_SIZE;
5931
5950
  try {
5932
- const fileInfoResult = await this.getFileInfo(path2);
5951
+ const fileInfoResult = await this.getFileInfo(path3);
5933
5952
  if (!fileInfoResult.success) {
5934
5953
  return {
5935
5954
  requestId: fileInfoResult.requestId,
@@ -5943,7 +5962,7 @@ var _FileSystem = class _FileSystem {
5943
5962
  requestId: fileInfoResult.requestId,
5944
5963
  success: false,
5945
5964
  content: "",
5946
- errorMessage: `Path does not exist or is a directory: ${path2}`
5965
+ errorMessage: `Path does not exist or is a directory: ${path3}`
5947
5966
  };
5948
5967
  }
5949
5968
  const fileSize = fileInfoResult.fileInfo.size || 0;
@@ -5963,7 +5982,7 @@ var _FileSystem = class _FileSystem {
5963
5982
  length = fileSize - offset;
5964
5983
  }
5965
5984
  try {
5966
- const chunkResult = await this.readFile(path2, offset, length);
5985
+ const chunkResult = await this.readFileChunk(path3, offset, length);
5967
5986
  if (!chunkResult.success) {
5968
5987
  return chunkResult;
5969
5988
  }
@@ -5994,25 +6013,25 @@ var _FileSystem = class _FileSystem {
5994
6013
  }
5995
6014
  }
5996
6015
  /**
5997
- * Writes a large file in chunks to handle size limitations of the underlying API.
5998
- * Corresponds to Python's write_large_file() method
6016
+ * Writes content to a file. Automatically handles large files by chunking.
5999
6017
  *
6000
6018
  * @param path - Path to the file to write.
6001
6019
  * @param content - Content to write to the file.
6002
- * @param chunkSize - Optional: Size of each chunk in bytes. Default is 60KB.
6020
+ * @param mode - Optional: Write mode. One of "overwrite", "append", or "create_new". Default is "overwrite".
6003
6021
  * @returns BoolResult indicating success or failure with requestId
6004
6022
  */
6005
- async writeLargeFile(path2, content, chunkSize = DEFAULT_CHUNK_SIZE) {
6023
+ async writeFile(path3, content, mode = "overwrite") {
6024
+ const chunkSize = DEFAULT_CHUNK_SIZE;
6006
6025
  try {
6007
6026
  const contentLen = content.length;
6008
6027
  if (contentLen <= chunkSize) {
6009
- return await this.writeFile(path2, content, "overwrite");
6028
+ return await this.writeFileChunk(path3, content, mode);
6010
6029
  }
6011
6030
  const firstChunkEnd = Math.min(chunkSize, contentLen);
6012
- const firstResult = await this.writeFile(
6013
- path2,
6031
+ const firstResult = await this.writeFileChunk(
6032
+ path3,
6014
6033
  content.substring(0, firstChunkEnd),
6015
- "overwrite"
6034
+ mode
6016
6035
  );
6017
6036
  if (!firstResult.success) {
6018
6037
  return firstResult;
@@ -6020,8 +6039,8 @@ var _FileSystem = class _FileSystem {
6020
6039
  let chunkCount = 1;
6021
6040
  for (let offset = firstChunkEnd; offset < contentLen; ) {
6022
6041
  const end = Math.min(offset + chunkSize, contentLen);
6023
- const chunkResult = await this.writeFile(
6024
- path2,
6042
+ const chunkResult = await this.writeFileChunk(
6043
+ path3,
6025
6044
  content.substring(offset, end),
6026
6045
  "append"
6027
6046
  );
@@ -6141,12 +6160,12 @@ var _Oss = class _Oss {
6141
6160
  * @returns OSSUploadResult with upload result and requestId
6142
6161
  * @throws APIError if the operation fails.
6143
6162
  */
6144
- async upload(bucket, object, path2) {
6163
+ async upload(bucket, object, path3) {
6145
6164
  try {
6146
6165
  const args = {
6147
6166
  bucket,
6148
6167
  object,
6149
- path: path2
6168
+ path: path3
6150
6169
  };
6151
6170
  const result = await this.session.callMcpTool("oss_upload", args);
6152
6171
  return {
@@ -6173,11 +6192,11 @@ var _Oss = class _Oss {
6173
6192
  * @returns OSSUploadResult with upload result and requestId
6174
6193
  * @throws APIError if the operation fails.
6175
6194
  */
6176
- async uploadAnonymous(url, path2) {
6195
+ async uploadAnonymous(url, path3) {
6177
6196
  try {
6178
6197
  const args = {
6179
6198
  url,
6180
- path: path2
6199
+ path: path3
6181
6200
  };
6182
6201
  const result = await this.session.callMcpTool("oss_upload_anonymous", args);
6183
6202
  return {
@@ -6205,12 +6224,12 @@ var _Oss = class _Oss {
6205
6224
  * @returns OSSDownloadResult with download result and requestId
6206
6225
  * @throws APIError if the operation fails.
6207
6226
  */
6208
- async download(bucket, object, path2) {
6227
+ async download(bucket, object, path3) {
6209
6228
  try {
6210
6229
  const args = {
6211
6230
  bucket,
6212
6231
  object,
6213
- path: path2
6232
+ path: path3
6214
6233
  };
6215
6234
  const result = await this.session.callMcpTool("oss_download", args);
6216
6235
  return {
@@ -6237,11 +6256,11 @@ var _Oss = class _Oss {
6237
6256
  * @returns OSSDownloadResult with download result and requestId
6238
6257
  * @throws APIError if the operation fails.
6239
6258
  */
6240
- async downloadAnonymous(url, path2) {
6259
+ async downloadAnonymous(url, path3) {
6241
6260
  try {
6242
6261
  const args = {
6243
6262
  url,
6244
- path: path2
6263
+ path: path3
6245
6264
  };
6246
6265
  const result = await this.session.callMcpTool("oss_download_anonymous", args);
6247
6266
  return {
@@ -7299,6 +7318,7 @@ var _BrowserOptionClass = class _BrowserOptionClass {
7299
7318
  this.screen = screen;
7300
7319
  this.fingerprint = fingerprint;
7301
7320
  this.proxies = proxies;
7321
+ this.extensionPath = "/tmp/extensions/";
7302
7322
  if (proxies !== void 0) {
7303
7323
  if (!Array.isArray(proxies)) {
7304
7324
  throw new Error("proxies must be a list");
@@ -7310,6 +7330,9 @@ var _BrowserOptionClass = class _BrowserOptionClass {
7310
7330
  }
7311
7331
  toMap() {
7312
7332
  const optionMap = {};
7333
+ if (process.env.AGENTBAY_BROWSER_BEHAVIOR_SIMULATE) {
7334
+ optionMap["behaviorSimulate"] = process.env.AGENTBAY_BROWSER_BEHAVIOR_SIMULATE !== "0";
7335
+ }
7313
7336
  if (this.useStealth !== void 0) {
7314
7337
  optionMap["useStealth"] = this.useStealth;
7315
7338
  }
@@ -7332,6 +7355,9 @@ var _BrowserOptionClass = class _BrowserOptionClass {
7332
7355
  if (this.proxies !== void 0) {
7333
7356
  optionMap["proxies"] = this.proxies.map((proxy) => proxy.toMap());
7334
7357
  }
7358
+ if (this.extensionPath !== void 0) {
7359
+ optionMap["extensionPath"] = this.extensionPath;
7360
+ }
7335
7361
  return optionMap;
7336
7362
  }
7337
7363
  fromMap(m) {
@@ -7369,6 +7395,9 @@ var _BrowserOptionClass = class _BrowserOptionClass {
7369
7395
  return BrowserProxyClass.fromMap(proxyData);
7370
7396
  }).filter(Boolean);
7371
7397
  }
7398
+ if (map.extensionPath !== void 0) {
7399
+ this.extensionPath = map.extensionPath;
7400
+ }
7372
7401
  return this;
7373
7402
  }
7374
7403
  };
@@ -7529,7 +7558,6 @@ var _Session = class _Session {
7529
7558
  * @param sessionId - The ID of this session.
7530
7559
  */
7531
7560
  constructor(agentBay, sessionId) {
7532
- this.resourceUrl = "";
7533
7561
  // VPC-related information
7534
7562
  this.isVpc = false;
7535
7563
  // Whether this session uses VPC resources
@@ -7540,7 +7568,6 @@ var _Session = class _Session {
7540
7568
  this.mcpTools = [];
7541
7569
  this.agentBay = agentBay;
7542
7570
  this.sessionId = sessionId;
7543
- this.resourceUrl = "";
7544
7571
  this.fileSystem = new FileSystem(this);
7545
7572
  this.command = new Command(this);
7546
7573
  this.code = new Code(this);
@@ -7830,7 +7857,6 @@ var _Session = class _Session {
7830
7857
  }
7831
7858
  if (_optionalChain([data, 'optionalAccess', _61 => _61.resourceUrl])) {
7832
7859
  sessionInfo.resourceUrl = data.resourceUrl;
7833
- this.resourceUrl = data.resourceUrl;
7834
7860
  }
7835
7861
  if (_optionalChain([data, 'optionalAccess', _62 => _62.desktopInfo])) {
7836
7862
  const desktopInfo = data.desktopInfo;
@@ -8142,6 +8168,7 @@ var _AgentBay = class _AgentBay {
8142
8168
  */
8143
8169
  constructor(options = {}) {
8144
8170
  this.sessions = /* @__PURE__ */ new Map();
8171
+ loadDotEnv();
8145
8172
  this.apiKey = options.apiKey || process.env.AGENTBAY_API_KEY || "";
8146
8173
  if (!this.apiKey) {
8147
8174
  throw new AuthenticationError(
@@ -8274,9 +8301,6 @@ var _AgentBay = class _AgentBay {
8274
8301
  log("session_id =", sessionId);
8275
8302
  log("resource_url =", resourceUrl);
8276
8303
  const session = new Session(this, sessionId);
8277
- if (resourceUrl) {
8278
- session.resourceUrl = resourceUrl;
8279
- }
8280
8304
  session.isVpc = params.isVpc || false;
8281
8305
  if (data.networkInterfaceIp) {
8282
8306
  session.networkInterfaceIp = data.networkInterfaceIp;
@@ -8481,6 +8505,366 @@ var AgentBay = _AgentBay;
8481
8505
  // src/agent/index.ts
8482
8506
  init_cjs_shims();
8483
8507
 
8508
+ // src/extension.ts
8509
+ init_cjs_shims();
8510
+
8511
+
8512
+ var _crypto = require('crypto'); var crypto = _interopRequireWildcard(_crypto);
8513
+ var _nodefetch = require('node-fetch'); var _nodefetch2 = _interopRequireDefault(_nodefetch);
8514
+ var EXTENSIONS_BASE_PATH = "/tmp/extensions";
8515
+ var _Extension = class _Extension {
8516
+ /**
8517
+ * Initialize an Extension object.
8518
+ *
8519
+ * @param id - The unique identifier of the extension.
8520
+ * @param name - The name of the extension.
8521
+ * @param createdAt - Date and time when the extension was created.
8522
+ */
8523
+ constructor(id, name, createdAt) {
8524
+ this.id = id;
8525
+ this.name = name;
8526
+ this.createdAt = createdAt;
8527
+ }
8528
+ };
8529
+ __name(_Extension, "Extension");
8530
+ var Extension = _Extension;
8531
+ var _ExtensionOption = class _ExtensionOption {
8532
+ /**
8533
+ * Initialize ExtensionOption with context and extension configuration.
8534
+ *
8535
+ * @param contextId - ID of the extension context for browser extensions.
8536
+ * This should match the context where extensions are stored.
8537
+ * @param extensionIds - List of extension IDs to be loaded in the browser session.
8538
+ * Each ID should correspond to a valid extension in the context.
8539
+ *
8540
+ * @throws {Error} If contextId is empty or extensionIds is empty.
8541
+ */
8542
+ constructor(contextId, extensionIds) {
8543
+ if (!contextId || !contextId.trim()) {
8544
+ throw new Error("contextId cannot be empty");
8545
+ }
8546
+ if (!extensionIds || extensionIds.length === 0) {
8547
+ throw new Error("extensionIds cannot be empty");
8548
+ }
8549
+ this.contextId = contextId;
8550
+ this.extensionIds = extensionIds;
8551
+ }
8552
+ /**
8553
+ * String representation of ExtensionOption.
8554
+ */
8555
+ toString() {
8556
+ return `ExtensionOption(contextId='${this.contextId}', extensionIds=${JSON.stringify(this.extensionIds)})`;
8557
+ }
8558
+ /**
8559
+ * Human-readable string representation.
8560
+ */
8561
+ toDisplayString() {
8562
+ return `Extension Config: ${this.extensionIds.length} extension(s) in context '${this.contextId}'`;
8563
+ }
8564
+ /**
8565
+ * Validate the extension option configuration.
8566
+ *
8567
+ * @returns True if configuration is valid, false otherwise.
8568
+ */
8569
+ validate() {
8570
+ try {
8571
+ if (!this.contextId || !this.contextId.trim()) {
8572
+ return false;
8573
+ }
8574
+ if (!this.extensionIds || this.extensionIds.length === 0) {
8575
+ return false;
8576
+ }
8577
+ for (const extId of this.extensionIds) {
8578
+ if (typeof extId !== "string" || !extId.trim()) {
8579
+ return false;
8580
+ }
8581
+ }
8582
+ return true;
8583
+ } catch (error) {
8584
+ return false;
8585
+ }
8586
+ }
8587
+ };
8588
+ __name(_ExtensionOption, "ExtensionOption");
8589
+ var ExtensionOption = _ExtensionOption;
8590
+ var _ExtensionsService = class _ExtensionsService {
8591
+ /**
8592
+ * Initializes the ExtensionsService with a context.
8593
+ *
8594
+ * @param agentBay - The AgentBay client instance.
8595
+ * @param contextId - The context ID or name. If empty or not provided,
8596
+ * a default context name will be generated automatically.
8597
+ * If the context doesn't exist, it will be automatically created.
8598
+ *
8599
+ * Note:
8600
+ * The service automatically detects if the context exists. If not,
8601
+ * it creates a new context with the provided name or a generated default name.
8602
+ * Context initialization is handled lazily on first use.
8603
+ */
8604
+ constructor(agentBay, contextId = "") {
8605
+ this._initializationPromise = null;
8606
+ if (!agentBay) {
8607
+ throw new AgentBayError("AgentBay instance is required");
8608
+ }
8609
+ if (!agentBay.context) {
8610
+ throw new AgentBayError("AgentBay instance must have a context service");
8611
+ }
8612
+ this.agentBay = agentBay;
8613
+ this.contextService = agentBay.context;
8614
+ this.autoCreated = true;
8615
+ if (!contextId || contextId.trim() === "") {
8616
+ contextId = `extensions-${Math.floor(Date.now() / 1e3)}`;
8617
+ log(`Generated default context name: ${contextId}`);
8618
+ }
8619
+ this.contextName = contextId;
8620
+ this._initializationPromise = this._initializeContext();
8621
+ }
8622
+ /**
8623
+ * Internal method to initialize the context.
8624
+ * This ensures the context is ready before any operations.
8625
+ */
8626
+ async _initializeContext() {
8627
+ try {
8628
+ const contextResult = await this.contextService.get(this.contextName, true);
8629
+ if (!contextResult.success || !contextResult.context) {
8630
+ throw new AgentBayError(`Failed to create extension repository context: ${this.contextName}`);
8631
+ }
8632
+ this.extensionContext = contextResult.context;
8633
+ this.contextId = this.extensionContext.id;
8634
+ } catch (error) {
8635
+ throw new AgentBayError(`Failed to initialize ExtensionsService: ${error instanceof Error ? error.message : String(error)}`);
8636
+ }
8637
+ }
8638
+ /**
8639
+ * Ensures the service is initialized before performing operations.
8640
+ */
8641
+ async _ensureInitialized() {
8642
+ if (this._initializationPromise) {
8643
+ await this._initializationPromise;
8644
+ this._initializationPromise = null;
8645
+ }
8646
+ }
8647
+ /**
8648
+ * An internal helper method that encapsulates the flow of "get upload URL for a specific path and upload".
8649
+ * Uses the existing context service for file operations.
8650
+ *
8651
+ * @param localPath - The path to the local file.
8652
+ * @param remotePath - The path of the file in context storage.
8653
+ *
8654
+ * @throws {AgentBayError} If getting the credential or uploading fails.
8655
+ */
8656
+ async _uploadToCloud(localPath, remotePath) {
8657
+ try {
8658
+ const urlResult = await this.contextService.getFileUploadUrl(this.contextId, remotePath);
8659
+ if (!urlResult.success || !urlResult.url) {
8660
+ throw new AgentBayError(`Failed to get upload URL: ${urlResult.url || "No URL returned"}`);
8661
+ }
8662
+ const preSignedUrl = urlResult.url;
8663
+ const fileBuffer = fs2.readFileSync(localPath);
8664
+ const response = await _nodefetch2.default.call(void 0, preSignedUrl, {
8665
+ method: "PUT",
8666
+ body: fileBuffer
8667
+ });
8668
+ if (!response.ok) {
8669
+ throw new AgentBayError(`HTTP error uploading file: ${response.status} ${response.statusText}`);
8670
+ }
8671
+ } catch (error) {
8672
+ if (error instanceof AgentBayError) {
8673
+ throw error;
8674
+ }
8675
+ throw new AgentBayError(`An error occurred while uploading the file: ${error instanceof Error ? error.message : String(error)}`);
8676
+ }
8677
+ }
8678
+ /**
8679
+ * Lists all available browser extensions within this context from the cloud.
8680
+ * Uses the context service to list files under the extensions directory.
8681
+ *
8682
+ * @returns Promise that resolves to an array of Extension objects.
8683
+ * @throws {AgentBayError} If listing extensions fails.
8684
+ */
8685
+ async list() {
8686
+ await this._ensureInitialized();
8687
+ try {
8688
+ const fileListResult = await this.contextService.listFiles(
8689
+ this.contextId,
8690
+ EXTENSIONS_BASE_PATH,
8691
+ 1,
8692
+ // pageNumber
8693
+ 100
8694
+ // pageSize - reasonable limit for extensions
8695
+ );
8696
+ if (!fileListResult.success) {
8697
+ throw new AgentBayError("Failed to list extensions: Context file listing failed.");
8698
+ }
8699
+ const extensions = [];
8700
+ for (const fileEntry of fileListResult.entries) {
8701
+ const extensionId = fileEntry.fileName || fileEntry.filePath;
8702
+ extensions.push(new Extension(
8703
+ extensionId,
8704
+ fileEntry.fileName || extensionId,
8705
+ fileEntry.gmtCreate
8706
+ ));
8707
+ }
8708
+ return extensions;
8709
+ } catch (error) {
8710
+ if (error instanceof AgentBayError) {
8711
+ throw error;
8712
+ }
8713
+ throw new AgentBayError(`An error occurred while listing browser extensions: ${error instanceof Error ? error.message : String(error)}`);
8714
+ }
8715
+ }
8716
+ /**
8717
+ * Uploads a new browser extension from a local path into the current context.
8718
+ *
8719
+ * @param localPath - Path to the local extension file (must be a .zip file).
8720
+ * @returns Promise that resolves to an Extension object.
8721
+ * @throws {Error} If the local file doesn't exist.
8722
+ * @throws {Error} If the file format is not supported (only .zip is supported).
8723
+ * @throws {AgentBayError} If upload fails.
8724
+ */
8725
+ async create(localPath) {
8726
+ await this._ensureInitialized();
8727
+ if (!fs2.existsSync(localPath)) {
8728
+ throw new Error(`The specified local file was not found: ${localPath}`);
8729
+ }
8730
+ const fileExtension = path2.extname(localPath).toLowerCase();
8731
+ if (fileExtension !== ".zip") {
8732
+ throw new Error(`Unsupported plugin format '${fileExtension}'. Only ZIP format (.zip) is supported.`);
8733
+ }
8734
+ const extensionId = `ext_${crypto.randomBytes(16).toString("hex")}${fileExtension}`;
8735
+ const extensionName = path2.basename(localPath);
8736
+ const remotePath = `${EXTENSIONS_BASE_PATH}/${extensionId}`;
8737
+ await this._uploadToCloud(localPath, remotePath);
8738
+ return new Extension(extensionId, extensionName);
8739
+ }
8740
+ /**
8741
+ * Updates an existing browser extension in the current context with a new file.
8742
+ *
8743
+ * @param extensionId - ID of the extension to update.
8744
+ * @param newLocalPath - Path to the new local extension file.
8745
+ * @returns Promise that resolves to an Extension object.
8746
+ * @throws {Error} If the new local file doesn't exist.
8747
+ * @throws {Error} If the extension doesn't exist in the context.
8748
+ * @throws {AgentBayError} If update fails.
8749
+ */
8750
+ async update(extensionId, newLocalPath) {
8751
+ await this._ensureInitialized();
8752
+ if (!fs2.existsSync(newLocalPath)) {
8753
+ throw new Error(`The specified new local file was not found: ${newLocalPath}`);
8754
+ }
8755
+ const existingExtensions = await this.list();
8756
+ const extensionExists = existingExtensions.some((ext) => ext.id === extensionId);
8757
+ if (!extensionExists) {
8758
+ throw new Error(`Browser extension with ID '${extensionId}' not found in the context. Cannot update.`);
8759
+ }
8760
+ const remotePath = `${EXTENSIONS_BASE_PATH}/${extensionId}`;
8761
+ await this._uploadToCloud(newLocalPath, remotePath);
8762
+ return new Extension(extensionId, path2.basename(newLocalPath));
8763
+ }
8764
+ /**
8765
+ * Gets detailed information about a specific browser extension.
8766
+ *
8767
+ * @param extensionId - The ID of the extension to get info for.
8768
+ * @returns Promise that resolves to an Extension object if found, undefined otherwise.
8769
+ */
8770
+ async _getExtensionInfo(extensionId) {
8771
+ await this._ensureInitialized();
8772
+ try {
8773
+ const extensions = await this.list();
8774
+ return extensions.find((ext) => ext.id === extensionId);
8775
+ } catch (error) {
8776
+ logError(`An error occurred while getting extension info for '${extensionId}':`, error);
8777
+ return void 0;
8778
+ }
8779
+ }
8780
+ /**
8781
+ * Cleans up the auto-created context if it was created by this service.
8782
+ *
8783
+ * @returns Promise that resolves to true if cleanup was successful or not needed, false if cleanup failed.
8784
+ *
8785
+ * Note:
8786
+ * This method only works if the context was auto-created by this service.
8787
+ * For existing contexts, no cleanup is performed.
8788
+ */
8789
+ async cleanup() {
8790
+ await this._ensureInitialized();
8791
+ if (!this.autoCreated) {
8792
+ return true;
8793
+ }
8794
+ try {
8795
+ const deleteResult = await this.contextService.delete(this.extensionContext);
8796
+ if (deleteResult) {
8797
+ log(`Extension context deleted: ${this.contextName} (ID: ${this.contextId})`);
8798
+ return true;
8799
+ } else {
8800
+ logError(`Warning: Failed to delete extension context: ${this.contextName}`, new Error("Delete operation returned false"));
8801
+ return false;
8802
+ }
8803
+ } catch (error) {
8804
+ logError(`Warning: Failed to delete extension context:`, error);
8805
+ return false;
8806
+ }
8807
+ }
8808
+ /**
8809
+ * Deletes a browser extension from the current context.
8810
+ *
8811
+ * @param extensionId - ID of the extension to delete.
8812
+ * @returns Promise that resolves to true if deletion was successful, false otherwise.
8813
+ */
8814
+ async delete(extensionId) {
8815
+ await this._ensureInitialized();
8816
+ const remotePath = `${EXTENSIONS_BASE_PATH}/${extensionId}`;
8817
+ try {
8818
+ const deleteResult = await this.contextService.deleteFile(this.contextId, remotePath);
8819
+ return deleteResult.success;
8820
+ } catch (error) {
8821
+ logError(`An error occurred while deleting browser extension '${extensionId}':`, error);
8822
+ return false;
8823
+ }
8824
+ }
8825
+ /**
8826
+ * Create an ExtensionOption for the current context with specified extension IDs.
8827
+ *
8828
+ * This is a convenience method that creates an ExtensionOption using the current
8829
+ * service's contextId and the provided extension IDs. This option can then be
8830
+ * used with BrowserContext for browser session creation.
8831
+ *
8832
+ * @param extensionIds - List of extension IDs to include in the option.
8833
+ * These should be extensions that exist in the current context.
8834
+ * @returns ExtensionOption configuration object for browser extension integration.
8835
+ * @throws {Error} If extensionIds is empty or invalid.
8836
+ *
8837
+ * @example
8838
+ * ```typescript
8839
+ * // Create extensions
8840
+ * const ext1 = await extensionsService.create("/path/to/ext1.zip");
8841
+ * const ext2 = await extensionsService.create("/path/to/ext2.zip");
8842
+ *
8843
+ * // Create extension option for browser integration
8844
+ * const extOption = extensionsService.createExtensionOption([ext1.id, ext2.id]);
8845
+ *
8846
+ * // Use with BrowserContext
8847
+ * const browserContext = new BrowserContext({
8848
+ * contextId: "browser_session",
8849
+ * autoUpload: true,
8850
+ * extensionContextId: extOption.contextId,
8851
+ * extensionIds: extOption.extensionIds
8852
+ * });
8853
+ * ```
8854
+ */
8855
+ createExtensionOption(extensionIds) {
8856
+ if (!this.contextId) {
8857
+ throw new Error("Service not initialized. Please call an async method first or ensure context is created.");
8858
+ }
8859
+ return new ExtensionOption(
8860
+ this.contextId,
8861
+ extensionIds
8862
+ );
8863
+ }
8864
+ };
8865
+ __name(_ExtensionsService, "ExtensionsService");
8866
+ var ExtensionsService = _ExtensionsService;
8867
+
8484
8868
  // src/context-sync.ts
8485
8869
  init_cjs_shims();
8486
8870
  var UploadStrategy = /* @__PURE__ */ ((UploadStrategy2) => {
@@ -8491,12 +8875,41 @@ var DownloadStrategy = /* @__PURE__ */ ((DownloadStrategy2) => {
8491
8875
  DownloadStrategy2["DownloadAsync"] = "DownloadAsync";
8492
8876
  return DownloadStrategy2;
8493
8877
  })(DownloadStrategy || {});
8878
+ var _ExtractPolicyClass = class _ExtractPolicyClass {
8879
+ constructor(extract = true, deleteSrcFile = true, extractToCurrentFolder = false) {
8880
+ this.extract = true;
8881
+ this.deleteSrcFile = true;
8882
+ this.extractToCurrentFolder = false;
8883
+ this.extract = extract;
8884
+ this.deleteSrcFile = deleteSrcFile;
8885
+ this.extractToCurrentFolder = extractToCurrentFolder;
8886
+ }
8887
+ /**
8888
+ * Creates a new extract policy with default values
8889
+ */
8890
+ static default() {
8891
+ return new _ExtractPolicyClass();
8892
+ }
8893
+ /**
8894
+ * Converts to plain object for JSON serialization
8895
+ */
8896
+ toDict() {
8897
+ return {
8898
+ extract: this.extract,
8899
+ deleteSrcFile: this.deleteSrcFile,
8900
+ extractToCurrentFolder: this.extractToCurrentFolder
8901
+ };
8902
+ }
8903
+ };
8904
+ __name(_ExtractPolicyClass, "ExtractPolicyClass");
8905
+ var ExtractPolicyClass = _ExtractPolicyClass;
8494
8906
  var _SyncPolicyImpl = class _SyncPolicyImpl {
8495
8907
  constructor(policy) {
8496
8908
  if (policy) {
8497
8909
  this.uploadPolicy = policy.uploadPolicy;
8498
8910
  this.downloadPolicy = policy.downloadPolicy;
8499
8911
  this.deletePolicy = policy.deletePolicy;
8912
+ this.extractPolicy = policy.extractPolicy;
8500
8913
  this.bwList = policy.bwList;
8501
8914
  }
8502
8915
  this.ensureDefaults();
@@ -8511,6 +8924,9 @@ var _SyncPolicyImpl = class _SyncPolicyImpl {
8511
8924
  if (!this.deletePolicy) {
8512
8925
  this.deletePolicy = newDeletePolicy();
8513
8926
  }
8927
+ if (!this.extractPolicy) {
8928
+ this.extractPolicy = newExtractPolicy();
8929
+ }
8514
8930
  if (!this.bwList) {
8515
8931
  this.bwList = {
8516
8932
  whiteLists: [
@@ -8528,6 +8944,7 @@ var _SyncPolicyImpl = class _SyncPolicyImpl {
8528
8944
  uploadPolicy: this.uploadPolicy,
8529
8945
  downloadPolicy: this.downloadPolicy,
8530
8946
  deletePolicy: this.deletePolicy,
8947
+ extractPolicy: this.extractPolicy,
8531
8948
  bwList: this.bwList
8532
8949
  };
8533
8950
  }
@@ -8535,9 +8952,9 @@ var _SyncPolicyImpl = class _SyncPolicyImpl {
8535
8952
  __name(_SyncPolicyImpl, "SyncPolicyImpl");
8536
8953
  var SyncPolicyImpl = _SyncPolicyImpl;
8537
8954
  var _ContextSync = class _ContextSync {
8538
- constructor(contextId, path2, policy) {
8955
+ constructor(contextId, path3, policy) {
8539
8956
  this.contextId = contextId;
8540
- this.path = path2;
8957
+ this.path = path3;
8541
8958
  this.policy = policy;
8542
8959
  }
8543
8960
  // WithPolicy sets the policy and returns the context sync for chaining
@@ -8570,11 +8987,20 @@ function newDeletePolicy() {
8570
8987
  };
8571
8988
  }
8572
8989
  __name(newDeletePolicy, "newDeletePolicy");
8990
+ function newExtractPolicy() {
8991
+ return {
8992
+ extract: true,
8993
+ deleteSrcFile: true,
8994
+ extractToCurrentFolder: false
8995
+ };
8996
+ }
8997
+ __name(newExtractPolicy, "newExtractPolicy");
8573
8998
  function newSyncPolicy() {
8574
8999
  return {
8575
9000
  uploadPolicy: newUploadPolicy(),
8576
9001
  downloadPolicy: newDownloadPolicy(),
8577
9002
  deletePolicy: newDeletePolicy(),
9003
+ extractPolicy: newExtractPolicy(),
8578
9004
  bwList: {
8579
9005
  whiteLists: [
8580
9006
  {
@@ -8590,13 +9016,98 @@ function newSyncPolicyWithDefaults(policy) {
8590
9016
  return new SyncPolicyImpl(policy).toJSON();
8591
9017
  }
8592
9018
  __name(newSyncPolicyWithDefaults, "newSyncPolicyWithDefaults");
8593
- function newContextSync(contextId, path2, policy) {
8594
- return new ContextSync(contextId, path2, policy);
9019
+ function newContextSync(contextId, path3, policy) {
9020
+ return new ContextSync(contextId, path3, policy);
8595
9021
  }
8596
9022
  __name(newContextSync, "newContextSync");
8597
9023
 
8598
9024
  // src/session-params.ts
8599
9025
  init_cjs_shims();
9026
+ var _BrowserContext = class _BrowserContext {
9027
+ /**
9028
+ * Initialize BrowserContextImpl with optional extension support.
9029
+ *
9030
+ * @param contextId - ID of the browser context to bind to the session.
9031
+ * This identifies the browser instance for the session.
9032
+ * @param autoUpload - Whether to automatically upload browser data
9033
+ * when the session ends. Defaults to true.
9034
+ * @param extensionOption - Extension configuration object containing
9035
+ * contextId and extensionIds. This encapsulates
9036
+ * all extension-related configuration.
9037
+ * Defaults to undefined.
9038
+ *
9039
+ * Extension Configuration:
9040
+ * - **ExtensionOption**: Use extensionOption parameter with an ExtensionOption object
9041
+ * - **No Extensions**: Don't provide extensionOption parameter
9042
+ *
9043
+ * Auto-generation:
9044
+ * - extensionContextSyncs is automatically generated when extensionOption is provided
9045
+ * - extensionContextSyncs will be undefined if no extensionOption is provided
9046
+ * - extensionContextSyncs will be a ContextSync[] if extensionOption is valid
9047
+ */
9048
+ constructor(contextId, autoUpload = true, extensionOption) {
9049
+ this.contextId = contextId;
9050
+ this.autoUpload = autoUpload;
9051
+ this.extensionOption = extensionOption;
9052
+ if (extensionOption) {
9053
+ this.extensionContextId = extensionOption.contextId;
9054
+ this.extensionIds = extensionOption.extensionIds;
9055
+ this.extensionContextSyncs = this._createExtensionContextSyncs();
9056
+ } else {
9057
+ this.extensionContextId = void 0;
9058
+ this.extensionIds = [];
9059
+ this.extensionContextSyncs = void 0;
9060
+ }
9061
+ }
9062
+ /**
9063
+ * Create ContextSync configurations for browser extensions.
9064
+ *
9065
+ * This method is called only when extensionOption is provided and contains
9066
+ * valid extension configuration (contextId and extensionIds).
9067
+ *
9068
+ * @returns ContextSync[] - List of context sync configurations for extensions.
9069
+ * Returns empty list if extension configuration is invalid.
9070
+ */
9071
+ _createExtensionContextSyncs() {
9072
+ if (!this.extensionIds || this.extensionIds.length === 0 || !this.extensionContextId) {
9073
+ return [];
9074
+ }
9075
+ const whiteLists = this.extensionIds.map((extId) => ({
9076
+ path: extId,
9077
+ excludePaths: []
9078
+ }));
9079
+ const syncPolicy = {
9080
+ uploadPolicy: {
9081
+ ...newUploadPolicy(),
9082
+ autoUpload: false
9083
+ },
9084
+ extractPolicy: {
9085
+ ...newExtractPolicy(),
9086
+ extract: true,
9087
+ deleteSrcFile: true
9088
+ },
9089
+ bwList: {
9090
+ whiteLists
9091
+ }
9092
+ };
9093
+ const extensionSync = new ContextSync(
9094
+ this.extensionContextId,
9095
+ "/tmp/extensions/",
9096
+ syncPolicy
9097
+ );
9098
+ return [extensionSync];
9099
+ }
9100
+ /**
9101
+ * Get all context syncs including extension syncs.
9102
+ *
9103
+ * @returns ContextSync[] - All context sync configurations. Returns empty list if no extensions configured.
9104
+ */
9105
+ getAllContextSyncs() {
9106
+ return this.extensionContextSyncs || [];
9107
+ }
9108
+ };
9109
+ __name(_BrowserContext, "BrowserContext");
9110
+ var BrowserContext = _BrowserContext;
8600
9111
  var _CreateSessionParams = class _CreateSessionParams {
8601
9112
  constructor() {
8602
9113
  this.labels = {};
@@ -8659,8 +9170,8 @@ var _CreateSessionParams = class _CreateSessionParams {
8659
9170
  /**
8660
9171
  * AddContextSync adds a context sync configuration to the session parameters.
8661
9172
  */
8662
- addContextSync(contextId, path2, policy) {
8663
- const contextSync = new ContextSync(contextId, path2, policy);
9173
+ addContextSync(contextId, path3, policy) {
9174
+ const contextSync = new ContextSync(contextId, path3, policy);
8664
9175
  this.contextSync.push(contextSync);
8665
9176
  return this;
8666
9177
  }
@@ -8682,10 +9193,15 @@ var _CreateSessionParams = class _CreateSessionParams {
8682
9193
  * Convert to plain object for JSON serialization
8683
9194
  */
8684
9195
  toJSON() {
9196
+ let allContextSyncs = [...this.contextSync];
9197
+ if (this.browserContext && "getAllContextSyncs" in this.browserContext) {
9198
+ const extensionSyncs = this.browserContext.getAllContextSyncs();
9199
+ allContextSyncs = allContextSyncs.concat(extensionSyncs);
9200
+ }
8685
9201
  return {
8686
9202
  labels: this.labels,
8687
9203
  imageId: this.imageId,
8688
- contextSync: this.contextSync,
9204
+ contextSync: allContextSyncs,
8689
9205
  browserContext: this.browserContext,
8690
9206
  isVpc: this.isVpc,
8691
9207
  mcpPolicyId: this.mcpPolicyId
@@ -8699,7 +9215,18 @@ var _CreateSessionParams = class _CreateSessionParams {
8699
9215
  params.labels = config.labels || {};
8700
9216
  params.imageId = config.imageId;
8701
9217
  params.contextSync = config.contextSync || [];
8702
- params.browserContext = config.browserContext;
9218
+ if (config.browserContext) {
9219
+ if ("getAllContextSyncs" in config.browserContext) {
9220
+ params.browserContext = config.browserContext;
9221
+ } else {
9222
+ const bc = config.browserContext;
9223
+ params.browserContext = new BrowserContext(
9224
+ bc.contextId,
9225
+ bc.autoUpload,
9226
+ bc.extensionOption
9227
+ );
9228
+ }
9229
+ }
8703
9230
  params.isVpc = config.isVpc || false;
8704
9231
  params.mcpPolicyId = config.mcpPolicyId;
8705
9232
  return params;
@@ -8830,5 +9357,13 @@ __name(newCreateSessionParams, "newCreateSessionParams");
8830
9357
 
8831
9358
 
8832
9359
 
8833
- exports.APIError = APIError; exports.Agent = Agent; exports.AgentBay = AgentBay; exports.AgentBayError = AgentBayError; exports.Application = Application; exports.ApplicationError = ApplicationError; exports.ApplyMqttTokenRequest = ApplyMqttTokenRequest; exports.ApplyMqttTokenResponse = ApplyMqttTokenResponse; exports.ApplyMqttTokenResponseBody = ApplyMqttTokenResponseBody; exports.ApplyMqttTokenResponseBodyData = ApplyMqttTokenResponseBodyData; exports.AuthenticationError = AuthenticationError; exports.Browser = Browser; exports.BrowserAgent = BrowserAgent; exports.BrowserError = BrowserError; exports.BrowserOptionClass = BrowserOptionClass; exports.BrowserProxyClass = BrowserProxyClass; exports.CallMcpToolRequest = CallMcpToolRequest; exports.CallMcpToolResponse = CallMcpToolResponse; exports.CallMcpToolResponseBody = CallMcpToolResponseBody; exports.Client = Client; exports.Command = Command; exports.CommandError = CommandError; exports.Context = Context; exports.ContextManager = ContextManager; exports.ContextService = ContextService; exports.ContextSync = ContextSync; exports.CreateMcpSessionRequest = CreateMcpSessionRequest; exports.CreateMcpSessionRequestPersistenceDataList = CreateMcpSessionRequestPersistenceDataList; exports.CreateMcpSessionResponse = CreateMcpSessionResponse; exports.CreateMcpSessionResponseBody = CreateMcpSessionResponseBody; exports.CreateMcpSessionResponseBodyData = CreateMcpSessionResponseBodyData; exports.CreateMcpSessionShrinkRequest = CreateMcpSessionShrinkRequest; exports.CreateSessionParams = CreateSessionParams; exports.DeleteContextFileRequest = DeleteContextFileRequest; exports.DeleteContextFileResponse = DeleteContextFileResponse; exports.DeleteContextFileResponseBody = DeleteContextFileResponseBody; exports.DeleteContextRequest = DeleteContextRequest; exports.DeleteContextResponse = DeleteContextResponse; exports.DeleteContextResponseBody = DeleteContextResponseBody; exports.DescribeContextFilesRequest = DescribeContextFilesRequest; exports.DescribeContextFilesResponse = DescribeContextFilesResponse; exports.DescribeContextFilesResponseBody = DescribeContextFilesResponseBody; exports.DownloadStrategy = DownloadStrategy; exports.FileError = FileError; exports.FileSystem = FileSystem; exports.GetContextFileDownloadUrlRequest = GetContextFileDownloadUrlRequest; exports.GetContextFileDownloadUrlResponse = GetContextFileDownloadUrlResponse; exports.GetContextFileDownloadUrlResponseBody = GetContextFileDownloadUrlResponseBody; exports.GetContextFileUploadUrlRequest = GetContextFileUploadUrlRequest; exports.GetContextFileUploadUrlResponse = GetContextFileUploadUrlResponse; exports.GetContextFileUploadUrlResponseBody = GetContextFileUploadUrlResponseBody; exports.GetContextInfoRequest = GetContextInfoRequest; exports.GetContextInfoResponse = GetContextInfoResponse; exports.GetContextInfoResponseBody = GetContextInfoResponseBody; exports.GetContextInfoResponseBodyData = GetContextInfoResponseBodyData; exports.GetContextRequest = GetContextRequest; exports.GetContextResponse = GetContextResponse; exports.GetContextResponseBody = GetContextResponseBody; exports.GetContextResponseBodyData = GetContextResponseBodyData; exports.GetLabelRequest = GetLabelRequest; exports.GetLabelResponse = GetLabelResponse; exports.GetLabelResponseBody = GetLabelResponseBody; exports.GetLabelResponseBodyData = GetLabelResponseBodyData; exports.GetLinkRequest = GetLinkRequest; exports.GetLinkResponse = GetLinkResponse; exports.GetLinkResponseBody = GetLinkResponseBody; exports.GetLinkResponseBodyData = GetLinkResponseBodyData; exports.GetMcpResourceRequest = GetMcpResourceRequest; exports.GetMcpResourceResponse = GetMcpResourceResponse; exports.GetMcpResourceResponseBody = GetMcpResourceResponseBody; exports.GetMcpResourceResponseBodyData = GetMcpResourceResponseBodyData; exports.GetMcpResourceResponseBodyDataDesktopInfo = GetMcpResourceResponseBodyDataDesktopInfo; exports.InitBrowserRequest = InitBrowserRequest; exports.InitBrowserResponse = InitBrowserResponse; exports.InitBrowserResponseBody = InitBrowserResponseBody; exports.InitBrowserResponseBodyData = InitBrowserResponseBodyData; exports.KeyCode = KeyCode; exports.ListContextsRequest = ListContextsRequest; exports.ListContextsResponse = ListContextsResponse; exports.ListContextsResponseBody = ListContextsResponseBody; exports.ListContextsResponseBodyData = ListContextsResponseBodyData; exports.ListMcpToolsRequest = ListMcpToolsRequest; exports.ListMcpToolsResponse = ListMcpToolsResponse; exports.ListMcpToolsResponseBody = ListMcpToolsResponseBody; exports.ListSessionRequest = ListSessionRequest; exports.ListSessionResponse = ListSessionResponse; exports.ListSessionResponseBody = ListSessionResponseBody; exports.ListSessionResponseBodyData = ListSessionResponseBodyData; exports.ModifyContextRequest = ModifyContextRequest; exports.ModifyContextResponse = ModifyContextResponse; exports.ModifyContextResponseBody = ModifyContextResponseBody; exports.Oss = Oss; exports.OssError = OssError; exports.ReleaseMcpSessionRequest = ReleaseMcpSessionRequest; exports.ReleaseMcpSessionResponse = ReleaseMcpSessionResponse; exports.ReleaseMcpSessionResponseBody = ReleaseMcpSessionResponseBody; exports.Session = Session; exports.SessionError = SessionError; exports.SetLabelRequest = SetLabelRequest; exports.SetLabelResponse = SetLabelResponse; exports.SetLabelResponseBody = SetLabelResponseBody; exports.SyncContextRequest = SyncContextRequest; exports.SyncContextResponse = SyncContextResponse; exports.SyncContextResponseBody = SyncContextResponseBody; exports.SyncPolicyImpl = SyncPolicyImpl; exports.UI = UI; exports.UIError = UIError; exports.UploadStrategy = UploadStrategy; exports.log = log; exports.logError = logError; exports.newContextManager = newContextManager; exports.newContextSync = newContextSync; exports.newCreateSessionParams = newCreateSessionParams; exports.newDeletePolicy = newDeletePolicy; exports.newDownloadPolicy = newDownloadPolicy; exports.newSyncPolicy = newSyncPolicy; exports.newSyncPolicyWithDefaults = newSyncPolicyWithDefaults; exports.newUploadPolicy = newUploadPolicy;
9360
+
9361
+
9362
+
9363
+
9364
+
9365
+
9366
+
9367
+
9368
+ exports.APIError = APIError; exports.Agent = Agent; exports.AgentBay = AgentBay; exports.AgentBayError = AgentBayError; exports.Application = Application; exports.ApplicationError = ApplicationError; exports.ApplyMqttTokenRequest = ApplyMqttTokenRequest; exports.ApplyMqttTokenResponse = ApplyMqttTokenResponse; exports.ApplyMqttTokenResponseBody = ApplyMqttTokenResponseBody; exports.ApplyMqttTokenResponseBodyData = ApplyMqttTokenResponseBodyData; exports.AuthenticationError = AuthenticationError; exports.Browser = Browser; exports.BrowserAgent = BrowserAgent; exports.BrowserContext = BrowserContext; exports.BrowserError = BrowserError; exports.BrowserOptionClass = BrowserOptionClass; exports.BrowserProxyClass = BrowserProxyClass; exports.CallMcpToolRequest = CallMcpToolRequest; exports.CallMcpToolResponse = CallMcpToolResponse; exports.CallMcpToolResponseBody = CallMcpToolResponseBody; exports.Client = Client; exports.Command = Command; exports.CommandError = CommandError; exports.Context = Context; exports.ContextManager = ContextManager; exports.ContextService = ContextService; exports.ContextSync = ContextSync; exports.CreateMcpSessionRequest = CreateMcpSessionRequest; exports.CreateMcpSessionRequestPersistenceDataList = CreateMcpSessionRequestPersistenceDataList; exports.CreateMcpSessionResponse = CreateMcpSessionResponse; exports.CreateMcpSessionResponseBody = CreateMcpSessionResponseBody; exports.CreateMcpSessionResponseBodyData = CreateMcpSessionResponseBodyData; exports.CreateMcpSessionShrinkRequest = CreateMcpSessionShrinkRequest; exports.CreateSessionParams = CreateSessionParams; exports.DeleteContextFileRequest = DeleteContextFileRequest; exports.DeleteContextFileResponse = DeleteContextFileResponse; exports.DeleteContextFileResponseBody = DeleteContextFileResponseBody; exports.DeleteContextRequest = DeleteContextRequest; exports.DeleteContextResponse = DeleteContextResponse; exports.DeleteContextResponseBody = DeleteContextResponseBody; exports.DescribeContextFilesRequest = DescribeContextFilesRequest; exports.DescribeContextFilesResponse = DescribeContextFilesResponse; exports.DescribeContextFilesResponseBody = DescribeContextFilesResponseBody; exports.DownloadStrategy = DownloadStrategy; exports.Extension = Extension; exports.ExtensionOption = ExtensionOption; exports.ExtensionsService = ExtensionsService; exports.ExtractPolicyClass = ExtractPolicyClass; exports.FileError = FileError; exports.FileSystem = FileSystem; exports.GetContextFileDownloadUrlRequest = GetContextFileDownloadUrlRequest; exports.GetContextFileDownloadUrlResponse = GetContextFileDownloadUrlResponse; exports.GetContextFileDownloadUrlResponseBody = GetContextFileDownloadUrlResponseBody; exports.GetContextFileUploadUrlRequest = GetContextFileUploadUrlRequest; exports.GetContextFileUploadUrlResponse = GetContextFileUploadUrlResponse; exports.GetContextFileUploadUrlResponseBody = GetContextFileUploadUrlResponseBody; exports.GetContextInfoRequest = GetContextInfoRequest; exports.GetContextInfoResponse = GetContextInfoResponse; exports.GetContextInfoResponseBody = GetContextInfoResponseBody; exports.GetContextInfoResponseBodyData = GetContextInfoResponseBodyData; exports.GetContextRequest = GetContextRequest; exports.GetContextResponse = GetContextResponse; exports.GetContextResponseBody = GetContextResponseBody; exports.GetContextResponseBodyData = GetContextResponseBodyData; exports.GetLabelRequest = GetLabelRequest; exports.GetLabelResponse = GetLabelResponse; exports.GetLabelResponseBody = GetLabelResponseBody; exports.GetLabelResponseBodyData = GetLabelResponseBodyData; exports.GetLinkRequest = GetLinkRequest; exports.GetLinkResponse = GetLinkResponse; exports.GetLinkResponseBody = GetLinkResponseBody; exports.GetLinkResponseBodyData = GetLinkResponseBodyData; exports.GetMcpResourceRequest = GetMcpResourceRequest; exports.GetMcpResourceResponse = GetMcpResourceResponse; exports.GetMcpResourceResponseBody = GetMcpResourceResponseBody; exports.GetMcpResourceResponseBodyData = GetMcpResourceResponseBodyData; exports.GetMcpResourceResponseBodyDataDesktopInfo = GetMcpResourceResponseBodyDataDesktopInfo; exports.InitBrowserRequest = InitBrowserRequest; exports.InitBrowserResponse = InitBrowserResponse; exports.InitBrowserResponseBody = InitBrowserResponseBody; exports.InitBrowserResponseBodyData = InitBrowserResponseBodyData; exports.KeyCode = KeyCode; exports.ListContextsRequest = ListContextsRequest; exports.ListContextsResponse = ListContextsResponse; exports.ListContextsResponseBody = ListContextsResponseBody; exports.ListContextsResponseBodyData = ListContextsResponseBodyData; exports.ListMcpToolsRequest = ListMcpToolsRequest; exports.ListMcpToolsResponse = ListMcpToolsResponse; exports.ListMcpToolsResponseBody = ListMcpToolsResponseBody; exports.ListSessionRequest = ListSessionRequest; exports.ListSessionResponse = ListSessionResponse; exports.ListSessionResponseBody = ListSessionResponseBody; exports.ListSessionResponseBodyData = ListSessionResponseBodyData; exports.ModifyContextRequest = ModifyContextRequest; exports.ModifyContextResponse = ModifyContextResponse; exports.ModifyContextResponseBody = ModifyContextResponseBody; exports.Oss = Oss; exports.OssError = OssError; exports.ReleaseMcpSessionRequest = ReleaseMcpSessionRequest; exports.ReleaseMcpSessionResponse = ReleaseMcpSessionResponse; exports.ReleaseMcpSessionResponseBody = ReleaseMcpSessionResponseBody; exports.Session = Session; exports.SessionError = SessionError; exports.SetLabelRequest = SetLabelRequest; exports.SetLabelResponse = SetLabelResponse; exports.SetLabelResponseBody = SetLabelResponseBody; exports.SyncContextRequest = SyncContextRequest; exports.SyncContextResponse = SyncContextResponse; exports.SyncContextResponseBody = SyncContextResponseBody; exports.SyncPolicyImpl = SyncPolicyImpl; exports.UI = UI; exports.UIError = UIError; exports.UploadStrategy = UploadStrategy; exports.loadConfig = loadConfig; exports.loadDotEnv = loadDotEnv; exports.log = log; exports.logError = logError; exports.newContextManager = newContextManager; exports.newContextSync = newContextSync; exports.newCreateSessionParams = newCreateSessionParams; exports.newDeletePolicy = newDeletePolicy; exports.newDownloadPolicy = newDownloadPolicy; exports.newExtractPolicy = newExtractPolicy; exports.newSyncPolicy = newSyncPolicy; exports.newSyncPolicyWithDefaults = newSyncPolicyWithDefaults; exports.newUploadPolicy = newUploadPolicy;
8834
9369
  //# sourceMappingURL=index.cjs.map