wuying-agentbay-sdk 0.10.2 → 0.11.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.
Files changed (104) hide show
  1. package/dist/chunk-E7QC5S76.mjs +3143 -0
  2. package/dist/chunk-E7QC5S76.mjs.map +1 -0
  3. package/dist/chunk-ZUB35HKV.cjs +3134 -0
  4. package/dist/chunk-ZUB35HKV.cjs.map +1 -0
  5. package/dist/index.cjs +3588 -3921
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.mts +2088 -687
  8. package/dist/index.d.ts +2088 -687
  9. package/dist/index.mjs +3556 -3889
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/key-normalizer-AF7APGQZ.cjs +136 -0
  12. package/dist/key-normalizer-AF7APGQZ.cjs.map +1 -0
  13. package/dist/key-normalizer-QDBRLFHF.mjs +145 -0
  14. package/dist/key-normalizer-QDBRLFHF.mjs.map +1 -0
  15. package/dist/model-2G37RFQQ.cjs +188 -0
  16. package/dist/model-2G37RFQQ.cjs.map +1 -0
  17. package/dist/model-ZFTLKEMC.mjs +197 -0
  18. package/docs/api/README.md +26 -0
  19. package/docs/api/browser-use/browser.md +177 -0
  20. package/docs/api/browser-use/extension.md +284 -0
  21. package/docs/api/codespace/code.md +77 -0
  22. package/docs/api/common-features/advanced/agent.md +84 -0
  23. package/docs/api/common-features/advanced/oss.md +221 -0
  24. package/docs/api/common-features/basics/agentbay.md +181 -0
  25. package/docs/api/common-features/basics/command.md +83 -0
  26. package/docs/api/common-features/basics/context-manager.md +130 -0
  27. package/docs/api/common-features/basics/context-sync.md +51 -0
  28. package/docs/api/common-features/basics/context.md +348 -0
  29. package/docs/api/common-features/basics/filesystem.md +499 -0
  30. package/docs/api/common-features/basics/logging.md +77 -0
  31. package/docs/api/common-features/basics/session.md +412 -0
  32. package/docs/api/computer-use/computer.md +786 -0
  33. package/docs/api/mobile-use/mobile.md +395 -0
  34. package/docs/examples/README.md +332 -0
  35. package/docs/examples/basic-usage.ts +86 -0
  36. package/docs/examples/browser-use/browser/README.md +356 -0
  37. package/docs/examples/browser-use/browser/basic-usage.ts +136 -0
  38. package/docs/examples/browser-use/browser/browser-command-args.ts +117 -0
  39. package/docs/examples/browser-use/browser/browser-context-cookie-persistence.ts +348 -0
  40. package/docs/examples/browser-use/browser/browser-fingerprint-basic-usage.ts +121 -0
  41. package/docs/examples/browser-use/browser/browser-fingerprint-construct.ts +114 -0
  42. package/docs/examples/browser-use/browser/browser-fingerprint-local-sync.ts +98 -0
  43. package/docs/examples/browser-use/browser/browser-fingerprint-persistence.ts +242 -0
  44. package/docs/examples/browser-use/browser/browser-proxies.ts +149 -0
  45. package/docs/examples/browser-use/browser/browser-type-example.ts +266 -0
  46. package/docs/examples/browser-use/browser/browser-viewport.ts +129 -0
  47. package/docs/examples/browser-use/browser/call_for_user_jd.ts +184 -0
  48. package/docs/examples/browser-use/browser/captcha_tongcheng.ts +151 -0
  49. package/docs/examples/browser-use/browser/run-2048.ts +209 -0
  50. package/docs/examples/browser-use/browser/run-sudoku.ts +150 -0
  51. package/docs/examples/browser-use/browser/screenshot-example.ts +132 -0
  52. package/docs/examples/browser-use/extension-example/README.md +252 -0
  53. package/docs/examples/browser-use/extension-example/extension-example.ts +380 -0
  54. package/docs/examples/codespace/automation/automation-example.ts +322 -0
  55. package/docs/examples/common-features/advanced/agent-module-example/README.md +40 -0
  56. package/docs/examples/common-features/advanced/agent-module-example.ts +66 -0
  57. package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +212 -0
  58. package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +213 -0
  59. package/docs/examples/common-features/advanced/vpc-session-example/README.md +47 -0
  60. package/docs/examples/common-features/advanced/vpc-session-example.ts +106 -0
  61. package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +236 -0
  62. package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +236 -0
  63. package/docs/examples/common-features/basics/command-example/README.md +47 -0
  64. package/docs/examples/common-features/basics/command-example/command-example.ts +153 -0
  65. package/docs/examples/common-features/basics/context-management/README.md +55 -0
  66. package/docs/examples/common-features/basics/context-management/context-management.ts +140 -0
  67. package/docs/examples/common-features/basics/data-persistence/README.md +129 -0
  68. package/docs/examples/common-features/basics/data-persistence/context-sync-demo.md +144 -0
  69. package/docs/examples/common-features/basics/data-persistence/context-sync-demo.ts +275 -0
  70. package/docs/examples/common-features/basics/data-persistence/data-persistence.ts +259 -0
  71. package/docs/examples/common-features/basics/data-persistence/recycle-policy-example.ts +294 -0
  72. package/docs/examples/common-features/basics/filesystem-example/README.md +57 -0
  73. package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +164 -0
  74. package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +153 -0
  75. package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +168 -0
  76. package/docs/examples/common-features/basics/get/README.md +136 -0
  77. package/docs/examples/common-features/basics/get/main.ts +79 -0
  78. package/docs/examples/common-features/basics/list_sessions/README.md +54 -0
  79. package/docs/examples/common-features/basics/list_sessions/main.ts +258 -0
  80. package/docs/examples/common-features/basics/mcp_tool_direct_call/README.md +142 -0
  81. package/docs/examples/common-features/basics/mcp_tool_direct_call/main.ts +135 -0
  82. package/docs/examples/common-features/basics/session-creation/README.md +28 -0
  83. package/docs/examples/common-features/basics/session-creation/session-creation.ts +295 -0
  84. package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
  85. package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
  86. package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
  87. package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
  88. package/package.json +18 -11
  89. package/dist/application-KZWXH46T.mjs +0 -17
  90. package/dist/application-LMA7KSRH.cjs +0 -8
  91. package/dist/application-LMA7KSRH.cjs.map +0 -1
  92. package/dist/chunk-BQNGKBQF.mjs +0 -386
  93. package/dist/chunk-BQNGKBQF.mjs.map +0 -1
  94. package/dist/chunk-IOVGAAJL.cjs +0 -558
  95. package/dist/chunk-IOVGAAJL.cjs.map +0 -1
  96. package/dist/chunk-UF2TC2R4.mjs +0 -567
  97. package/dist/chunk-UF2TC2R4.mjs.map +0 -1
  98. package/dist/chunk-X6MS7Z5L.cjs +0 -377
  99. package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
  100. package/dist/window-DH37ZDD5.mjs +0 -17
  101. package/dist/window-DH37ZDD5.mjs.map +0 -1
  102. package/dist/window-U7N3H735.cjs +0 -8
  103. package/dist/window-U7N3H735.cjs.map +0 -1
  104. /package/dist/{application-KZWXH46T.mjs.map → model-ZFTLKEMC.mjs.map} +0 -0
