wuying-agentbay-sdk 0.10.2 → 0.12.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/chunk-BVWUCG4J.mjs +3402 -0
- package/dist/chunk-BVWUCG4J.mjs.map +1 -0
- package/dist/chunk-SL5GCAQE.cjs +3393 -0
- package/dist/chunk-SL5GCAQE.cjs.map +1 -0
- package/dist/index.cjs +4623 -3978
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +3934 -1964
- package/dist/index.d.ts +3934 -1964
- package/dist/index.mjs +4601 -3956
- package/dist/index.mjs.map +1 -1
- package/dist/key-normalizer-AF7APGQZ.cjs +136 -0
- package/dist/key-normalizer-AF7APGQZ.cjs.map +1 -0
- package/dist/key-normalizer-QDBRLFHF.mjs +145 -0
- package/dist/key-normalizer-QDBRLFHF.mjs.map +1 -0
- package/dist/model-CNCGFWJH.cjs +200 -0
- package/dist/model-CNCGFWJH.cjs.map +1 -0
- package/dist/model-LGWQJWKQ.mjs +209 -0
- package/docs/api/README.md +26 -0
- package/docs/api/browser-use/browser.md +177 -0
- package/docs/api/browser-use/extension.md +284 -0
- package/docs/api/codespace/code.md +77 -0
- package/docs/api/common-features/advanced/agent.md +84 -0
- package/docs/api/common-features/advanced/oss.md +221 -0
- package/docs/api/common-features/basics/agentbay.md +277 -0
- package/docs/api/common-features/basics/command.md +83 -0
- package/docs/api/common-features/basics/context-manager.md +149 -0
- package/docs/api/common-features/basics/context-sync.md +51 -0
- package/docs/api/common-features/basics/context.md +348 -0
- package/docs/api/common-features/basics/filesystem.md +499 -0
- package/docs/api/common-features/basics/logging.md +77 -0
- package/docs/api/common-features/basics/session.md +542 -0
- package/docs/api/computer-use/computer.md +786 -0
- package/docs/api/mobile-use/mobile.md +395 -0
- package/docs/examples/README.md +332 -0
- package/docs/examples/basic-usage.ts +86 -0
- package/docs/examples/browser-use/browser/README.md +356 -0
- package/docs/examples/browser-use/browser/basic-usage.ts +136 -0
- package/docs/examples/browser-use/browser/browser-command-args.ts +117 -0
- package/docs/examples/browser-use/browser/browser-context-cookie-persistence.ts +348 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-basic-usage.ts +121 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-construct.ts +114 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-local-sync.ts +98 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-persistence.ts +242 -0
- package/docs/examples/browser-use/browser/browser-proxies.ts +149 -0
- package/docs/examples/browser-use/browser/browser-type-example.ts +266 -0
- package/docs/examples/browser-use/browser/browser-viewport.ts +129 -0
- package/docs/examples/browser-use/browser/call_for_user_jd.ts +184 -0
- package/docs/examples/browser-use/browser/captcha_tongcheng.ts +151 -0
- package/docs/examples/browser-use/browser/run-2048.ts +209 -0
- package/docs/examples/browser-use/browser/run-sudoku.ts +150 -0
- package/docs/examples/browser-use/browser/screenshot-example.ts +132 -0
- package/docs/examples/browser-use/extension-example/README.md +252 -0
- package/docs/examples/browser-use/extension-example/extension-example.ts +381 -0
- package/docs/examples/codespace/automation/automation-example.ts +322 -0
- package/docs/examples/common-features/advanced/agent-module-example/README.md +40 -0
- package/docs/examples/common-features/advanced/agent-module-example.ts +66 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +212 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +213 -0
- package/docs/examples/common-features/advanced/vpc-session-example/README.md +47 -0
- package/docs/examples/common-features/advanced/vpc-session-example.ts +106 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +236 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +236 -0
- package/docs/examples/common-features/basics/command-example/README.md +47 -0
- package/docs/examples/common-features/basics/command-example/command-example.ts +153 -0
- package/docs/examples/common-features/basics/context-management/README.md +55 -0
- package/docs/examples/common-features/basics/context-management/context-management.ts +140 -0
- package/docs/examples/common-features/basics/data-persistence/README.md +129 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.md +144 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.ts +275 -0
- package/docs/examples/common-features/basics/data-persistence/data-persistence.ts +259 -0
- package/docs/examples/common-features/basics/data-persistence/recycle-policy-example.ts +294 -0
- package/docs/examples/common-features/basics/filesystem-example/README.md +57 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +164 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +153 -0
- package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +168 -0
- package/docs/examples/common-features/basics/get/README.md +136 -0
- package/docs/examples/common-features/basics/get/main.ts +79 -0
- package/docs/examples/common-features/basics/list_sessions/README.md +54 -0
- package/docs/examples/common-features/basics/list_sessions/main.ts +258 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/README.md +142 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/main.ts +135 -0
- package/docs/examples/common-features/basics/session-creation/README.md +28 -0
- package/docs/examples/common-features/basics/session-creation/session-creation.ts +295 -0
- package/docs/examples/common-features/basics/session-pause-resume/README.md +53 -0
- package/docs/examples/common-features/basics/session-pause-resume/session-pause-resume.ts +237 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
- package/docs/examples/mobile-use/mobile-simulate-basic-usage.ts +202 -0
- package/docs/examples/mobile-use/mobile-simulate-with-ctx.ts +170 -0
- package/package.json +19 -12
- package/dist/application-KZWXH46T.mjs +0 -17
- package/dist/application-LMA7KSRH.cjs +0 -8
- package/dist/application-LMA7KSRH.cjs.map +0 -1
- package/dist/chunk-BQNGKBQF.mjs +0 -386
- package/dist/chunk-BQNGKBQF.mjs.map +0 -1
- package/dist/chunk-IOVGAAJL.cjs +0 -558
- package/dist/chunk-IOVGAAJL.cjs.map +0 -1
- package/dist/chunk-UF2TC2R4.mjs +0 -567
- package/dist/chunk-UF2TC2R4.mjs.map +0 -1
- package/dist/chunk-X6MS7Z5L.cjs +0 -377
- package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
- package/dist/window-DH37ZDD5.mjs +0 -17
- package/dist/window-DH37ZDD5.mjs.map +0 -1
- package/dist/window-U7N3H735.cjs +0 -8
- package/dist/window-U7N3H735.cjs.map +0 -1
- /package/dist/{application-KZWXH46T.mjs.map → model-LGWQJWKQ.mjs.map} +0 -0
|
@@ -0,0 +1,381 @@
|
|
|
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
|
+
// @ts-nocheck
|
|
16
|
+
import { AgentBay, ExtensionsService, Extension, ExtensionOption, BrowserContext } from "wuying-agentbay-sdk";
|
|
17
|
+
import * as fs from "fs";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Basic Extension Management Example
|
|
21
|
+
* Demonstrates fundamental extension operations
|
|
22
|
+
*/
|
|
23
|
+
async function basicExtensionExample(): Promise<boolean> {
|
|
24
|
+
console.log("🚀 Starting basic extension example...");
|
|
25
|
+
|
|
26
|
+
// Initialize AgentBay client
|
|
27
|
+
const agentBay = new AgentBay({
|
|
28
|
+
apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// Create extensions service with auto-generated context
|
|
32
|
+
const extensionsService = new ExtensionsService(agentBay);
|
|
33
|
+
|
|
34
|
+
try {
|
|
35
|
+
// Example extension path (update with your actual extension)
|
|
36
|
+
const extensionPath = "/Users/shiwen/extension/welcome_extension.zip";
|
|
37
|
+
|
|
38
|
+
if (!fs.existsSync(extensionPath)) {
|
|
39
|
+
console.log(`❌ Extension file not found: ${extensionPath}`);
|
|
40
|
+
console.log("💡 Please update the extensionPath variable with a valid ZIP file");
|
|
41
|
+
console.log("📝 Continuing with simulated workflow...\n");
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Upload extension to cloud
|
|
46
|
+
console.log(`📦 Uploading extension: ${extensionPath}`);
|
|
47
|
+
const extension = await extensionsService.create(extensionPath);
|
|
48
|
+
console.log(`✅ Extension uploaded successfully!`);
|
|
49
|
+
console.log(` - Name: ${extension.name}`);
|
|
50
|
+
console.log(` - ID: ${extension.id}`);
|
|
51
|
+
|
|
52
|
+
// Create extension option for browser session
|
|
53
|
+
console.log("🔧 Creating extension configuration...");
|
|
54
|
+
const extOption = extensionsService.createExtensionOption([extension.id]);
|
|
55
|
+
console.log(`✅ Extension option created: ${extOption.toDisplayString()}`);
|
|
56
|
+
|
|
57
|
+
// Create browser session with extension
|
|
58
|
+
console.log("🌐 Creating browser session with extension...");
|
|
59
|
+
|
|
60
|
+
// Create session parameters with browser context configuration
|
|
61
|
+
// In a real implementation, you would use the BrowserContext class:
|
|
62
|
+
// const browserContext = new BrowserContext("basic_extension_session", true, extOption);
|
|
63
|
+
// For this example, we'll use a plain object to demonstrate the structure:
|
|
64
|
+
const sessionParams = {
|
|
65
|
+
labels: { purpose: "basic_extension_example", type: "demo" },
|
|
66
|
+
browserContext: new BrowserContext("basic_extension_session",true,extOption)
|
|
67
|
+
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const sessionResult = await agentBay.create(sessionParams);
|
|
71
|
+
if (!sessionResult.success) {
|
|
72
|
+
console.log(`❌ Failed to create session: ${sessionResult.errorMessage}`);
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const session = sessionResult.session;
|
|
77
|
+
console.log(`✅ Browser session created successfully!`);
|
|
78
|
+
console.log(` - Session ID: ${session.sessionId}`);
|
|
79
|
+
console.log(` - Extensions synchronized to: /tmp/extensions/`);
|
|
80
|
+
|
|
81
|
+
// List available extensions in context
|
|
82
|
+
console.log("\n📋 Listing available extensions:");
|
|
83
|
+
const extensions = await extensionsService.list();
|
|
84
|
+
for (const ext of extensions) {
|
|
85
|
+
console.log(` - ${ext.name} (ID: ${ext.id})`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
console.log("\n🎉 Basic extension example completed successfully!");
|
|
89
|
+
return true;
|
|
90
|
+
|
|
91
|
+
} catch (error) {
|
|
92
|
+
console.log(`❌ Error during basic extension example: ${error}`);
|
|
93
|
+
return false;
|
|
94
|
+
} finally {
|
|
95
|
+
// Clean up resources
|
|
96
|
+
console.log("\n🧹 Cleaning up resources...");
|
|
97
|
+
await extensionsService.cleanup();
|
|
98
|
+
console.log("✅ Cleanup completed\n");
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Multiple Extensions Example
|
|
104
|
+
* Demonstrates handling multiple extensions in a single session
|
|
105
|
+
*/
|
|
106
|
+
async function multipleExtensionsExample(): Promise<boolean> {
|
|
107
|
+
console.log("🚀 Starting multiple extensions example...");
|
|
108
|
+
|
|
109
|
+
const agentBay = new AgentBay({
|
|
110
|
+
apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
|
|
111
|
+
});
|
|
112
|
+
const extensionsService = new ExtensionsService(agentBay, "multi_ext_demo");
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
// List of extension paths (update with your actual extensions)
|
|
116
|
+
const extensionPaths = [
|
|
117
|
+
"/path/to/extension1.zip",
|
|
118
|
+
"/path/to/extension2.zip",
|
|
119
|
+
"/path/to/extension3.zip"
|
|
120
|
+
];
|
|
121
|
+
|
|
122
|
+
// Filter existing files
|
|
123
|
+
const existingPaths = extensionPaths.filter(path => fs.existsSync(path));
|
|
124
|
+
if (existingPaths.length === 0) {
|
|
125
|
+
console.log("❌ No extension files found. Please update extensionPaths with valid ZIP files");
|
|
126
|
+
console.log("📝 Continuing with simulated workflow...\n");
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
console.log(`📦 Uploading ${existingPaths.length} extensions...`);
|
|
131
|
+
|
|
132
|
+
// Upload all extensions
|
|
133
|
+
const extensionIds: string[] = [];
|
|
134
|
+
for (const path of existingPaths) {
|
|
135
|
+
const ext = await extensionsService.create(path);
|
|
136
|
+
extensionIds.push(ext.id);
|
|
137
|
+
console.log(` ✅ ${ext.name} uploaded (ID: ${ext.id})`);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Create session with all extensions
|
|
141
|
+
console.log("🔧 Creating configuration for all extensions...");
|
|
142
|
+
const extOption = extensionsService.createExtensionOption(extensionIds);
|
|
143
|
+
|
|
144
|
+
// Create session parameters with browser context configuration
|
|
145
|
+
// In a real implementation, you would use the BrowserContext class:
|
|
146
|
+
// const browserContext = new BrowserContext("multi_extension_session", true, extOption);
|
|
147
|
+
// For this example, we'll use a plain object to demonstrate the structure:
|
|
148
|
+
const sessionParams = {
|
|
149
|
+
labels: {
|
|
150
|
+
purpose: "multiple_extensions",
|
|
151
|
+
count: extensionIds.length.toString()
|
|
152
|
+
},
|
|
153
|
+
browserContext: new BrowserContext("multi_extension_session",true,extOption)
|
|
154
|
+
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
console.log("🌐 Creating browser session...");
|
|
158
|
+
const sessionResult = await agentBay.create(sessionParams);
|
|
159
|
+
const session = sessionResult.session;
|
|
160
|
+
|
|
161
|
+
console.log(`✅ Session created with ${extensionIds.length} extensions!`);
|
|
162
|
+
console.log(` - Session ID: ${session.sessionId}`);
|
|
163
|
+
|
|
164
|
+
console.log("\n🎉 Multiple extensions example completed successfully!");
|
|
165
|
+
return true;
|
|
166
|
+
|
|
167
|
+
} catch (error) {
|
|
168
|
+
console.log(`❌ Error: ${error}`);
|
|
169
|
+
return false;
|
|
170
|
+
} finally {
|
|
171
|
+
await extensionsService.cleanup();
|
|
172
|
+
console.log("✅ Multiple extensions cleanup completed\n");
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Extension Development Workflow Example
|
|
178
|
+
* Demonstrates a complete development and testing workflow
|
|
179
|
+
*/
|
|
180
|
+
async function extensionDevelopmentWorkflow(): Promise<boolean> {
|
|
181
|
+
console.log("🚀 Starting extension development workflow...");
|
|
182
|
+
|
|
183
|
+
const agentBay = new AgentBay({
|
|
184
|
+
apiKey: process.env.AGENTBAY_API_KEY || "your-api-key-here",
|
|
185
|
+
});
|
|
186
|
+
const extensionsService = new ExtensionsService(agentBay, "dev_workflow");
|
|
187
|
+
|
|
188
|
+
try {
|
|
189
|
+
// Step 1: Upload initial extension
|
|
190
|
+
const initialExtensionPath = "/path/to/initial-extension.zip";
|
|
191
|
+
if (!fs.existsSync(initialExtensionPath)) {
|
|
192
|
+
console.log("❌ Initial extension file not found. Using simulated workflow.");
|
|
193
|
+
console.log("📝 In a real scenario, you would:");
|
|
194
|
+
console.log(" 1. Upload your extension ZIP file");
|
|
195
|
+
console.log(" 2. Create a test session with the extension");
|
|
196
|
+
console.log(" 3. Test extension functionality");
|
|
197
|
+
console.log(" 4. Update extension if needed");
|
|
198
|
+
console.log(" 5. Deploy to production\n");
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
console.log("📦 Step 1: Upload initial extension");
|
|
203
|
+
const extension = await extensionsService.create(initialExtensionPath);
|
|
204
|
+
console.log(`✅ Initial extension uploaded: ${extension.id}`);
|
|
205
|
+
|
|
206
|
+
// Step 2: Test with browser session
|
|
207
|
+
console.log("🌐 Step 2: Create test session");
|
|
208
|
+
const extOption = extensionsService.createExtensionOption([extension.id]);
|
|
209
|
+
|
|
210
|
+
// Create session parameters with browser context configuration
|
|
211
|
+
// In a real implementation, you would use the BrowserContext class:
|
|
212
|
+
// const browserContext = new BrowserContext("dev_test_session", true, extOption);
|
|
213
|
+
// For this example, we'll use a plain object to demonstrate the structure:
|
|
214
|
+
const sessionParams = {
|
|
215
|
+
labels: { purpose: "development", phase: "testing" },
|
|
216
|
+
browserContext: new BrowserContext("dev_test_session",true,extOption)
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const sessionResult = await agentBay.create(sessionParams);
|
|
220
|
+
const session = sessionResult.session;
|
|
221
|
+
console.log(`✅ Test session created: ${session.sessionId}`);
|
|
222
|
+
|
|
223
|
+
// Step 3: Update extension (simulated)
|
|
224
|
+
console.log("🔄 Step 3: Update extension (simulated)");
|
|
225
|
+
const updatedExtensionPath = "/path/to/updated-extension.zip";
|
|
226
|
+
if (fs.existsSync(updatedExtensionPath)) {
|
|
227
|
+
const updatedExtension = await extensionsService.update(extension.id, updatedExtensionPath);
|
|
228
|
+
console.log(`✅ Extension updated: ${updatedExtension.name}`);
|
|
229
|
+
} else {
|
|
230
|
+
console.log("⚠ Updated extension file not found, skipping update step");
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Step 4: List all extensions in development context
|
|
234
|
+
console.log("📋 Step 4: Review all extensions in development");
|
|
235
|
+
const allExtensions = await extensionsService.list();
|
|
236
|
+
allExtensions.forEach((ext, index) => {
|
|
237
|
+
console.log(` ${index + 1}. ${ext.name} (ID: ${ext.id})`);
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
console.log("\n🎉 Extension development workflow completed successfully!");
|
|
241
|
+
return true;
|
|
242
|
+
|
|
243
|
+
} catch (error) {
|
|
244
|
+
console.log(`❌ Error in development workflow: ${error}`);
|
|
245
|
+
return false;
|
|
246
|
+
} finally {
|
|
247
|
+
await extensionsService.cleanup();
|
|
248
|
+
console.log("✅ Development workflow cleanup completed\n");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Error Handling and Validation Example
|
|
254
|
+
* Demonstrates proper error handling patterns
|
|
255
|
+
*/
|
|
256
|
+
function errorHandlingExample(): void {
|
|
257
|
+
console.log("🚀 Starting error handling example...");
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
// This will throw an error - empty context ID
|
|
261
|
+
const invalidOption1 = new ExtensionOption("", ["ext_1"]);
|
|
262
|
+
} catch (error) {
|
|
263
|
+
console.log(`✅ Caught expected error: ${error instanceof Error ? error.message : String(error)}`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
// This will also throw an error - empty extension IDs
|
|
268
|
+
const invalidOption2 = new ExtensionOption("valid-context", []);
|
|
269
|
+
} catch (error) {
|
|
270
|
+
console.log(`✅ Caught expected error: ${error instanceof Error ? error.message : String(error)}`);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// Valid configuration
|
|
274
|
+
const validOption = new ExtensionOption("valid-context", ["ext_1", "ext_2"]);
|
|
275
|
+
console.log(`✅ Valid option created: ${validOption.toDisplayString()}`);
|
|
276
|
+
console.log(`✅ Validation result: ${validOption.validate()}`);
|
|
277
|
+
|
|
278
|
+
console.log("\n🎉 Error handling example completed!\n");
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Main execution function that runs all examples
|
|
283
|
+
*/
|
|
284
|
+
async function extensionManagementExample(): Promise<void> {
|
|
285
|
+
console.log("=== Comprehensive Extension Management Examples ===\n");
|
|
286
|
+
|
|
287
|
+
// Check API key
|
|
288
|
+
if (!process.env.AGENTBAY_API_KEY) {
|
|
289
|
+
console.log("❌ Please set AGENTBAY_API_KEY environment variable");
|
|
290
|
+
console.log("💡 Example: export AGENTBAY_API_KEY='your-api-key-here'\n");
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
try {
|
|
294
|
+
// Run all examples
|
|
295
|
+
console.log("1. Basic Extension Example");
|
|
296
|
+
console.log("-".repeat(40));
|
|
297
|
+
await basicExtensionExample();
|
|
298
|
+
|
|
299
|
+
console.log("2. Multiple Extensions Example");
|
|
300
|
+
console.log("-".repeat(40));
|
|
301
|
+
await multipleExtensionsExample();
|
|
302
|
+
|
|
303
|
+
console.log("3. Extension Development Workflow");
|
|
304
|
+
console.log("-".repeat(40));
|
|
305
|
+
await extensionDevelopmentWorkflow();
|
|
306
|
+
|
|
307
|
+
console.log("4. Error Handling Example");
|
|
308
|
+
console.log("-".repeat(40));
|
|
309
|
+
errorHandlingExample();
|
|
310
|
+
|
|
311
|
+
console.log("=== All Extension Examples Completed Successfully! ===\n");
|
|
312
|
+
|
|
313
|
+
console.log("💡 Next steps:");
|
|
314
|
+
console.log(" - Update extension paths with your actual ZIP files");
|
|
315
|
+
console.log(" - Set AGENTBAY_API_KEY environment variable");
|
|
316
|
+
console.log(" - Check the API documentation for advanced usage");
|
|
317
|
+
console.log(" - Explore browser automation integration patterns");
|
|
318
|
+
|
|
319
|
+
} catch (error) {
|
|
320
|
+
console.error("❌ Extension management examples failed:", error);
|
|
321
|
+
throw error;
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Helper function to demonstrate batch extension creation
|
|
326
|
+
async function batchExtensionCreation(extensionsService: ExtensionsService, paths: string[]): Promise<Extension[]> {
|
|
327
|
+
const extensions: Extension[] = [];
|
|
328
|
+
|
|
329
|
+
for (const path of paths) {
|
|
330
|
+
try {
|
|
331
|
+
if (fs.existsSync(path)) {
|
|
332
|
+
const extension = await extensionsService.create(path);
|
|
333
|
+
extensions.push(extension);
|
|
334
|
+
console.log(`Created extension: ${extension.name}`);
|
|
335
|
+
} else {
|
|
336
|
+
console.log(`Skipping ${path}: File not found`);
|
|
337
|
+
}
|
|
338
|
+
} catch (error) {
|
|
339
|
+
console.error(`Failed to create extension from ${path}:`, error);
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
return extensions;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// Helper function to demonstrate extension validation
|
|
347
|
+
function validateExtensionOption(option: ExtensionOption): void {
|
|
348
|
+
console.log(`Validating extension option: ${option.toDisplayString()}`);
|
|
349
|
+
|
|
350
|
+
if (option.validate()) {
|
|
351
|
+
console.log("✅ Extension option is valid");
|
|
352
|
+
console.log(` Context ID: ${option.contextId}`);
|
|
353
|
+
console.log(` Extension count: ${option.extensionIds.length}`);
|
|
354
|
+
console.log(` Extension IDs: ${option.extensionIds.join(', ')}`);
|
|
355
|
+
} else {
|
|
356
|
+
console.log("❌ Extension option is invalid");
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Run the example if this file is executed directly
|
|
361
|
+
if (require.main === module) {
|
|
362
|
+
extensionManagementExample()
|
|
363
|
+
.then(() => {
|
|
364
|
+
console.log("Extension examples completed successfully!");
|
|
365
|
+
process.exit(0);
|
|
366
|
+
})
|
|
367
|
+
.catch((error) => {
|
|
368
|
+
console.error("Extension examples failed:", error);
|
|
369
|
+
process.exit(1);
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export {
|
|
374
|
+
extensionManagementExample,
|
|
375
|
+
basicExtensionExample,
|
|
376
|
+
multipleExtensionsExample,
|
|
377
|
+
extensionDevelopmentWorkflow,
|
|
378
|
+
errorHandlingExample,
|
|
379
|
+
batchExtensionCreation,
|
|
380
|
+
validateExtensionOption,
|
|
381
|
+
};
|
|
@@ -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 };
|