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,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RecyclePolicy Example - Data Lifecycle Management
|
|
3
|
+
*
|
|
4
|
+
* This example demonstrates how to use RecyclePolicy to control the lifecycle
|
|
5
|
+
* of context data in the cloud.
|
|
6
|
+
*
|
|
7
|
+
* Expected Output:
|
|
8
|
+
*
|
|
9
|
+
* ======================================================================
|
|
10
|
+
* Example 1: Default RecyclePolicy
|
|
11
|
+
* ======================================================================
|
|
12
|
+
* ✅ Context created: SdkCtx-xxxxxxxxxxxxx
|
|
13
|
+
* Lifecycle: Lifecycle_Forever
|
|
14
|
+
* Paths: [""]
|
|
15
|
+
* ✅ Session created: session-xxxxxxxxxxxxx
|
|
16
|
+
* ✅ Data written to /tmp/default_data/test.txt
|
|
17
|
+
* ✅ Session deleted
|
|
18
|
+
* ✅ Context deleted
|
|
19
|
+
*
|
|
20
|
+
* ======================================================================
|
|
21
|
+
* Example 2: RecyclePolicy with 1 Day Lifecycle
|
|
22
|
+
* ======================================================================
|
|
23
|
+
* ✅ Context created: SdkCtx-xxxxxxxxxxxxx
|
|
24
|
+
* Lifecycle: Lifecycle_1Day
|
|
25
|
+
* Paths: [""]
|
|
26
|
+
* ✅ Session created: session-xxxxxxxxxxxxx
|
|
27
|
+
* ✅ Data written to /tmp/oneday_data/test.txt
|
|
28
|
+
* ℹ️ This data will be automatically deleted after 1 day
|
|
29
|
+
* ✅ Session deleted
|
|
30
|
+
* ✅ Context deleted
|
|
31
|
+
*
|
|
32
|
+
* ======================================================================
|
|
33
|
+
* Example 3: RecyclePolicy for Specific Paths
|
|
34
|
+
* ======================================================================
|
|
35
|
+
* ✅ Context created: SdkCtx-xxxxxxxxxxxxx
|
|
36
|
+
* Lifecycle: Lifecycle_3Days
|
|
37
|
+
* Paths: ["/tmp/cache", "/tmp/logs"]
|
|
38
|
+
* ℹ️ Only files in /tmp/cache and /tmp/logs will be deleted after 3 days
|
|
39
|
+
* ✅ Session created: session-xxxxxxxxxxxxx
|
|
40
|
+
* ✅ Session deleted
|
|
41
|
+
* ✅ Context deleted
|
|
42
|
+
*
|
|
43
|
+
* ======================================================================
|
|
44
|
+
* Example 4: Different Lifecycle Options
|
|
45
|
+
* ======================================================================
|
|
46
|
+
* 📋 Available Lifecycle Options:
|
|
47
|
+
* --------------------------------------------------
|
|
48
|
+
* Lifecycle_1Day - 1 day
|
|
49
|
+
* Lifecycle_3Days - 3 days
|
|
50
|
+
* Lifecycle_5Days - 5 days
|
|
51
|
+
* Lifecycle_10Days - 10 days
|
|
52
|
+
* Lifecycle_30Days - 30 days
|
|
53
|
+
* Lifecycle_Forever - Forever (permanent)
|
|
54
|
+
* ✅ All lifecycle options validated successfully
|
|
55
|
+
*/
|
|
56
|
+
|
|
57
|
+
import { AgentBay } from "wuying-agentbay-sdk";
|
|
58
|
+
import { CreateSessionParams } from 'wuying-agentbay-sdk';
|
|
59
|
+
import {
|
|
60
|
+
ContextSync,
|
|
61
|
+
Lifecycle,
|
|
62
|
+
newRecyclePolicy,
|
|
63
|
+
newSyncPolicy,
|
|
64
|
+
RecyclePolicy,
|
|
65
|
+
SyncPolicyImpl,
|
|
66
|
+
} from 'wuying-agentbay-sdk';
|
|
67
|
+
|
|
68
|
+
async function example1DefaultRecyclePolicy(): Promise<void> {
|
|
69
|
+
console.log("\n" + "=".repeat(70));
|
|
70
|
+
console.log("Example 1: Default RecyclePolicy");
|
|
71
|
+
console.log("=".repeat(70));
|
|
72
|
+
|
|
73
|
+
const agentBay = new AgentBay();
|
|
74
|
+
|
|
75
|
+
// Create a context
|
|
76
|
+
const contextResult = await agentBay.context.get("default-recycle-demo", true);
|
|
77
|
+
if (!contextResult.success || !contextResult.context) {
|
|
78
|
+
console.log(`❌ Failed to create context: ${contextResult.errorMessage}`);
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const context = contextResult.context;
|
|
83
|
+
console.log(`✅ Context created: ${context.id}`);
|
|
84
|
+
|
|
85
|
+
// Use default SyncPolicy (includes default RecyclePolicy with Lifecycle_Forever)
|
|
86
|
+
const syncPolicy = newSyncPolicy();
|
|
87
|
+
console.log(` Lifecycle: ${syncPolicy.recyclePolicy?.lifecycle}`);
|
|
88
|
+
console.log(` Paths: ${JSON.stringify(syncPolicy.recyclePolicy?.paths)}`);
|
|
89
|
+
|
|
90
|
+
const contextSync = new ContextSync(context.id, "/tmp/default_data", syncPolicy);
|
|
91
|
+
|
|
92
|
+
// Create session with context sync
|
|
93
|
+
const params: CreateSessionParams = {};
|
|
94
|
+
params.contextSync = [contextSync];
|
|
95
|
+
const sessionResult = await agentBay.create(params);
|
|
96
|
+
|
|
97
|
+
if (!sessionResult.success || !sessionResult.session) {
|
|
98
|
+
console.log(`❌ Failed to create session: ${sessionResult.errorMessage}`);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const session = sessionResult.session;
|
|
103
|
+
console.log(`✅ Session created: ${session.sessionId}`);
|
|
104
|
+
|
|
105
|
+
// Write some data
|
|
106
|
+
await session.command.executeCommand(
|
|
107
|
+
"echo 'Default policy - data kept forever' > /tmp/default_data/test.txt"
|
|
108
|
+
);
|
|
109
|
+
console.log("✅ Data written to /tmp/default_data/test.txt");
|
|
110
|
+
|
|
111
|
+
// Clean up
|
|
112
|
+
await agentBay.delete(session);
|
|
113
|
+
console.log("✅ Session deleted");
|
|
114
|
+
|
|
115
|
+
await agentBay.context.delete(context);
|
|
116
|
+
console.log("✅ Context deleted");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function example2OneDayLifecycle(): Promise<void> {
|
|
120
|
+
console.log("\n" + "=".repeat(70));
|
|
121
|
+
console.log("Example 2: RecyclePolicy with 1 Day Lifecycle");
|
|
122
|
+
console.log("=".repeat(70));
|
|
123
|
+
|
|
124
|
+
const agentBay = new AgentBay();
|
|
125
|
+
|
|
126
|
+
// Create a context
|
|
127
|
+
const contextResult = await agentBay.context.get("one-day-recycle-demo", true);
|
|
128
|
+
if (!contextResult.success || !contextResult.context) {
|
|
129
|
+
console.log(`❌ Failed to create context: ${contextResult.errorMessage}`);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const context = contextResult.context;
|
|
134
|
+
console.log(`✅ Context created: ${context.id}`);
|
|
135
|
+
|
|
136
|
+
// Create custom RecyclePolicy with 1 day lifecycle
|
|
137
|
+
const recyclePolicy: RecyclePolicy = {
|
|
138
|
+
lifecycle: Lifecycle.Lifecycle_1Day,
|
|
139
|
+
paths: [""], // Apply to all paths
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
// Create SyncPolicy with custom RecyclePolicy
|
|
143
|
+
const syncPolicy = new SyncPolicyImpl({
|
|
144
|
+
recyclePolicy: recyclePolicy,
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
console.log(` Lifecycle: ${syncPolicy.recyclePolicy?.lifecycle}`);
|
|
148
|
+
console.log(` Paths: ${JSON.stringify(syncPolicy.recyclePolicy?.paths)}`);
|
|
149
|
+
|
|
150
|
+
const contextSync = new ContextSync(context.id, "/tmp/oneday_data", syncPolicy);
|
|
151
|
+
|
|
152
|
+
// Create session with context sync
|
|
153
|
+
const params: CreateSessionParams = {};
|
|
154
|
+
params.labels = { example: "recycle_policy", lifecycle: "1day" };
|
|
155
|
+
params.contextSync = [contextSync];
|
|
156
|
+
const sessionResult = await agentBay.create(params);
|
|
157
|
+
|
|
158
|
+
if (!sessionResult.success || !sessionResult.session) {
|
|
159
|
+
console.log(`❌ Failed to create session: ${sessionResult.errorMessage}`);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const session = sessionResult.session;
|
|
164
|
+
console.log(`✅ Session created: ${session.sessionId}`);
|
|
165
|
+
|
|
166
|
+
// Write some data
|
|
167
|
+
await session.command.executeCommand("mkdir -p /tmp/oneday_data");
|
|
168
|
+
await session.command.executeCommand(
|
|
169
|
+
"echo 'This data will be deleted after 1 day' > /tmp/oneday_data/test.txt"
|
|
170
|
+
);
|
|
171
|
+
console.log("✅ Data written to /tmp/oneday_data/test.txt");
|
|
172
|
+
console.log(" ℹ️ This data will be automatically deleted after 1 day");
|
|
173
|
+
|
|
174
|
+
// Clean up
|
|
175
|
+
await agentBay.delete(session);
|
|
176
|
+
console.log("✅ Session deleted");
|
|
177
|
+
|
|
178
|
+
await agentBay.context.delete(context);
|
|
179
|
+
console.log("✅ Context deleted");
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function example3SpecificPaths(): Promise<void> {
|
|
183
|
+
console.log("\n" + "=".repeat(70));
|
|
184
|
+
console.log("Example 3: RecyclePolicy for Specific Paths");
|
|
185
|
+
console.log("=".repeat(70));
|
|
186
|
+
|
|
187
|
+
const agentBay = new AgentBay();
|
|
188
|
+
|
|
189
|
+
// Create a context
|
|
190
|
+
const contextResult = await agentBay.context.get("specific-path-demo", true);
|
|
191
|
+
if (!contextResult.success || !contextResult.context) {
|
|
192
|
+
console.log(`❌ Failed to create context: ${contextResult.errorMessage}`);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const context = contextResult.context;
|
|
197
|
+
console.log(`✅ Context created: ${context.id}`);
|
|
198
|
+
|
|
199
|
+
// Create RecyclePolicy for specific paths
|
|
200
|
+
const recyclePolicy: RecyclePolicy = {
|
|
201
|
+
lifecycle: Lifecycle.Lifecycle_3Days,
|
|
202
|
+
paths: ["/tmp/cache", "/tmp/logs"], // Only these paths
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
const syncPolicy = new SyncPolicyImpl({ recyclePolicy: recyclePolicy });
|
|
206
|
+
|
|
207
|
+
console.log(` Lifecycle: ${syncPolicy.recyclePolicy?.lifecycle}`);
|
|
208
|
+
console.log(` Paths: ${JSON.stringify(syncPolicy.recyclePolicy?.paths)}`);
|
|
209
|
+
console.log(
|
|
210
|
+
" ℹ️ Only files in /tmp/cache and /tmp/logs will be deleted after 3 days"
|
|
211
|
+
);
|
|
212
|
+
|
|
213
|
+
const contextSync = new ContextSync(
|
|
214
|
+
context.id,
|
|
215
|
+
"/tmp/multipath_data",
|
|
216
|
+
syncPolicy
|
|
217
|
+
);
|
|
218
|
+
|
|
219
|
+
// Create session
|
|
220
|
+
const params: CreateSessionParams = {};
|
|
221
|
+
params.contextSync = [contextSync];
|
|
222
|
+
const sessionResult = await agentBay.create(params);
|
|
223
|
+
|
|
224
|
+
if (!sessionResult.success || !sessionResult.session) {
|
|
225
|
+
console.log(`❌ Failed to create session: ${sessionResult.errorMessage}`);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const session = sessionResult.session;
|
|
230
|
+
console.log(`✅ Session created: ${session.sessionId}`);
|
|
231
|
+
|
|
232
|
+
// Clean up
|
|
233
|
+
await agentBay.delete(session);
|
|
234
|
+
console.log("✅ Session deleted");
|
|
235
|
+
|
|
236
|
+
await agentBay.context.delete(context);
|
|
237
|
+
console.log("✅ Context deleted");
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function example4DifferentLifecycles(): void {
|
|
241
|
+
console.log("\n" + "=".repeat(70));
|
|
242
|
+
console.log("Example 4: Different Lifecycle Options");
|
|
243
|
+
console.log("=".repeat(70));
|
|
244
|
+
|
|
245
|
+
const lifecycles = [
|
|
246
|
+
{ lifecycle: Lifecycle.Lifecycle_1Day, description: "1 day" },
|
|
247
|
+
{ lifecycle: Lifecycle.Lifecycle_3Days, description: "3 days" },
|
|
248
|
+
{ lifecycle: Lifecycle.Lifecycle_5Days, description: "5 days" },
|
|
249
|
+
{ lifecycle: Lifecycle.Lifecycle_10Days, description: "10 days" },
|
|
250
|
+
{ lifecycle: Lifecycle.Lifecycle_30Days, description: "30 days" },
|
|
251
|
+
{ lifecycle: Lifecycle.Lifecycle_Forever, description: "Forever (permanent)" },
|
|
252
|
+
];
|
|
253
|
+
|
|
254
|
+
console.log("\n📋 Available Lifecycle Options:");
|
|
255
|
+
console.log("-".repeat(50));
|
|
256
|
+
for (const { lifecycle, description} of lifecycles) {
|
|
257
|
+
const recyclePolicy: RecyclePolicy = {
|
|
258
|
+
lifecycle: lifecycle,
|
|
259
|
+
paths: [""],
|
|
260
|
+
};
|
|
261
|
+
console.log(` ${lifecycle.padEnd(25)} - ${description}`);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
console.log("\n✅ All lifecycle options validated successfully");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async function main(): Promise<void> {
|
|
268
|
+
console.log("\n" + "=".repeat(70));
|
|
269
|
+
console.log("RecyclePolicy Examples - Data Lifecycle Management");
|
|
270
|
+
console.log("=".repeat(70));
|
|
271
|
+
console.log("\nThese examples demonstrate how to use RecyclePolicy to control");
|
|
272
|
+
console.log("the lifecycle of context data in the cloud.");
|
|
273
|
+
|
|
274
|
+
try {
|
|
275
|
+
// Run examples
|
|
276
|
+
await example1DefaultRecyclePolicy();
|
|
277
|
+
await example2OneDayLifecycle();
|
|
278
|
+
await example3SpecificPaths();
|
|
279
|
+
example4DifferentLifecycles();
|
|
280
|
+
|
|
281
|
+
console.log("\n" + "=".repeat(70));
|
|
282
|
+
console.log("✅ All RecyclePolicy examples completed successfully!");
|
|
283
|
+
console.log("=".repeat(70));
|
|
284
|
+
} catch (error) {
|
|
285
|
+
console.log(`\n❌ Example failed with error: ${error}`);
|
|
286
|
+
console.error(error);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Only run if this file is executed directly
|
|
291
|
+
if (require.main === module) {
|
|
292
|
+
main();
|
|
293
|
+
}
|
|
294
|
+
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Filesystem Operations Example
|
|
2
|
+
|
|
3
|
+
This example demonstrates how to use the AgentBay SDK to perform various filesystem operations within a session.
|
|
4
|
+
|
|
5
|
+
## Features Demonstrated
|
|
6
|
+
|
|
7
|
+
- Directory Operations:
|
|
8
|
+
- Creating directories
|
|
9
|
+
- Listing directory contents
|
|
10
|
+
|
|
11
|
+
- File Operations:
|
|
12
|
+
- Writing files
|
|
13
|
+
- Reading files
|
|
14
|
+
- Getting file information
|
|
15
|
+
- Editing file content
|
|
16
|
+
- Moving/renaming files
|
|
17
|
+
- Searching for files
|
|
18
|
+
|
|
19
|
+
- File Transfer Operations:
|
|
20
|
+
- Uploading files from local to remote environment
|
|
21
|
+
- Downloading files from remote to local environment
|
|
22
|
+
- Progress tracking during file transfers
|
|
23
|
+
|
|
24
|
+
## Running the Examples
|
|
25
|
+
|
|
26
|
+
Make sure you have set your AgentBay API key as an environment variable:
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
export AGENTBAY_API_KEY="your-api-key-here"
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Basic Filesystem Operations
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
cd filesystem-example
|
|
36
|
+
npx ts-node filesystem-example.ts
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Directory Monitoring
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cd filesystem-example
|
|
43
|
+
npx ts-node watch-directory-example.ts
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### File Transfer Operations
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
cd filesystem-example
|
|
50
|
+
npx ts-node filesystem-filetransfer-example.ts
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Note
|
|
54
|
+
|
|
55
|
+
The example uses the `/tmp` directory for all operations to ensure it has the necessary permissions. Some operations might not be supported in all session types or environments. The example includes error handling to handle such cases gracefully.
|
|
56
|
+
|
|
57
|
+
File transfer operations require proper session context configuration for optimal performance. The examples demonstrate best practices for handling file transfers with progress tracking and error handling.
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { AgentBay, logError, log } from 'wuying-agentbay-sdk';
|
|
2
|
+
|
|
3
|
+
// Define test path prefix
|
|
4
|
+
const TestPathPrefix = '/tmp';
|
|
5
|
+
|
|
6
|
+
// Define interfaces for file system operations
|
|
7
|
+
interface FileEntry {
|
|
8
|
+
name: string;
|
|
9
|
+
isDirectory: boolean;
|
|
10
|
+
size?: number;
|
|
11
|
+
path?: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function main() {
|
|
15
|
+
// Get API key from environment variable or use default value for testing
|
|
16
|
+
const apiKey = process.env.AGENTBAY_API_KEY || 'akm-xxx'; // Replace with your actual API key
|
|
17
|
+
if (!process.env.AGENTBAY_API_KEY) {
|
|
18
|
+
log('Warning: Using placeholder API key. Set AGENTBAY_API_KEY environment variable for production use.');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Initialize the AgentBay client
|
|
22
|
+
const agentBay = new AgentBay({ apiKey });
|
|
23
|
+
|
|
24
|
+
// Create a new session
|
|
25
|
+
log('\nCreating a new session...');
|
|
26
|
+
const createResponse = await agentBay.create({imageId:'linux_latest'});
|
|
27
|
+
const session = createResponse.session;
|
|
28
|
+
log(`\nSession created with ID: ${session.sessionId}`);
|
|
29
|
+
log(`Create Session RequestId: ${createResponse.requestId}`);
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
// 1. Create a directory
|
|
33
|
+
const testDirPath = `${TestPathPrefix}/test_directory`;
|
|
34
|
+
log(`\nCreating directory: ${testDirPath}`);
|
|
35
|
+
try {
|
|
36
|
+
const createDirResponse = await session.fileSystem.createDirectory(testDirPath);
|
|
37
|
+
log(`Directory created: ${createDirResponse.success}`);
|
|
38
|
+
log(`Create Directory RequestId: ${createDirResponse.requestId}`);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
log(`Error creating directory: ${error}`);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// 2. Write a file
|
|
44
|
+
const testFilePath = `${TestPathPrefix}/test_directory/sample.txt`;
|
|
45
|
+
const testContent = "This is a sample file content.\nThis is the second line.\nThis is the third line.";
|
|
46
|
+
log(`\nWriting file: ${testFilePath}`);
|
|
47
|
+
try {
|
|
48
|
+
const writeResponse = await session.fileSystem.writeFile(testFilePath, testContent, "overwrite");
|
|
49
|
+
log(`File written successfully: ${writeResponse.success}`);
|
|
50
|
+
log(`Write File RequestId: ${writeResponse.requestId}`);
|
|
51
|
+
} catch (error) {
|
|
52
|
+
log(`Error writing file: ${error}`);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 3. Read the file we just created
|
|
56
|
+
log(`\nReading file: ${testFilePath}`);
|
|
57
|
+
try {
|
|
58
|
+
const readResponse = await session.fileSystem.readFile(testFilePath);
|
|
59
|
+
log(`File content:\n${readResponse.content}`);
|
|
60
|
+
log(`Read File RequestId: ${readResponse.requestId}`);
|
|
61
|
+
|
|
62
|
+
// Verify content matches what we wrote
|
|
63
|
+
if (readResponse.content === testContent) {
|
|
64
|
+
log('Content verification successful!');
|
|
65
|
+
} else {
|
|
66
|
+
log('Content verification failed!');
|
|
67
|
+
}
|
|
68
|
+
} catch (error) {
|
|
69
|
+
log(`Error reading file: ${error}`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 4. Get file info
|
|
73
|
+
log(`\nGetting file info for: ${testFilePath}`);
|
|
74
|
+
try {
|
|
75
|
+
const fileInfoResponse = await session.fileSystem.getFileInfo(testFilePath);
|
|
76
|
+
const fileInfo = fileInfoResponse.fileInfo;
|
|
77
|
+
log(`File info: Name=${fileInfo.name}, Path=${fileInfo.path}, Size=${fileInfo.size}, IsDirectory=${fileInfo.isDirectory}`);
|
|
78
|
+
log(`Get File Info RequestId: ${fileInfoResponse.requestId}`);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
log(`Error getting file info: ${error}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 5. List directory
|
|
84
|
+
log(`\nListing directory: ${testDirPath}`);
|
|
85
|
+
try {
|
|
86
|
+
const listResponse = await session.fileSystem.listDirectory(testDirPath);
|
|
87
|
+
log('Directory entries:');
|
|
88
|
+
listResponse.entries.forEach((entry: FileEntry) => {
|
|
89
|
+
log(`${entry.isDirectory ? '[DIR]' : '[FILE]'} ${entry.name}`);
|
|
90
|
+
});
|
|
91
|
+
log(`List Directory RequestId: ${listResponse.requestId}`);
|
|
92
|
+
} catch (error) {
|
|
93
|
+
log(`Error listing directory: ${error}`);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 6. Edit file
|
|
97
|
+
log(`\nEditing file: ${testFilePath}`);
|
|
98
|
+
try {
|
|
99
|
+
const edits = [
|
|
100
|
+
{
|
|
101
|
+
oldText: "second line",
|
|
102
|
+
newText: "MODIFIED second line"
|
|
103
|
+
}
|
|
104
|
+
];
|
|
105
|
+
const editResponse = await session.fileSystem.editFile(testFilePath, edits, false);
|
|
106
|
+
log(`File edited successfully: ${editResponse.success}`);
|
|
107
|
+
log(`Edit File RequestId: ${editResponse.requestId}`);
|
|
108
|
+
|
|
109
|
+
// Read the file again to verify the edit
|
|
110
|
+
const readAgainResponse = await session.fileSystem.readFile(testFilePath);
|
|
111
|
+
log(`Edited file content:\n${readAgainResponse.content}`);
|
|
112
|
+
log(`Read File Again RequestId: ${readAgainResponse.requestId}`);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
log(`Error editing file: ${error}`);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// 7. Search files
|
|
118
|
+
log(`\nSearching for files in ${TestPathPrefix} containing 'sample'`);
|
|
119
|
+
try {
|
|
120
|
+
const searchResponse = await session.fileSystem.searchFiles(TestPathPrefix, "*sample*", undefined);
|
|
121
|
+
log(`Search results: ${searchResponse.matches.length} files found`);
|
|
122
|
+
searchResponse.matches.forEach((path: string) => {
|
|
123
|
+
log(`- ${path}`);
|
|
124
|
+
});
|
|
125
|
+
log(`Search Files RequestId: ${searchResponse.requestId}`);
|
|
126
|
+
} catch (error) {
|
|
127
|
+
log(`Error searching files: ${error}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// 8. Move/Rename file
|
|
131
|
+
const newFilePath = `${TestPathPrefix}/test_directory/renamed.txt`;
|
|
132
|
+
log(`\nMoving file from ${testFilePath} to ${newFilePath}`);
|
|
133
|
+
try {
|
|
134
|
+
const moveResponse = await session.fileSystem.moveFile(testFilePath, newFilePath);
|
|
135
|
+
log(`File moved successfully: ${moveResponse.success}`);
|
|
136
|
+
log(`Move File RequestId: ${moveResponse.requestId}`);
|
|
137
|
+
|
|
138
|
+
// List directory again to verify the move
|
|
139
|
+
const listAgainResponse = await session.fileSystem.listDirectory(testDirPath);
|
|
140
|
+
log('Directory entries after move:');
|
|
141
|
+
listAgainResponse.entries.forEach((entry: FileEntry) => {
|
|
142
|
+
log(`${entry.isDirectory ? '[DIR]' : '[FILE]'} ${entry.name}`);
|
|
143
|
+
});
|
|
144
|
+
log(`List Directory Again RequestId: ${listAgainResponse.requestId}`);
|
|
145
|
+
} catch (error) {
|
|
146
|
+
log(`Error moving file: ${error}`);
|
|
147
|
+
}
|
|
148
|
+
} finally {
|
|
149
|
+
// Clean up by deleting the session when we're done
|
|
150
|
+
log('\nDeleting the session...');
|
|
151
|
+
try {
|
|
152
|
+
const deleteResponse = await agentBay.delete(session);
|
|
153
|
+
log('Session deleted successfully');
|
|
154
|
+
log(`Delete Session RequestId: ${deleteResponse.requestId}`);
|
|
155
|
+
} catch (error) {
|
|
156
|
+
log(`Error deleting session: ${error}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
main().catch(error => {
|
|
162
|
+
logError('Error in main execution:', error);
|
|
163
|
+
process.exit(1);
|
|
164
|
+
});
|
package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { AgentBay } from 'wuying-agentbay-sdk';
|
|
2
|
+
import { logError, log } from 'wuying-agentbay-sdk';
|
|
3
|
+
import * as fs from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
5
|
+
import * as os from 'os';
|
|
6
|
+
|
|
7
|
+
async function main() {
|
|
8
|
+
// Get API key from environment variable or use default value for testing
|
|
9
|
+
const apiKey = process.env.AGENTBAY_API_KEY || 'akm-xxx'; // Replace with your actual API key
|
|
10
|
+
if (!process.env.AGENTBAY_API_KEY) {
|
|
11
|
+
log('Warning: Using placeholder API key. Set AGENTBAY_API_KEY environment variable for production use.');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Initialize the AgentBay client
|
|
15
|
+
const agentBay = new AgentBay({ apiKey });
|
|
16
|
+
|
|
17
|
+
// Create a temporary directory for our test files
|
|
18
|
+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentbay-filetransfer-'));
|
|
19
|
+
log(`Created temporary directory: ${tempDir}`);
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
// Create a test file to upload
|
|
23
|
+
const localUploadPath = path.join(tempDir, 'upload-test.txt');
|
|
24
|
+
const testContent = "This is a test file for AgentBay FileTransfer functionality.\n".repeat(10);
|
|
25
|
+
fs.writeFileSync(localUploadPath, testContent);
|
|
26
|
+
log(`Created test file for upload: ${localUploadPath}`);
|
|
27
|
+
|
|
28
|
+
// Create a session with context sync for file transfer
|
|
29
|
+
log('\nCreating a new session with file transfer context...');
|
|
30
|
+
const createResponse = await agentBay.create({
|
|
31
|
+
imageId: 'code_latest'
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
if (!createResponse.success || !createResponse.session) {
|
|
35
|
+
log(`Failed to create session: ${createResponse.errorMessage}`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const session = createResponse.session;
|
|
40
|
+
log(`\nSession created with ID: ${session.sessionId}`);
|
|
41
|
+
log(`Create Session RequestId: ${createResponse.requestId}`);
|
|
42
|
+
log(`Session fileTransferContextId: ${session.fileTransferContextId}`);
|
|
43
|
+
|
|
44
|
+
try {
|
|
45
|
+
// 1. Upload a file
|
|
46
|
+
const remotePath = '/tmp/file_transfer_test/uploaded-file.txt';
|
|
47
|
+
log(`\nUploading file from ${localUploadPath} to ${remotePath}`);
|
|
48
|
+
|
|
49
|
+
// Create the remote directory first
|
|
50
|
+
const dirPath = path.dirname(remotePath);
|
|
51
|
+
const createDirResult = await session.fileSystem.createDirectory(dirPath);
|
|
52
|
+
if (!createDirResult.success) {
|
|
53
|
+
log(`Warning: Failed to create directory ${dirPath}: ${createDirResult.errorMessage}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Upload the file with progress callback
|
|
57
|
+
const uploadResult = await session.fileSystem.uploadFile(
|
|
58
|
+
localUploadPath,
|
|
59
|
+
remotePath,
|
|
60
|
+
{
|
|
61
|
+
progressCb: (bytesTransferred: number) => {
|
|
62
|
+
log(`Upload progress: ${bytesTransferred} bytes transferred`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
if (uploadResult.success) {
|
|
68
|
+
log(`Upload successful!`);
|
|
69
|
+
log(`Bytes sent: ${uploadResult.bytesSent}`);
|
|
70
|
+
log(`Request ID (upload URL): ${uploadResult.requestIdUploadUrl}`);
|
|
71
|
+
log(`Request ID (sync): ${uploadResult.requestIdSync}`);
|
|
72
|
+
|
|
73
|
+
// Verify the file exists in remote location
|
|
74
|
+
const listResult = await session.fileSystem.listDirectory(dirPath);
|
|
75
|
+
if (listResult.success) {
|
|
76
|
+
const fileFound = listResult.entries.some((entry: any) => entry.name === 'uploaded-file.txt');
|
|
77
|
+
if (fileFound) {
|
|
78
|
+
log('File verified in remote directory');
|
|
79
|
+
} else {
|
|
80
|
+
log('Warning: File not found in remote directory');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
} else {
|
|
84
|
+
log(`Upload failed: ${uploadResult.error}`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 2. Create a file in the remote location for download
|
|
88
|
+
const remoteDownloadPath = '/tmp/file_transfer_test/download-test.txt';
|
|
89
|
+
const downloadContent = "This is a test file for AgentBay FileTransfer download functionality.\n".repeat(15);
|
|
90
|
+
|
|
91
|
+
log(`\nCreating remote file for download: ${remoteDownloadPath}`);
|
|
92
|
+
const writeResult = await session.fileSystem.writeFile(remoteDownloadPath, downloadContent);
|
|
93
|
+
if (writeResult.success) {
|
|
94
|
+
log('Remote file created successfully');
|
|
95
|
+
} else {
|
|
96
|
+
log(`Failed to create remote file: ${writeResult.errorMessage}`);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 3. Download the file
|
|
100
|
+
const localDownloadPath = path.join(tempDir, 'downloaded-file.txt');
|
|
101
|
+
log(`\nDownloading file from ${remoteDownloadPath} to ${localDownloadPath}`);
|
|
102
|
+
|
|
103
|
+
const downloadResult = await session.fileSystem.downloadFile(
|
|
104
|
+
remoteDownloadPath,
|
|
105
|
+
localDownloadPath,
|
|
106
|
+
{
|
|
107
|
+
progressCb: (bytesReceived: number) => {
|
|
108
|
+
log(`Download progress: ${bytesReceived} bytes received`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
if (downloadResult.success) {
|
|
114
|
+
log(`Download successful!`);
|
|
115
|
+
log(`Bytes received: ${downloadResult.bytesReceived}`);
|
|
116
|
+
log(`Request ID (download URL): ${downloadResult.requestIdDownloadUrl}`);
|
|
117
|
+
log(`Request ID (sync): ${downloadResult.requestIdSync}`);
|
|
118
|
+
|
|
119
|
+
// Verify downloaded file content
|
|
120
|
+
const downloadedContent = fs.readFileSync(localDownloadPath, 'utf-8');
|
|
121
|
+
if (downloadedContent === downloadContent) {
|
|
122
|
+
log('Downloaded file content verified successfully');
|
|
123
|
+
} else {
|
|
124
|
+
log('Warning: Downloaded file content does not match');
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
log(`Download failed: ${downloadResult.error}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
} finally {
|
|
131
|
+
// Clean up by deleting the session when we're done
|
|
132
|
+
log('\nDeleting the session...');
|
|
133
|
+
try {
|
|
134
|
+
const deleteResponse = await agentBay.delete(session);
|
|
135
|
+
log('Session deleted successfully');
|
|
136
|
+
log(`Delete Session RequestId: ${deleteResponse.requestId}`);
|
|
137
|
+
} catch (error) {
|
|
138
|
+
log(`Error deleting session: ${error}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} finally {
|
|
142
|
+
// Clean up temporary files
|
|
143
|
+
if (fs.existsSync(tempDir)) {
|
|
144
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
145
|
+
log(`Cleaned up temporary directory: ${tempDir}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
main().catch(error => {
|
|
151
|
+
logError('Error in main execution:', error);
|
|
152
|
+
process.exit(1);
|
|
153
|
+
});
|