@@ -0,0 +1,380 @@
1
+ /**
2
+ * Comprehensive Extension Management Example
3
+ *
4
+ * This example demonstrates how to use the TypeScript extension functionality
5
+ * to manage browser extensions in the Wuying AgentBay SDK.
6
+ *
7
+ * Features demonstrated:
8
+ * - Basic extension upload and management
9
+ * - Multiple extensions handling
10
+ * - Browser session integration
11
+ * - Development workflow patterns
12
+ * - Error handling and cleanup
13
+ */
14
+
15
+ import { AgentBay, ExtensionsService, Extension, ExtensionOption, BrowserContext } from "wuying-agentbay-sdk";
16
+ import * as fs from "fs";
17
+
18
+ /**
19
+ * Basic Extension Management Example
20
+ * Demonstrates fundamental extension operations
21
+ */
22
+ async function basicExtensionExample(): Promise<boolean> {
23
+ console.log("🚀 Starting basic extension example...");
24
+
25
+ // Initialize AgentBay client
26
+ const agentBay = new AgentBay({
27
+ apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
28
+ });
29
+
30
+ // Create extensions service with auto-generated context
31
+ const extensionsService = new ExtensionsService(agentBay);
32
+
33
+ try {
34
+ // Example extension path (update with your actual extension)
35
+ const extensionPath = "/path/to/your-extension.zip";
36
+
37
+ if (!fs.existsSync(extensionPath)) {
38
+ console.log(`❌ Extension file not found: ${extensionPath}`);
39
+ console.log("💡 Please update the extensionPath variable with a valid ZIP file");
40
+ console.log("📝 Continuing with simulated workflow...\n");
41
+ return false;
42
+ }
43
+
44
+ // Upload extension to cloud
45
+ console.log(`📦 Uploading extension: ${extensionPath}`);
46
+ const extension = await extensionsService.create(extensionPath);
47
+ console.log(`✅ Extension uploaded successfully!`);
48
+ console.log(` - Name: ${extension.name}`);
49
+ console.log(` - ID: ${extension.id}`);
50
+
51
+ // Create extension option for browser session
52
+ console.log("🔧 Creating extension configuration...");
53
+ const extOption = extensionsService.createExtensionOption([extension.id]);
54
+ console.log(`✅ Extension option created: ${extOption.toDisplayString()}`);
55
+
56
+ // Create browser session with extension
57
+ console.log("🌐 Creating browser session with extension...");
58
+
59
+ // Create session parameters with browser context configuration
60
+ // In a real implementation, you would use the BrowserContext class:
61
+ // const browserContext = new BrowserContext("basic_extension_session", true, extOption);
62
+ // For this example, we'll use a plain object to demonstrate the structure:
63
+ const sessionParams = {
64
+ labels: { purpose: "basic_extension_example", type: "demo" },
65
+ browserContext: new BrowserContext("basic_extension_session",true,extOption)
66
+
67
+ };
68
+
69
+ const sessionResult = await agentBay.create(sessionParams);
70
+ if (!sessionResult.success) {
71
+ console.log(`❌ Failed to create session: ${sessionResult.errorMessage}`);
72
+ return false;
73
+ }
74
+
75
+ const session = sessionResult.session;
76
+ console.log(`✅ Browser session created successfully!`);
77
+ console.log(` - Session ID: ${session.sessionId}`);
78
+ console.log(` - Extensions synchronized to: /tmp/extensions/`);
79
+
80
+ // List available extensions in context
81
+ console.log("\n📋 Listing available extensions:");
82
+ const extensions = await extensionsService.list();
83
+ for (const ext of extensions) {
84
+ console.log(` - ${ext.name} (ID: ${ext.id})`);
85
+ }
86
+
87
+ console.log("\n🎉 Basic extension example completed successfully!");
88
+ return true;
89
+
90
+ } catch (error) {
91
+ console.log(`❌ Error during basic extension example: ${error}`);
92
+ return false;
93
+ } finally {
94
+ // Clean up resources
95
+ console.log("\n🧹 Cleaning up resources...");
96
+ await extensionsService.cleanup();
97
+ console.log("✅ Cleanup completed\n");
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Multiple Extensions Example
103
+ * Demonstrates handling multiple extensions in a single session
104
+ */
105
+ async function multipleExtensionsExample(): Promise<boolean> {
106
+ console.log("🚀 Starting multiple extensions example...");
107
+
108
+ const agentBay = new AgentBay({
109
+ apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
110
+ });
111
+ const extensionsService = new ExtensionsService(agentBay, "multi_ext_demo");
112
+
113
+ try {
114
+ // List of extension paths (update with your actual extensions)
115
+ const extensionPaths = [
116
+ "/path/to/extension1.zip",
117
+ "/path/to/extension2.zip",
118
+ "/path/to/extension3.zip"
119
+ ];
120
+
121
+ // Filter existing files
122
+ const existingPaths = extensionPaths.filter(path => fs.existsSync(path));
123
+ if (existingPaths.length === 0) {
124
+ console.log("❌ No extension files found. Please update extensionPaths with valid ZIP files");
125
+ console.log("📝 Continuing with simulated workflow...\n");
126
+ return false;
127
+ }
128
+
129
+ console.log(`📦 Uploading ${existingPaths.length} extensions...`);
130
+
131
+ // Upload all extensions
132
+ const extensionIds: string[] = [];
133
+ for (const path of existingPaths) {
134
+ const ext = await extensionsService.create(path);
135
+ extensionIds.push(ext.id);
136
+ console.log(` ✅ ${ext.name} uploaded (ID: ${ext.id})`);
137
+ }
138
+
139
+ // Create session with all extensions
140
+ console.log("🔧 Creating configuration for all extensions...");
141
+ const extOption = extensionsService.createExtensionOption(extensionIds);
142
+
143
+ // Create session parameters with browser context configuration
144
+ // In a real implementation, you would use the BrowserContext class:
145
+ // const browserContext = new BrowserContext("multi_extension_session", true, extOption);
146
+ // For this example, we'll use a plain object to demonstrate the structure:
147
+ const sessionParams = {
148
+ labels: {
149
+ purpose: "multiple_extensions",
150
+ count: extensionIds.length.toString()
151
+ },
152
+ browserContext: new BrowserContext("multi_extension_session",true,extOption)
153
+
154
+ };
155
+
156
+ console.log("🌐 Creating browser session...");
157
+ const sessionResult = await agentBay.create(sessionParams);
158
+ const session = sessionResult.session;
159
+
160
+ console.log(`✅ Session created with ${extensionIds.length} extensions!`);
161
+ console.log(` - Session ID: ${session.sessionId}`);
162
+
163
+ console.log("\n🎉 Multiple extensions example completed successfully!");
164
+ return true;
165
+
166
+ } catch (error) {
167
+ console.log(`❌ Error: ${error}`);
168
+ return false;
169
+ } finally {
170
+ await extensionsService.cleanup();
171
+ console.log("✅ Multiple extensions cleanup completed\n");
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Extension Development Workflow Example
177
+ * Demonstrates a complete development and testing workflow
178
+ */
179
+ async function extensionDevelopmentWorkflow(): Promise<boolean> {
180
+ console.log("🚀 Starting extension development workflow...");
181
+
182
+ const agentBay = new AgentBay({
183
+ apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
184
+ });
185
+ const extensionsService = new ExtensionsService(agentBay, "dev_workflow");
186
+
187
+ try {
188
+ // Step 1: Upload initial extension
189
+ const initialExtensionPath = "/path/to/initial-extension.zip";
190
+ if (!fs.existsSync(initialExtensionPath)) {
191
+ console.log("❌ Initial extension file not found. Using simulated workflow.");
192
+ console.log("📝 In a real scenario, you would:");
193
+ console.log(" 1. Upload your extension ZIP file");
194
+ console.log(" 2. Create a test session with the extension");
195
+ console.log(" 3. Test extension functionality");
196
+ console.log(" 4. Update extension if needed");
197
+ console.log(" 5. Deploy to production\n");
198
+ return false;
199
+ }
200
+
201
+ console.log("📦 Step 1: Upload initial extension");
202
+ const extension = await extensionsService.create(initialExtensionPath);
203
+ console.log(`✅ Initial extension uploaded: ${extension.id}`);
204
+
205
+ // Step 2: Test with browser session
206
+ console.log("🌐 Step 2: Create test session");
207
+ const extOption = extensionsService.createExtensionOption([extension.id]);
208
+
209
+ // Create session parameters with browser context configuration
210
+ // In a real implementation, you would use the BrowserContext class:
211
+ // const browserContext = new BrowserContext("dev_test_session", true, extOption);
212
+ // For this example, we'll use a plain object to demonstrate the structure:
213
+ const sessionParams = {
214
+ labels: { purpose: "development", phase: "testing" },
215
+ browserContext: new BrowserContext("dev_test_session",true,extOption)
216
+ };
217
+
218
+ const sessionResult = await agentBay.create(sessionParams);
219
+ const session = sessionResult.session;
220
+ console.log(`✅ Test session created: ${session.sessionId}`);
221
+
222
+ // Step 3: Update extension (simulated)
223
+ console.log("🔄 Step 3: Update extension (simulated)");
224
+ const updatedExtensionPath = "/path/to/updated-extension.zip";
225
+ if (fs.existsSync(updatedExtensionPath)) {
226
+ const updatedExtension = await extensionsService.update(extension.id, updatedExtensionPath);
227
+ console.log(`✅ Extension updated: ${updatedExtension.name}`);
228
+ } else {
229
+ console.log("⚠ Updated extension file not found, skipping update step");
230
+ }
231
+
232
+ // Step 4: List all extensions in development context
233
+ console.log("📋 Step 4: Review all extensions in development");
234
+ const allExtensions = await extensionsService.list();
235
+ allExtensions.forEach((ext, index) => {
236
+ console.log(` ${index + 1}. ${ext.name} (ID: ${ext.id})`);
237
+ });
238
+
239
+ console.log("\n🎉 Extension development workflow completed successfully!");
240
+ return true;
241
+
242
+ } catch (error) {
243
+ console.log(`❌ Error in development workflow: ${error}`);
244
+ return false;
245
+ } finally {
246
+ await extensionsService.cleanup();
247
+ console.log("✅ Development workflow cleanup completed\n");
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Error Handling and Validation Example
253
+ * Demonstrates proper error handling patterns
254
+ */
255
+ function errorHandlingExample(): void {
256
+ console.log("🚀 Starting error handling example...");
257
+
258
+ try {
259
+ // This will throw an error - empty context ID
260
+ const invalidOption1 = new ExtensionOption("", ["ext_1"]);
261
+ } catch (error) {
262
+ console.log(`✅ Caught expected error: ${error instanceof Error ? error.message : String(error)}`);
263
+ }
264
+
265
+ try {
266
+ // This will also throw an error - empty extension IDs
267
+ const invalidOption2 = new ExtensionOption("valid-context", []);
268
+ } catch (error) {
269
+ console.log(`✅ Caught expected error: ${error instanceof Error ? error.message : String(error)}`);
270
+ }
271
+
272
+ // Valid configuration
273
+ const validOption = new ExtensionOption("valid-context", ["ext_1", "ext_2"]);
274
+ console.log(`✅ Valid option created: ${validOption.toDisplayString()}`);
275
+ console.log(`✅ Validation result: ${validOption.validate()}`);
276
+
277
+ console.log("\n🎉 Error handling example completed!\n");
278
+ }
279
+
280
+ /**
281
+ * Main execution function that runs all examples
282
+ */
283
+ async function extensionManagementExample(): Promise<void> {
284
+ console.log("=== Comprehensive Extension Management Examples ===\n");
285
+
286
+ // Check API key
287
+ if (!process.env.AGENTBAY_API_KEY) {
288
+ console.log("❌ Please set AGENTBAY_API_KEY environment variable");
289
+ console.log("💡 Example: export AGENTBAY_API_KEY='your-api-key-here'\n");
290
+ }
291
+
292
+ try {
293
+ // Run all examples
294
+ console.log("1. Basic Extension Example");
295
+ console.log("-".repeat(40));
296
+ await basicExtensionExample();
297
+
298
+ console.log("2. Multiple Extensions Example");
299
+ console.log("-".repeat(40));
300
+ await multipleExtensionsExample();
301
+
302
+ console.log("3. Extension Development Workflow");
303
+ console.log("-".repeat(40));
304
+ await extensionDevelopmentWorkflow();
305
+
306
+ console.log("4. Error Handling Example");
307
+ console.log("-".repeat(40));
308
+ errorHandlingExample();
309
+
310
+ console.log("=== All Extension Examples Completed Successfully! ===\n");
311
+
312
+ console.log("💡 Next steps:");
313
+ console.log(" - Update extension paths with your actual ZIP files");
314
+ console.log(" - Set AGENTBAY_API_KEY environment variable");
315
+ console.log(" - Check the API documentation for advanced usage");
316
+ console.log(" - Explore browser automation integration patterns");
317
+
318
+ } catch (error) {
319
+ console.error("❌ Extension management examples failed:", error);
320
+ throw error;
321
+ }
322
+ }
323
+
324
+ // Helper function to demonstrate batch extension creation
325
+ async function batchExtensionCreation(extensionsService: ExtensionsService, paths: string[]): Promise<Extension[]> {
326
+ const extensions: Extension[] = [];
327
+
328
+ for (const path of paths) {
329
+ try {
330
+ if (fs.existsSync(path)) {
331
+ const extension = await extensionsService.create(path);
332
+ extensions.push(extension);
333
+ console.log(`Created extension: ${extension.name}`);
334
+ } else {
335
+ console.log(`Skipping ${path}: File not found`);
336
+ }
337
+ } catch (error) {
338
+ console.error(`Failed to create extension from ${path}:`, error);
339
+ }
340
+ }
341
+
342
+ return extensions;
343
+ }
344
+
345
+ // Helper function to demonstrate extension validation
346
+ function validateExtensionOption(option: ExtensionOption): void {
347
+ console.log(`Validating extension option: ${option.toDisplayString()}`);
348
+
349
+ if (option.validate()) {
350
+ console.log("✅ Extension option is valid");
351
+ console.log(` Context ID: ${option.contextId}`);
352
+ console.log(` Extension count: ${option.extensionIds.length}`);
353
+ console.log(` Extension IDs: ${option.extensionIds.join(', ')}`);
354
+ } else {
355
+ console.log("❌ Extension option is invalid");
356
+ }
357
+ }
358
+
359
+ // Run the example if this file is executed directly
360
+ if (require.main === module) {
361
+ extensionManagementExample()
362
+ .then(() => {
363
+ console.log("Extension examples completed successfully!");
364
+ process.exit(0);
365
+ })
366
+ .catch((error) => {
367
+ console.error("Extension examples failed:", error);
368
+ process.exit(1);
369
+ });
370
+ }
371
+
372
+ export {
373
+ extensionManagementExample,
374
+ basicExtensionExample,
375
+ multipleExtensionsExample,
376
+ extensionDevelopmentWorkflow,
377
+ errorHandlingExample,
378
+ batchExtensionCreation,
379
+ validateExtensionOption,
380
+ };
@@ -0,0 +1,322 @@
1
+ /**
2
+ * AgentBay SDK - Codespace Automation Features Example (TypeScript)
3
+ *
4
+ * This example demonstrates how to use AgentBay SDK automation features in codespace environment, including:
5
+ * - Command execution
6
+ * - Code execution (Python and JavaScript)
7
+ * - Workflow orchestration
8
+ */
9
+
10
+ import { AgentBay } from 'wuying-agentbay-sdk';
11
+
12
+ async function main(): Promise<void> {
13
+ console.log('🚀 AgentBay Codespace Automation Features Example (TypeScript)');
14
+
15
+ // Get API key from environment variable or use a placeholder value
16
+ const apiKey = process.env.AGENTBAY_API_KEY || 'akm-xxx';
17
+ if (!process.env.AGENTBAY_API_KEY) {
18
+ console.log('Warning: Using placeholder API key. Set AGENTBAY_API_KEY environment variable for production use.');
19
+ }
20
+
21
+ // Initialize AgentBay client
22
+ const agentBay = new AgentBay({ apiKey });
23
+
24
+ // Create session
25
+ console.log('\n📱 Creating session...');
26
+ const sessionResult = await agentBay.create({imageId:'code_latest'});
27
+ if (!sessionResult.success) {
28
+ console.log(`❌ Session creation failed: ${sessionResult.errorMessage}`);
29
+ return;
30
+ }
31
+
32
+ const session = sessionResult.session;
33
+ console.log(`✅ Session created successfully: ${session.sessionId}`);
34
+
35
+ try {
36
+ // 1. Command execution example
37
+ await commandExecutionExample(session);
38
+
39
+ // 2. Code execution example
40
+ await codeExecutionExample(session);
41
+
42
+ // 3. Workflow orchestration example
43
+ await workflowExample(session);
44
+
45
+ } catch (error) {
46
+ console.log(`❌ Example execution failed: ${error}`);
47
+ } finally {
48
+ // Clean up session
49
+ console.log(`\n🧹 Cleaning up session: ${session.sessionId}`);
50
+ await agentBay.delete(session);
51
+ console.log('✅ Example execution completed');
52
+ }
53
+ }
54
+
55
+ async function commandExecutionExample(session: any): Promise<void> {
56
+ console.log('\n💻 === Command Execution Example ===');
57
+
58
+ // Basic command execution
59
+ const commands = [
60
+ 'whoami',
61
+ 'pwd',
62
+ 'ls -la /tmp',
63
+ 'df -h',
64
+ 'free -h'
65
+ ];
66
+
67
+ for (const cmd of commands) {
68
+ console.log(`\n🔄 Executing command: ${cmd}`);
69
+ const result = await session.command.executeCommand(cmd);
70
+
71
+ if (result.success) {
72
+ console.log(`✅ Output: ${result.output.trim()}`);
73
+ } else {
74
+ console.log(`❌ Command failed: ${result.errorMessage}`);
75
+ }
76
+ }
77
+
78
+ // Command execution with timeout
79
+ console.log('\n🔄 Executing command with timeout...');
80
+ const timeoutResult = await session.command.executeCommand('sleep 2', 5000);
81
+ if (timeoutResult.success) {
82
+ console.log('✅ Timeout command executed successfully');
83
+ } else {
84
+ console.log(`❌ Timeout command failed: ${timeoutResult.errorMessage}`);
85
+ }
86
+ }
87
+
88
+ async function codeExecutionExample(session: any): Promise<void> {
89
+ console.log('\n🐍 === Code Execution Example ===');
90
+
91
+ // Python code execution
92
+ const pythonCode = `
93
+ import sys
94
+ import os
95
+ import json
96
+ from datetime import datetime
97
+
98
+ # System information
99
+ system_info = {
100
+ "python_version": sys.version,
101
+ "current_directory": os.getcwd(),
102
+ "timestamp": datetime.now().isoformat(),
103
+ "environment_vars": len(os.environ)
104
+ }
105
+
106
+ print("Python code executed successfully!")
107
+ print(f"System info: {json.dumps(system_info, indent=2)}")
108
+
109
+ # Simple calculation
110
+ numbers = list(range(1, 11))
111
+ total = sum(numbers)
112
+ print(f"Sum of 1 to 10: {total}")
113
+ `;
114
+
115
+ console.log('🔄 Executing Python code...');
116
+ const pythonResult = await session.code.runCode(pythonCode, 'python');
117
+ if (pythonResult.success) {
118
+ console.log('✅ Python code executed successfully:');
119
+ console.log(pythonResult.result);
120
+ } else {
121
+ console.log(`❌ Python code execution failed: ${pythonResult.errorMessage}`);
122
+ }
123
+
124
+ // JavaScript code execution
125
+ const jsCode = `
126
+ console.log("JavaScript code executed successfully!");
127
+
128
+ // Get system information
129
+ const os = require('os');
130
+ const systemInfo = {
131
+ platform: os.platform(),
132
+ arch: os.arch(),
133
+ nodeVersion: process.version,
134
+ memory: Math.round(os.totalmem() / 1024 / 1024) + ' MB'
135
+ };
136
+
137
+ console.log("System info:", JSON.stringify(systemInfo, null, 2));
138
+
139
+ // Array operations
140
+ const numbers = [1, 2, 3, 4, 5];
141
+ const doubled = numbers.map(n => n * 2);
142
+ console.log("Original array:", numbers);
143
+ console.log("Doubled:", doubled);
144
+ `;
145
+
146
+ console.log('\n🔄 Executing JavaScript code...');
147
+ const jsResult = await session.code.runCode(jsCode, 'javascript');
148
+ if (jsResult.success) {
149
+ console.log('✅ JavaScript code executed successfully:');
150
+ console.log(jsResult.result);
151
+ } else {
152
+ console.log(`❌ JavaScript code execution failed: ${jsResult.errorMessage}`);
153
+ }
154
+ }
155
+
156
+ async function workflowExample(session: any): Promise<void> {
157
+ console.log('\n🔄 === Workflow Orchestration Example ===');
158
+
159
+ console.log('🔄 Executing data processing workflow...');
160
+
161
+ // Step 1: Create test data
162
+ console.log('Step 1: Creating test data...');
163
+ const createDataCode = `
164
+ import json
165
+ import random
166
+ from datetime import datetime, timedelta
167
+
168
+ # Generate test data
169
+ data = []
170
+ base_date = datetime.now()
171
+
172
+ for i in range(50):
173
+ record = {
174
+ "id": i + 1,
175
+ "name": f"User{i+1}",
176
+ "score": random.randint(60, 100),
177
+ "date": (base_date - timedelta(days=random.randint(0, 30))).isoformat(),
178
+ "category": random.choice(["A", "B", "C"])
179
+ }
180
+ data.append(record)
181
+
182
+ # Save data
183
+ with open('/tmp/test_data.json', 'w', encoding='utf-8') as f:
184
+ json.dump(data, f, ensure_ascii=False, indent=2)
185
+
186
+ print(f"Generated {len(data)} test records")
187
+ `;
188
+
189
+ const createResult = await session.code.runCode(createDataCode, 'python');
190
+ if (!createResult.success) {
191
+ console.log(`❌ Data creation failed: ${createResult.errorMessage}`);
192
+ return;
193
+ }
194
+ console.log('✅ Test data creation completed');
195
+
196
+ // Step 2: Data analysis (using JavaScript)
197
+ console.log('Step 2: Data analysis...');
198
+ const analysisCode = `
199
+ const fs = require('fs');
200
+
201
+ // Read data
202
+ const rawData = fs.readFileSync('/tmp/test_data.json', 'utf8');
203
+ const data = JSON.parse(rawData);
204
+
205
+ // Analyze data
206
+ const scores = data.map(record => record.score);
207
+ const categories = {};
208
+ data.forEach(record => {
209
+ const cat = record.category;
210
+ categories[cat] = (categories[cat] || 0) + 1;
211
+ });
212
+
213
+ const analysisResult = {
214
+ total_records: data.length,
215
+ average_score: scores.reduce((a, b) => a + b, 0) / scores.length,
216
+ max_score: Math.max(...scores),
217
+ min_score: Math.min(...scores),
218
+ category_distribution: categories
219
+ };
220
+
221
+ // Save analysis results
222
+ fs.writeFileSync('/tmp/analysis_result.json', JSON.stringify(analysisResult, null, 2));
223
+
224
+ console.log("Data analysis completed:");
225
+ Object.entries(analysisResult).forEach(([key, value]) => {
226
+ console.log(\` \${key}: \${JSON.stringify(value)}\`);
227
+ });
228
+ `;
229
+
230
+ const analysisResult = await session.code.runCode(analysisCode, 'javascript');
231
+ if (!analysisResult.success) {
232
+ console.log(`❌ Data analysis failed: ${analysisResult.errorMessage}`);
233
+ return;
234
+ }
235
+ console.log('✅ Data analysis completed');
236
+
237
+ // Step 3: Generate report
238
+ console.log('Step 3: Generating report...');
239
+ const reportCode = `
240
+ import json
241
+ from datetime import datetime
242
+
243
+ # Read analysis results
244
+ with open('/tmp/analysis_result.json', 'r', encoding='utf-8') as f:
245
+ analysis = json.load(f)
246
+
247
+ # Generate HTML report
248
+ html_report = f'''
249
+ <!DOCTYPE html>
250
+ <html>
251
+ <head>
252
+ <title>Data Analysis Report</title>
253
+ <meta charset="utf-8">
254
+ <style>
255
+ body {{ font-family: Arial, sans-serif; margin: 40px; }}
256
+ .header {{ background-color: #f0f8ff; padding: 20px; border-radius: 8px; }}
257
+ .metric {{ margin: 10px 0; padding: 10px; background-color: #f9f9f9; border-radius: 5px; }}
258
+ </style>
259
+ </head>
260
+ <body>
261
+ <div class="header">
262
+ <h1>Data Analysis Report (TypeScript Example)</h1>
263
+ <p>Generated at: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</p>
264
+ </div>
265
+
266
+ <div class="metric">
267
+ <h3>Basic Statistics</h3>
268
+ <p>Total records: {analysis['total_records']}</p>
269
+ <p>Average score: {analysis['average_score']:.2f}</p>
270
+ <p>Max score: {analysis['max_score']}</p>
271
+ <p>Min score: {analysis['min_score']}</p>
272
+ </div>
273
+
274
+ <div class="metric">
275
+ <h3>Category Distribution</h3>
276
+ '''
277
+
278
+ for category, count in analysis['category_distribution'].items():
279
+ html_report += f' <p>Category {category}: {count} records</p>\\n'
280
+
281
+ html_report += '''
282
+ </div>
283
+ </body>
284
+ </html>
285
+ '''
286
+
287
+ # Save report
288
+ with open('/tmp/report.html', 'w', encoding='utf-8') as f:
289
+ f.write(html_report)
290
+
291
+ print("HTML report generated: /tmp/report.html")
292
+ `;
293
+
294
+ const reportResult = await session.code.runCode(reportCode, 'python');
295
+ if (!reportResult.success) {
296
+ console.log(`❌ Report generation failed: ${reportResult.errorMessage}`);
297
+ return;
298
+ }
299
+ console.log('✅ Report generation completed');
300
+
301
+ // Step 4: Verify results
302
+ console.log('Step 4: Verifying results...');
303
+ const filesToCheck = ['/tmp/test_data.json', '/tmp/analysis_result.json', '/tmp/report.html'];
304
+
305
+ for (const filePath of filesToCheck) {
306
+ const result = await session.fileSystem.readFile(filePath);
307
+ if (result.success) {
308
+ console.log(`✅ File exists: ${filePath} (${result.content.length} bytes)`);
309
+ } else {
310
+ console.log(`❌ File not found: ${filePath}`);
311
+ }
312
+ }
313
+
314
+ console.log('🎉 Workflow execution completed!');
315
+ }
316
+
317
+ // Run example
318
+ if (require.main === module) {
319
+ main().catch(console.error);
320
+ }
321
+
322
+ export { main };