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,236 @@
|
|
|
1
|
+
# Archive Upload Mode Context Sync Example
|
|
2
|
+
|
|
3
|
+
This directory contains examples demonstrating the Archive upload mode functionality for context synchronization in the AgentBay SDK.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
The Archive upload mode is designed for efficient file transfer by compressing files before uploading them to the context storage. This is particularly useful when:
|
|
8
|
+
|
|
9
|
+
- Working with large files
|
|
10
|
+
- Dealing with many files
|
|
11
|
+
- Optimizing bandwidth usage
|
|
12
|
+
- Reducing upload time for compressible content
|
|
13
|
+
|
|
14
|
+
## Files
|
|
15
|
+
|
|
16
|
+
### `archive-upload-mode-example.ts`
|
|
17
|
+
|
|
18
|
+
A comprehensive example that demonstrates:
|
|
19
|
+
|
|
20
|
+
1. **Context Creation**: Creating a context for Archive upload mode
|
|
21
|
+
2. **Sync Policy Configuration**: Setting up sync policy with Archive uploadMode
|
|
22
|
+
3. **Session Management**: Creating and managing sessions with context sync
|
|
23
|
+
4. **File Operations**: Writing files to the context path
|
|
24
|
+
5. **Context Sync**: Synchronizing context before retrieving information
|
|
25
|
+
6. **Context Info**: Retrieving context status information
|
|
26
|
+
7. **File Listing**: Listing files in context sync directory
|
|
27
|
+
8. **Cleanup**: Proper session cleanup and error handling
|
|
28
|
+
|
|
29
|
+
## Key Features Demonstrated
|
|
30
|
+
|
|
31
|
+
### Archive Upload Mode Configuration
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
import { UploadMode } from "wuying-agentbay-sdk";
|
|
35
|
+
|
|
36
|
+
// Configure sync policy with Archive upload mode
|
|
37
|
+
const syncPolicy = newSyncPolicy();
|
|
38
|
+
syncPolicy.uploadPolicy!.uploadMode = UploadMode.Archive; // Set to Archive mode
|
|
39
|
+
|
|
40
|
+
// Create context sync with Archive mode
|
|
41
|
+
const contextSync = newContextSync(
|
|
42
|
+
contextId,
|
|
43
|
+
"/tmp/archive-mode-test",
|
|
44
|
+
syncPolicy
|
|
45
|
+
);
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Session Creation with Context Sync
|
|
49
|
+
|
|
50
|
+
```typescript
|
|
51
|
+
const sessionParams: CreateSessionParams = {
|
|
52
|
+
labels: {
|
|
53
|
+
example: `archive-mode-${uniqueId}`,
|
|
54
|
+
type: "archive-upload-demo",
|
|
55
|
+
uploadMode: UploadMode.Archive
|
|
56
|
+
},
|
|
57
|
+
contextSync: [contextSync]
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const sessionResult = await agentBay.create(sessionParams);
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### File Operations
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
const fileSystem = new FileSystem(session);
|
|
67
|
+
|
|
68
|
+
// Write file to context path
|
|
69
|
+
const writeResult = await fileSystem.writeFile(filePath, fileContent, "overwrite");
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
### Context Sync and Information Retrieval
|
|
73
|
+
|
|
74
|
+
```typescript
|
|
75
|
+
// Call context sync before getting info
|
|
76
|
+
const syncResult = await session.context.sync();
|
|
77
|
+
|
|
78
|
+
// Get context status information after sync
|
|
79
|
+
const infoResult = await session.context.info();
|
|
80
|
+
|
|
81
|
+
// Display context status details
|
|
82
|
+
infoResult.contextStatusData.forEach((status, index) => {
|
|
83
|
+
console.log(`Context ID: ${status.contextId}`);
|
|
84
|
+
console.log(`Path: ${status.path}`);
|
|
85
|
+
console.log(`Status: ${status.status}`);
|
|
86
|
+
console.log(`Task Type: ${status.taskType}`);
|
|
87
|
+
});
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### File Listing in Context Directory
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
// List files in context sync directory
|
|
94
|
+
const listResult = await agentBay.context.listFiles(contextId, syncDirPath, 1, 10);
|
|
95
|
+
|
|
96
|
+
// Display file entries
|
|
97
|
+
listResult.entries.forEach((entry, index) => {
|
|
98
|
+
console.log(`FilePath: ${entry.filePath}`);
|
|
99
|
+
console.log(`FileType: ${entry.fileType}`);
|
|
100
|
+
console.log(`FileName: ${entry.fileName}`);
|
|
101
|
+
console.log(`Size: ${entry.size} bytes`);
|
|
102
|
+
});
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Running the Example
|
|
106
|
+
|
|
107
|
+
### Prerequisites
|
|
108
|
+
|
|
109
|
+
1. **Environment Setup**: Set your AgentBay API key
|
|
110
|
+
```bash
|
|
111
|
+
export AGENTBAY_API_KEY="your-api-key-here"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
2. **Dependencies**: Ensure you have the AgentBay SDK installed
|
|
115
|
+
```bash
|
|
116
|
+
npm install
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Execution
|
|
120
|
+
|
|
121
|
+
```bash
|
|
122
|
+
# Navigate to the project root
|
|
123
|
+
cd /path/to/wuying-agentbay-sdk
|
|
124
|
+
|
|
125
|
+
# Run the example
|
|
126
|
+
npx ts-node docs/example/archive-upload-mode-example.ts
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Expected Output
|
|
130
|
+
|
|
131
|
+
The example will output detailed logs showing:
|
|
132
|
+
|
|
133
|
+
```
|
|
134
|
+
🚀 Archive Upload Mode Context Sync Example
|
|
135
|
+
============================================================
|
|
136
|
+
|
|
137
|
+
📦 Step 1: Creating context for Archive upload mode...
|
|
138
|
+
✅ Context created successfully!
|
|
139
|
+
Context ID: ctx_xxxxx
|
|
140
|
+
Request ID: req_xxxxx
|
|
141
|
+
|
|
142
|
+
⚙️ Step 2: Configuring sync policy with Archive upload mode...
|
|
143
|
+
✅ Sync policy configured with uploadMode: Archive
|
|
144
|
+
|
|
145
|
+
🔧 Step 3: Creating context sync configuration...
|
|
146
|
+
✅ Context sync created:
|
|
147
|
+
Context ID: ctx_xxxxx
|
|
148
|
+
Path: /tmp/archive-mode-test
|
|
149
|
+
Upload Mode: Archive
|
|
150
|
+
|
|
151
|
+
🏗️ Step 4: Creating session with Archive mode context sync...
|
|
152
|
+
✅ Session created successfully!
|
|
153
|
+
Session ID: sess_xxxxx
|
|
154
|
+
Request ID: req_xxxxx
|
|
155
|
+
App Instance ID: app_xxxxx
|
|
156
|
+
|
|
157
|
+
📝 Step 5: Creating test files in Archive mode context...
|
|
158
|
+
📄 Creating file: /tmp/archive-mode-test/test-file-5kb.txt
|
|
159
|
+
📊 File content size: 5120 bytes
|
|
160
|
+
✅ File write successful!
|
|
161
|
+
Request ID: req_xxxxx
|
|
162
|
+
|
|
163
|
+
📊 Step 6: Testing context sync and info functionality...
|
|
164
|
+
🔄 Calling context sync before getting info...
|
|
165
|
+
✅ Context sync successful!
|
|
166
|
+
Sync Request ID: req_xxxxx
|
|
167
|
+
📋 Calling context info after sync...
|
|
168
|
+
✅ Context info retrieved successfully!
|
|
169
|
+
Info Request ID: req_xxxxx
|
|
170
|
+
Context status data count: X
|
|
171
|
+
|
|
172
|
+
📋 Context status details:
|
|
173
|
+
[0] Context ID: ctx_xxxxx
|
|
174
|
+
Path: /tmp/archive-mode-test
|
|
175
|
+
Status: Success
|
|
176
|
+
Task Type: upload
|
|
177
|
+
|
|
178
|
+
🔍 Step 7: Listing files in context sync directory...
|
|
179
|
+
✅ List files successful!
|
|
180
|
+
Request ID: req_xxxxx
|
|
181
|
+
Total files found: X
|
|
182
|
+
|
|
183
|
+
📋 Files in context sync directory:
|
|
184
|
+
[0] FilePath: /tmp/archive-mode-test/test-file-5kb.txt
|
|
185
|
+
FileType: file
|
|
186
|
+
FileName: test-file-5kb.txt
|
|
187
|
+
Size: 5120 bytes
|
|
188
|
+
|
|
189
|
+
🎉 Archive upload mode example completed successfully!
|
|
190
|
+
✅ All operations completed without errors.
|
|
191
|
+
|
|
192
|
+
🧹 Step 8: Cleaning up session...
|
|
193
|
+
✅ Session deleted successfully!
|
|
194
|
+
Success: true
|
|
195
|
+
Request ID: req_xxxxx
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
## Related Documentation
|
|
199
|
+
|
|
200
|
+
- [Context Sync Documentation](../../../../../../docs/guides/common-features/basics/data-persistence.md)
|
|
201
|
+
- [Session Management Guide](../../../../../../docs/guides/common-features/basics/session-management.md)
|
|
202
|
+
- [File Operations Guide](../../../../../../docs/guides/common-features/basics/file-operations.md)
|
|
203
|
+
|
|
204
|
+
## Troubleshooting
|
|
205
|
+
|
|
206
|
+
### Common Issues
|
|
207
|
+
|
|
208
|
+
1. **API Key Not Set**
|
|
209
|
+
```
|
|
210
|
+
Warning: AGENTBAY_API_KEY environment variable not set
|
|
211
|
+
```
|
|
212
|
+
**Solution**: Set the environment variable or update the API key in the code
|
|
213
|
+
|
|
214
|
+
2. **Context Creation Failed**
|
|
215
|
+
```
|
|
216
|
+
Context creation failed: [error message]
|
|
217
|
+
```
|
|
218
|
+
**Solution**: Check your API key and network connectivity
|
|
219
|
+
|
|
220
|
+
3. **Session Creation Failed**
|
|
221
|
+
```
|
|
222
|
+
Session creation failed: [error message]
|
|
223
|
+
```
|
|
224
|
+
**Solution**: Verify context sync configuration and try again
|
|
225
|
+
|
|
226
|
+
4. **File Operation Failed**
|
|
227
|
+
```
|
|
228
|
+
File write failed: [error message]
|
|
229
|
+
```
|
|
230
|
+
**Solution**: Check file path permissions and available disk space
|
|
231
|
+
|
|
232
|
+
## Support
|
|
233
|
+
|
|
234
|
+
For additional help:
|
|
235
|
+
- [GitHub Issues](https://github.com/aliyun/wuying-agentbay-sdk/issues)
|
|
236
|
+
- [Documentation Home](../../../../../docs/api/README.md)
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { AgentBay, CreateSessionParams, Session, newContextSync, newSyncPolicy, FileSystem, UploadMode } from "wuying-agentbay-sdk";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Archive Upload Mode Context Sync Example
|
|
5
|
+
*
|
|
6
|
+
* This example demonstrates how to use Archive upload mode for context synchronization.
|
|
7
|
+
* Archive mode compresses files before uploading, which is more efficient for large files
|
|
8
|
+
* or when dealing with many files.
|
|
9
|
+
*
|
|
10
|
+
* Features demonstrated:
|
|
11
|
+
* - Creating context with Archive upload mode
|
|
12
|
+
* - Session creation with context sync
|
|
13
|
+
* - File operations in the context path
|
|
14
|
+
* - Context sync and info operations
|
|
15
|
+
* - Proper cleanup and error handling
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
function getAPIKey(): string {
|
|
19
|
+
const apiKey = process.env.AGENTBAY_API_KEY;
|
|
20
|
+
if (!apiKey) {
|
|
21
|
+
console.warn("Warning: AGENTBAY_API_KEY environment variable not set. Using default key.");
|
|
22
|
+
return "your-api-key-here"; // Replace with your actual API key
|
|
23
|
+
}
|
|
24
|
+
return apiKey;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function generateUniqueId(): string {
|
|
28
|
+
const timestamp = Date.now() * 1000 + Math.floor(Math.random() * 1000);
|
|
29
|
+
const randomPart = Math.floor(Math.random() * 10000);
|
|
30
|
+
return `${timestamp}-${randomPart}`;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function archiveUploadModeExample(): Promise<void> {
|
|
34
|
+
console.log("🚀 Archive Upload Mode Context Sync Example");
|
|
35
|
+
console.log("=" .repeat(60));
|
|
36
|
+
|
|
37
|
+
// Initialize AgentBay client
|
|
38
|
+
const agentBay = new AgentBay({ apiKey: getAPIKey() });
|
|
39
|
+
const uniqueId = generateUniqueId();
|
|
40
|
+
|
|
41
|
+
let session: Session | null = null;
|
|
42
|
+
|
|
43
|
+
try {
|
|
44
|
+
// Step 1: Create context for Archive mode
|
|
45
|
+
console.log("\n📦 Step 1: Creating context for Archive upload mode...");
|
|
46
|
+
const contextName = `archive-mode-context-${uniqueId}`;
|
|
47
|
+
const contextResult = await agentBay.context.get(contextName, true);
|
|
48
|
+
|
|
49
|
+
if (!contextResult.success) {
|
|
50
|
+
throw new Error(`Context creation failed: ${contextResult.errorMessage}`);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
console.log(`✅ Context created successfully!`);
|
|
54
|
+
console.log(` Context ID: ${contextResult.contextId}`);
|
|
55
|
+
console.log(` Request ID: ${contextResult.requestId}`);
|
|
56
|
+
|
|
57
|
+
// Step 2: Configure sync policy with Archive upload mode
|
|
58
|
+
console.log("\n⚙️ Step 2: Configuring sync policy with Archive upload mode...");
|
|
59
|
+
const syncPolicy = newSyncPolicy();
|
|
60
|
+
syncPolicy.uploadPolicy!.uploadMode = UploadMode.Archive; // Set to Archive mode
|
|
61
|
+
|
|
62
|
+
console.log(`✅ Sync policy configured with uploadMode: ${syncPolicy.uploadPolicy!.uploadMode}`);
|
|
63
|
+
|
|
64
|
+
// Step 3: Create context sync configuration
|
|
65
|
+
console.log("\n🔧 Step 3: Creating context sync configuration...");
|
|
66
|
+
const contextSync = newContextSync(
|
|
67
|
+
contextResult.contextId,
|
|
68
|
+
"/tmp/archive-mode-test",
|
|
69
|
+
syncPolicy
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
console.log(`✅ Context sync created:`);
|
|
73
|
+
console.log(` Context ID: ${contextSync.contextId}`);
|
|
74
|
+
console.log(` Path: ${contextSync.path}`);
|
|
75
|
+
console.log(` Upload Mode: ${contextSync.policy?.uploadPolicy?.uploadMode}`);
|
|
76
|
+
|
|
77
|
+
// Step 4: Create session with Archive mode context sync
|
|
78
|
+
console.log("\n🏗️ Step 4: Creating session with Archive mode context sync...");
|
|
79
|
+
const sessionParams: CreateSessionParams = {
|
|
80
|
+
labels: {
|
|
81
|
+
example: `archive-mode-${uniqueId}`,
|
|
82
|
+
type: "archive-upload-demo",
|
|
83
|
+
uploadMode: UploadMode.Archive
|
|
84
|
+
},
|
|
85
|
+
contextSync: [contextSync]
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const sessionResult = await agentBay.create(sessionParams);
|
|
89
|
+
if (!sessionResult.success) {
|
|
90
|
+
throw new Error(`Session creation failed: ${sessionResult.errorMessage}`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
session = sessionResult.session!;
|
|
94
|
+
console.log(`✅ Session created successfully!`);
|
|
95
|
+
console.log(` Session ID: ${session!.sessionId}`);
|
|
96
|
+
console.log(` Request ID: ${sessionResult.requestId}`);
|
|
97
|
+
|
|
98
|
+
// Get session info to verify setup
|
|
99
|
+
const sessionInfo = await agentBay.getSession(session!.sessionId);
|
|
100
|
+
if (sessionInfo.success && sessionInfo.data) {
|
|
101
|
+
console.log(` App Instance ID: ${sessionInfo.data.appInstanceId}`);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Step 5: Create and write test files
|
|
105
|
+
console.log("\n📝 Step 5: Creating test files in Archive mode context...");
|
|
106
|
+
const fileSystem = new FileSystem(session!);
|
|
107
|
+
|
|
108
|
+
// Generate 5KB test content
|
|
109
|
+
const contentSize = 5 * 1024; // 5KB
|
|
110
|
+
const baseContent = "Archive mode test successful! This is a test file created in the session path. ";
|
|
111
|
+
const repeatedContent = baseContent.repeat(Math.ceil(contentSize / baseContent.length));
|
|
112
|
+
const fileContent = repeatedContent.substring(0, contentSize);
|
|
113
|
+
|
|
114
|
+
const filePath = "/tmp/archive-mode-test/test-file-5kb.txt";
|
|
115
|
+
|
|
116
|
+
console.log(`📄 Creating file: ${filePath}`);
|
|
117
|
+
console.log(`📊 File content size: ${fileContent.length} bytes`);
|
|
118
|
+
|
|
119
|
+
const writeResult = await fileSystem.writeFile(filePath, fileContent, "overwrite");
|
|
120
|
+
|
|
121
|
+
if (!writeResult.success) {
|
|
122
|
+
throw new Error(`File write failed: ${writeResult.errorMessage}`);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
console.log(`✅ File write successful!`);
|
|
126
|
+
console.log(` Request ID: ${writeResult.requestId}`);
|
|
127
|
+
|
|
128
|
+
// Step 6: Test context sync and info functionality
|
|
129
|
+
console.log("\n📊 Step 6: Testing context sync and info functionality...");
|
|
130
|
+
|
|
131
|
+
// Call context sync before getting info
|
|
132
|
+
console.log("🔄 Calling context sync before getting info...");
|
|
133
|
+
const syncResult = await session!.context.sync();
|
|
134
|
+
|
|
135
|
+
if (!syncResult.success) {
|
|
136
|
+
throw new Error(`Context sync failed: ${syncResult.errorMessage}`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
console.log(`✅ Context sync successful!`);
|
|
140
|
+
console.log(` Sync Request ID: ${syncResult.requestId}`);
|
|
141
|
+
|
|
142
|
+
// Now call context info after sync
|
|
143
|
+
console.log("📋 Calling context info after sync...");
|
|
144
|
+
const infoResult = await session!.context.info();
|
|
145
|
+
|
|
146
|
+
if (!infoResult.success) {
|
|
147
|
+
throw new Error(`Context info failed: ${infoResult.errorMessage}`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
console.log(`✅ Context info retrieved successfully!`);
|
|
151
|
+
console.log(` Info Request ID: ${infoResult.requestId}`);
|
|
152
|
+
console.log(` Context status data count: ${infoResult.contextStatusData.length}`);
|
|
153
|
+
|
|
154
|
+
// Display context status details
|
|
155
|
+
if (infoResult.contextStatusData.length > 0) {
|
|
156
|
+
console.log("\n📋 Context status details:");
|
|
157
|
+
infoResult.contextStatusData.forEach((status:any, index:any) => {
|
|
158
|
+
console.log(` [${index}] Context ID: ${status.contextId}`);
|
|
159
|
+
console.log(` Path: ${status.path}`);
|
|
160
|
+
console.log(` Status: ${status.status}`);
|
|
161
|
+
console.log(` Task Type: ${status.taskType}`);
|
|
162
|
+
if (status.errorMessage) {
|
|
163
|
+
console.log(` Error: ${status.errorMessage}`);
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Step 7: List files in context sync directory
|
|
169
|
+
console.log("\n🔍 Step 7: Listing files in context sync directory...");
|
|
170
|
+
|
|
171
|
+
// Use the sync directory path
|
|
172
|
+
const syncDirPath = "/tmp/archive-mode-test";
|
|
173
|
+
|
|
174
|
+
const listResult = await agentBay.context.listFiles(contextResult.contextId, syncDirPath, 1, 10);
|
|
175
|
+
|
|
176
|
+
if (!listResult.success) {
|
|
177
|
+
throw new Error(`List files failed: ${listResult.errorMessage || 'Unknown error'}`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
console.log(`✅ List files successful!`);
|
|
181
|
+
console.log(` Request ID: ${listResult.requestId}`);
|
|
182
|
+
console.log(` Total files found: ${listResult.entries.length}`);
|
|
183
|
+
|
|
184
|
+
if (listResult.entries.length > 0) {
|
|
185
|
+
console.log("\n📋 Files in context sync directory:");
|
|
186
|
+
listResult.entries.forEach((entry:any, index:any) => {
|
|
187
|
+
console.log(` [${index}] FilePath: ${entry.filePath}`);
|
|
188
|
+
console.log(` FileType: ${entry.fileType}`);
|
|
189
|
+
console.log(` FileName: ${entry.fileName}`);
|
|
190
|
+
console.log(` Size: ${entry.size} bytes`);
|
|
191
|
+
});
|
|
192
|
+
} else {
|
|
193
|
+
console.log(" No files found in context sync directory");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
console.log("\n🎉 Archive upload mode example completed successfully!");
|
|
197
|
+
console.log("✅ All operations completed without errors.");
|
|
198
|
+
|
|
199
|
+
} catch (error) {
|
|
200
|
+
console.error("\n❌ Error occurred during example execution:");
|
|
201
|
+
console.error(error);
|
|
202
|
+
} finally {
|
|
203
|
+
// Step 8: Cleanup
|
|
204
|
+
if (session) {
|
|
205
|
+
console.log("\n🧹 Step 8: Cleaning up session...");
|
|
206
|
+
try {
|
|
207
|
+
const deleteResult = await agentBay.delete(session, true);
|
|
208
|
+
console.log(`✅ Session deleted successfully!`);
|
|
209
|
+
console.log(` Success: ${deleteResult.success}`);
|
|
210
|
+
console.log(` Request ID: ${deleteResult.requestId}`);
|
|
211
|
+
} catch (deleteError) {
|
|
212
|
+
console.error(`❌ Failed to delete session: ${deleteError}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Main execution
|
|
219
|
+
async function main(): Promise<void> {
|
|
220
|
+
try {
|
|
221
|
+
await archiveUploadModeExample();
|
|
222
|
+
} catch (error) {
|
|
223
|
+
console.error("❌ Example execution failed:", error);
|
|
224
|
+
process.exit(1);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// Run the example if this file is executed directly
|
|
229
|
+
if (require.main === module) {
|
|
230
|
+
main().catch((error) => {
|
|
231
|
+
console.error("❌ Unhandled error:", error);
|
|
232
|
+
process.exit(1);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export { archiveUploadModeExample };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Command Execution Example
|
|
2
|
+
|
|
3
|
+
This example demonstrates how to use the command execution features of the AgentBay SDK for TypeScript.
|
|
4
|
+
|
|
5
|
+
## Features Demonstrated
|
|
6
|
+
|
|
7
|
+
- Executing shell commands
|
|
8
|
+
- Setting custom timeouts for commands
|
|
9
|
+
- Running Python code
|
|
10
|
+
- Running JavaScript code
|
|
11
|
+
- Executing multi-line command sequences
|
|
12
|
+
|
|
13
|
+
## Running the Example
|
|
14
|
+
|
|
15
|
+
1. Make sure you have installed the AgentBay SDK:
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install wuying-agentbay-sdk
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
2. Set your API key as an environment variable (recommended):
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
export AGENTBAY_API_KEY=your_api_key_here
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
3. Compile and run the example:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# Compile TypeScript
|
|
31
|
+
cd command-example
|
|
32
|
+
npx ts-node command-example.ts
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Code Explanation
|
|
36
|
+
|
|
37
|
+
The example demonstrates different ways to execute commands:
|
|
38
|
+
|
|
39
|
+
1. Basic shell command execution
|
|
40
|
+
2. Command execution with custom timeout
|
|
41
|
+
3. Running Python code
|
|
42
|
+
4. Running JavaScript code with custom timeout
|
|
43
|
+
5. Executing a multi-line shell command sequence
|
|
44
|
+
|
|
45
|
+
The code also demonstrates proper error handling and resource cleanup using try-finally.
|
|
46
|
+
|
|
47
|
+
For more details on command execution, see the [Command API Reference](../../../../api/common-features/basics/command.md) and [Command Execution Tutorial](../../../../../../docs/guides/common-features/basics/command-execution.md).
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { AgentBay, log, logError } from 'wuying-agentbay-sdk';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Helper function to truncate long output text
|
|
5
|
+
*/
|
|
6
|
+
function truncateOutput(output: string, maxLines: number): string {
|
|
7
|
+
const lines = output.split('\n');
|
|
8
|
+
if (lines.length <= maxLines) {
|
|
9
|
+
return output;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const truncated = lines.slice(0, maxLines);
|
|
13
|
+
return truncated.join('\n') + '\n... (output truncated)';
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function main() {
|
|
17
|
+
// Get API key from environment variable or use a placeholder value
|
|
18
|
+
const apiKey = process.env.AGENTBAY_API_KEY || 'akm-xxx'; // Replace with your actual API key
|
|
19
|
+
if (!process.env.AGENTBAY_API_KEY) {
|
|
20
|
+
log('Warning: Using placeholder API key. Set AGENTBAY_API_KEY environment variable for production use.');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Initialize the AgentBay client
|
|
24
|
+
const agentBay = new AgentBay({ apiKey });
|
|
25
|
+
|
|
26
|
+
// Create session parameters with imageId set to code_latest to support code execution
|
|
27
|
+
const params = {
|
|
28
|
+
imageId: 'code_latest'
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Create a new session
|
|
32
|
+
log('\nCreating a new session with code_latest image...');
|
|
33
|
+
const createResponse = await agentBay.create(params);
|
|
34
|
+
const session = createResponse.session;
|
|
35
|
+
log(`\nSession created with ID: ${session.sessionId}`);
|
|
36
|
+
log(`Create Session RequestId: ${createResponse.requestId}`);
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
// 1. Execute simple shell command
|
|
40
|
+
log('\n1. Executing simple shell command (echo)...');
|
|
41
|
+
try {
|
|
42
|
+
const echoCommand = "echo 'Hello from AgentBay SDK!'";
|
|
43
|
+
const echoResponse = await session.command.executeCommand(echoCommand);
|
|
44
|
+
log(`Echo command output:\n${echoResponse.output}`);
|
|
45
|
+
log(`Execute Command RequestId: ${echoResponse.requestId}`);
|
|
46
|
+
} catch (error) {
|
|
47
|
+
log(`Error executing echo command: ${error}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 2. Execute command with longer timeout
|
|
51
|
+
log('\n2. Executing command with custom timeout...');
|
|
52
|
+
try {
|
|
53
|
+
const lsCommand = "ls -la /etc";
|
|
54
|
+
const timeoutMs = 5000; // 5 seconds timeout
|
|
55
|
+
const lsResponse = await session.command.executeCommand(lsCommand, timeoutMs);
|
|
56
|
+
log(`Directory listing (first few lines):\n${truncateOutput(lsResponse.output, 5)}`);
|
|
57
|
+
log(`Execute Command with Timeout RequestId: ${lsResponse.requestId}`);
|
|
58
|
+
} catch (error) {
|
|
59
|
+
log(`Error executing ls command: ${error}`);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// 3. Execute Python code
|
|
63
|
+
log('\n3. Running Python code...');
|
|
64
|
+
try {
|
|
65
|
+
const pythonCode = `
|
|
66
|
+
import platform
|
|
67
|
+
import sys
|
|
68
|
+
|
|
69
|
+
print(f"Python version: {platform.python_version()}")
|
|
70
|
+
print(f"System info: {platform.system()} {platform.release()}")
|
|
71
|
+
print("Working with numbers in Python:")
|
|
72
|
+
for i in range(1, 6):
|
|
73
|
+
print(f"{i} squared is {i*i}")
|
|
74
|
+
`;
|
|
75
|
+
const pythonResponse = await session.code.runCode(pythonCode, "python");
|
|
76
|
+
log(`Python code output:\n${pythonResponse.result}`);
|
|
77
|
+
log(`Run Python Code RequestId: ${pythonResponse.requestId}`);
|
|
78
|
+
|
|
79
|
+
if (!pythonResponse.result || pythonResponse.result.trim() === '') {
|
|
80
|
+
log('Warning: Python code execution returned empty result');
|
|
81
|
+
if (pythonResponse.errorMessage) {
|
|
82
|
+
log(`Error message: ${pythonResponse.errorMessage}`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
} catch (error) {
|
|
86
|
+
log(`Error running Python code: ${error}`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// 4. Execute JavaScript code with custom timeout
|
|
90
|
+
log('\n4. Running JavaScript code with custom timeout...');
|
|
91
|
+
try {
|
|
92
|
+
const jsCode = `
|
|
93
|
+
console.log("JavaScript execution in AgentBay");
|
|
94
|
+
console.log("Basic operations:");
|
|
95
|
+
|
|
96
|
+
// Simple array operations
|
|
97
|
+
const numbers = [1, 2, 3, 4, 5];
|
|
98
|
+
console.log("Original array:", numbers);
|
|
99
|
+
|
|
100
|
+
const doubled = numbers.map(n => n * 2);
|
|
101
|
+
console.log("Doubled values:", doubled);
|
|
102
|
+
|
|
103
|
+
const sum = numbers.reduce((total, n) => total + n, 0);
|
|
104
|
+
console.log("Sum of array:", sum);
|
|
105
|
+
`;
|
|
106
|
+
const timeoutS = 10; // 10 seconds timeout
|
|
107
|
+
const jsResponse = await session.code.runCode(jsCode, "javascript", timeoutS);
|
|
108
|
+
log(`JavaScript code output:\n${jsResponse.result}`);
|
|
109
|
+
log(`Run JavaScript Code RequestId: ${jsResponse.requestId}`);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
log(`Error running JavaScript code: ${error}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 5. Execute a more complex shell command sequence
|
|
115
|
+
log('\n5. Executing a sequence of shell commands...');
|
|
116
|
+
try {
|
|
117
|
+
const complexCommand = `
|
|
118
|
+
echo "Current working directory:"
|
|
119
|
+
pwd
|
|
120
|
+
echo "\nSystem information:"
|
|
121
|
+
uname -a
|
|
122
|
+
echo "\nMemory usage:"
|
|
123
|
+
free -h 2>/dev/null || vm_stat 2>/dev/null || echo "Memory info not available"
|
|
124
|
+
echo "\nDisk usage:"
|
|
125
|
+
df -h | head -5
|
|
126
|
+
`;
|
|
127
|
+
const complexResponse = await session.command.executeCommand(complexCommand);
|
|
128
|
+
log(`Complex command output:\n${truncateOutput(complexResponse.output, 15)}`);
|
|
129
|
+
log(`Execute Complex Command RequestId: ${complexResponse.requestId}`);
|
|
130
|
+
} catch (error) {
|
|
131
|
+
log(`Error executing complex command: ${error}`);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
log('\nCommand examples completed successfully!');
|
|
135
|
+
|
|
136
|
+
} finally {
|
|
137
|
+
// Clean up by deleting the session when we're done
|
|
138
|
+
log('\nDeleting the session...');
|
|
139
|
+
try {
|
|
140
|
+
const deleteResponse = await agentBay.delete(session);
|
|
141
|
+
log('Session deleted successfully');
|
|
142
|
+
log(`Delete Session RequestId: ${deleteResponse.requestId}`);
|
|
143
|
+
} catch (error) {
|
|
144
|
+
log(`Error deleting session: ${error}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Execute the main function
|
|
150
|
+
main().catch(error => {
|
|
151
|
+
logError('Error in main execution:', error);
|
|
152
|
+
process.exit(1);
|
|
153
|
+
});
|