wuying-agentbay-sdk 0.10.2 โ†’ 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/dist/chunk-E7QC5S76.mjs +3143 -0
  2. package/dist/chunk-E7QC5S76.mjs.map +1 -0
  3. package/dist/chunk-ZUB35HKV.cjs +3134 -0
  4. package/dist/chunk-ZUB35HKV.cjs.map +1 -0
  5. package/dist/index.cjs +3588 -3921
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.mts +2088 -687
  8. package/dist/index.d.ts +2088 -687
  9. package/dist/index.mjs +3556 -3889
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/key-normalizer-AF7APGQZ.cjs +136 -0
  12. package/dist/key-normalizer-AF7APGQZ.cjs.map +1 -0
  13. package/dist/key-normalizer-QDBRLFHF.mjs +145 -0
  14. package/dist/key-normalizer-QDBRLFHF.mjs.map +1 -0
  15. package/dist/model-2G37RFQQ.cjs +188 -0
  16. package/dist/model-2G37RFQQ.cjs.map +1 -0
  17. package/dist/model-ZFTLKEMC.mjs +197 -0
  18. package/docs/api/README.md +26 -0
  19. package/docs/api/browser-use/browser.md +177 -0
  20. package/docs/api/browser-use/extension.md +284 -0
  21. package/docs/api/codespace/code.md +77 -0
  22. package/docs/api/common-features/advanced/agent.md +84 -0
  23. package/docs/api/common-features/advanced/oss.md +221 -0
  24. package/docs/api/common-features/basics/agentbay.md +181 -0
  25. package/docs/api/common-features/basics/command.md +83 -0
  26. package/docs/api/common-features/basics/context-manager.md +130 -0
  27. package/docs/api/common-features/basics/context-sync.md +51 -0
  28. package/docs/api/common-features/basics/context.md +348 -0
  29. package/docs/api/common-features/basics/filesystem.md +499 -0
  30. package/docs/api/common-features/basics/logging.md +77 -0
  31. package/docs/api/common-features/basics/session.md +412 -0
  32. package/docs/api/computer-use/computer.md +786 -0
  33. package/docs/api/mobile-use/mobile.md +395 -0
  34. package/docs/examples/README.md +332 -0
  35. package/docs/examples/basic-usage.ts +86 -0
  36. package/docs/examples/browser-use/browser/README.md +356 -0
  37. package/docs/examples/browser-use/browser/basic-usage.ts +136 -0
  38. package/docs/examples/browser-use/browser/browser-command-args.ts +117 -0
  39. package/docs/examples/browser-use/browser/browser-context-cookie-persistence.ts +348 -0
  40. package/docs/examples/browser-use/browser/browser-fingerprint-basic-usage.ts +121 -0
  41. package/docs/examples/browser-use/browser/browser-fingerprint-construct.ts +114 -0
  42. package/docs/examples/browser-use/browser/browser-fingerprint-local-sync.ts +98 -0
  43. package/docs/examples/browser-use/browser/browser-fingerprint-persistence.ts +242 -0
  44. package/docs/examples/browser-use/browser/browser-proxies.ts +149 -0
  45. package/docs/examples/browser-use/browser/browser-type-example.ts +266 -0
  46. package/docs/examples/browser-use/browser/browser-viewport.ts +129 -0
  47. package/docs/examples/browser-use/browser/call_for_user_jd.ts +184 -0
  48. package/docs/examples/browser-use/browser/captcha_tongcheng.ts +151 -0
  49. package/docs/examples/browser-use/browser/run-2048.ts +209 -0
  50. package/docs/examples/browser-use/browser/run-sudoku.ts +150 -0
  51. package/docs/examples/browser-use/browser/screenshot-example.ts +132 -0
  52. package/docs/examples/browser-use/extension-example/README.md +252 -0
  53. package/docs/examples/browser-use/extension-example/extension-example.ts +380 -0
  54. package/docs/examples/codespace/automation/automation-example.ts +322 -0
  55. package/docs/examples/common-features/advanced/agent-module-example/README.md +40 -0
  56. package/docs/examples/common-features/advanced/agent-module-example.ts +66 -0
  57. package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +212 -0
  58. package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +213 -0
  59. package/docs/examples/common-features/advanced/vpc-session-example/README.md +47 -0
  60. package/docs/examples/common-features/advanced/vpc-session-example.ts +106 -0
  61. package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +236 -0
  62. package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +236 -0
  63. package/docs/examples/common-features/basics/command-example/README.md +47 -0
  64. package/docs/examples/common-features/basics/command-example/command-example.ts +153 -0
  65. package/docs/examples/common-features/basics/context-management/README.md +55 -0
  66. package/docs/examples/common-features/basics/context-management/context-management.ts +140 -0
  67. package/docs/examples/common-features/basics/data-persistence/README.md +129 -0
  68. package/docs/examples/common-features/basics/data-persistence/context-sync-demo.md +144 -0
  69. package/docs/examples/common-features/basics/data-persistence/context-sync-demo.ts +275 -0
  70. package/docs/examples/common-features/basics/data-persistence/data-persistence.ts +259 -0
  71. package/docs/examples/common-features/basics/data-persistence/recycle-policy-example.ts +294 -0
  72. package/docs/examples/common-features/basics/filesystem-example/README.md +57 -0
  73. package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +164 -0
  74. package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +153 -0
  75. package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +168 -0
  76. package/docs/examples/common-features/basics/get/README.md +136 -0
  77. package/docs/examples/common-features/basics/get/main.ts +79 -0
  78. package/docs/examples/common-features/basics/list_sessions/README.md +54 -0
  79. package/docs/examples/common-features/basics/list_sessions/main.ts +258 -0
  80. package/docs/examples/common-features/basics/mcp_tool_direct_call/README.md +142 -0
  81. package/docs/examples/common-features/basics/mcp_tool_direct_call/main.ts +135 -0
  82. package/docs/examples/common-features/basics/session-creation/README.md +28 -0
  83. package/docs/examples/common-features/basics/session-creation/session-creation.ts +295 -0
  84. package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
  85. package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
  86. package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
  87. package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
  88. package/package.json +18 -11
  89. package/dist/application-KZWXH46T.mjs +0 -17
  90. package/dist/application-LMA7KSRH.cjs +0 -8
  91. package/dist/application-LMA7KSRH.cjs.map +0 -1
  92. package/dist/chunk-BQNGKBQF.mjs +0 -386
  93. package/dist/chunk-BQNGKBQF.mjs.map +0 -1
  94. package/dist/chunk-IOVGAAJL.cjs +0 -558
  95. package/dist/chunk-IOVGAAJL.cjs.map +0 -1
  96. package/dist/chunk-UF2TC2R4.mjs +0 -567
  97. package/dist/chunk-UF2TC2R4.mjs.map +0 -1
  98. package/dist/chunk-X6MS7Z5L.cjs +0 -377
  99. package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
  100. package/dist/window-DH37ZDD5.mjs +0 -17
  101. package/dist/window-DH37ZDD5.mjs.map +0 -1
  102. package/dist/window-U7N3H735.cjs +0 -8
  103. package/dist/window-U7N3H735.cjs.map +0 -1
  104. /package/dist/{application-KZWXH46T.mjs.map โ†’ model-ZFTLKEMC.mjs.map} +0 -0
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Watch Directory Example
3
+ *
4
+ * This example demonstrates how to use the watch_directory functionality
5
+ * to monitor file changes in a directory.
6
+ */
7
+
8
+ import { AgentBay, CreateSessionParams } from "wuying-agentbay-sdk";
9
+ import { FileChangeEvent } from "wuying-agentbay-sdk";
10
+
11
+ async function main(): Promise<void> {
12
+ // Get API key from environment variable
13
+ const apiKey = process.env.AGENTBAY_API_KEY;
14
+ if (!apiKey) {
15
+ console.log("โŒ Please set the AGENTBAY_API_KEY environment variable");
16
+ return;
17
+ }
18
+
19
+ console.log("๐Ÿš€ Watch Directory Example");
20
+ console.log("=".repeat(50));
21
+
22
+ try {
23
+ // Initialize AgentBay client
24
+ const agentbay = new AgentBay({ apiKey });
25
+ console.log("โœ… AgentBay client initialized");
26
+
27
+ // Create session with code_latest ImageId
28
+ const sessionParams: CreateSessionParams = { imageId: "code_latest" };
29
+ const sessionResult = await agentbay.create(sessionParams);
30
+
31
+ if (!sessionResult.success) {
32
+ console.log(`โŒ Failed to create session: ${sessionResult.errorMessage}`);
33
+ return;
34
+ }
35
+
36
+ const session = sessionResult.session;
37
+ console.log(`โœ… Session created: ${session.getSessionId()}`);
38
+
39
+ try {
40
+ // Create a test directory to monitor
41
+ const testDir = "/tmp/watch_example";
42
+ console.log(`\n๐Ÿ“ Creating test directory: ${testDir}`);
43
+
44
+ const createResult = await session.fileSystem.createDirectory(testDir);
45
+ if (!createResult.success) {
46
+ console.log(`โŒ Failed to create directory: ${createResult.errorMessage}`);
47
+ return;
48
+ }
49
+
50
+ console.log("โœ… Test directory created");
51
+
52
+ // Set up file change monitoring
53
+ const detectedChanges: FileChangeEvent[] = [];
54
+
55
+ const onFileChange = (events: FileChangeEvent[]) => {
56
+ console.log(`\n๐Ÿ”” Detected ${events.length} file changes:`);
57
+ for (const event of events) {
58
+ console.log(` ๐Ÿ“„ ${event.eventType.toUpperCase()}: ${event.path} (${event.pathType})`);
59
+ }
60
+ detectedChanges.push(...events);
61
+ };
62
+
63
+ console.log("\n๐Ÿ‘๏ธ Starting directory monitoring...");
64
+ console.log(" Press Ctrl+C to stop monitoring");
65
+
66
+ // Start monitoring
67
+ const controller = new AbortController();
68
+ const watchPromise = session.fileSystem.watchDirectory(
69
+ testDir,
70
+ onFileChange,
71
+ 1000, // Check every second
72
+ controller.signal
73
+ );
74
+
75
+ console.log("โœ… Directory monitoring started");
76
+
77
+ // Demonstrate file operations
78
+ console.log("\n๐Ÿ”จ Demonstrating file operations...");
79
+
80
+ // Create some files
81
+ const filesToCreate = [
82
+ { name: "example1.txt", content: "Hello, World!" },
83
+ { name: "example2.txt", content: "This is a test file." },
84
+ { name: "config.json", content: '{"setting": "value"}' }
85
+ ];
86
+
87
+ for (const file of filesToCreate) {
88
+ const filepath = `${testDir}/${file.name}`;
89
+ console.log(` Creating: ${file.name}`);
90
+
91
+ const writeResult = await session.fileSystem.writeFile(filepath, file.content);
92
+ if (writeResult.success) {
93
+ console.log(` โœ… Created: ${file.name}`);
94
+ } else {
95
+ console.log(` โŒ Failed to create ${file.name}: ${writeResult.errorMessage}`);
96
+ }
97
+
98
+ // Give time for monitoring to detect changes
99
+ await new Promise(resolve => setTimeout(resolve, 1500));
100
+ }
101
+
102
+ // Modify a file
103
+ console.log("\n Modifying example1.txt...");
104
+ const modifyResult = await session.fileSystem.writeFile(
105
+ `${testDir}/example1.txt`,
106
+ "Hello, World! - Modified content"
107
+ );
108
+ if (modifyResult.success) {
109
+ console.log(" โœ… Modified example1.txt");
110
+ } else {
111
+ console.log(` โŒ Failed to modify file: ${modifyResult.errorMessage}`);
112
+ }
113
+
114
+ // Wait a bit more to capture all events
115
+ console.log("\nโณ Waiting for final events...");
116
+ await new Promise(resolve => setTimeout(resolve, 3000));
117
+
118
+ // Stop monitoring
119
+ console.log("\n๐Ÿ›‘ Stopping directory monitoring...");
120
+ controller.abort();
121
+ await watchPromise;
122
+ console.log("โœ… Directory monitoring stopped");
123
+
124
+ // Summary
125
+ console.log("\n๐Ÿ“Š Summary:");
126
+ console.log(` Total events detected: ${detectedChanges.length}`);
127
+
128
+ if (detectedChanges.length > 0) {
129
+ console.log(" Event breakdown:");
130
+ const eventTypes: Record<string, number> = {};
131
+ for (const event of detectedChanges) {
132
+ eventTypes[event.eventType] = (eventTypes[event.eventType] || 0) + 1;
133
+ }
134
+
135
+ for (const [eventType, count] of Object.entries(eventTypes)) {
136
+ console.log(` ${eventType}: ${count}`);
137
+ }
138
+ }
139
+
140
+ console.log("\nโœจ Example completed successfully!");
141
+
142
+ } finally {
143
+ // Clean up session
144
+ console.log("\n๐Ÿงน Cleaning up...");
145
+ const deleteResult = await agentbay.delete(session);
146
+ if (deleteResult.success) {
147
+ console.log("โœ… Session cleaned up successfully");
148
+ } else {
149
+ console.log(`โš ๏ธ Session cleanup warning: ${deleteResult.errorMessage}`);
150
+ }
151
+ }
152
+
153
+ } catch (error) {
154
+ if (error instanceof Error && error.name === 'AbortError') {
155
+ console.log("\n\nโน๏ธ Monitoring stopped by user");
156
+ } else {
157
+ console.log(`\nโŒ An error occurred: ${error}`);
158
+ }
159
+ }
160
+ }
161
+
162
+ // Handle Ctrl+C gracefully
163
+ process.on('SIGINT', () => {
164
+ console.log("\n\nโน๏ธ Received interrupt signal, stopping...");
165
+ process.exit(0);
166
+ });
167
+
168
+ main().catch(console.error);
@@ -0,0 +1,136 @@
1
+ # Get API Example
2
+
3
+ This example demonstrates how to use the `get` API to retrieve a session by its ID.
4
+
5
+ ## Description
6
+
7
+ The `get` API allows you to retrieve a session object by providing its session ID. This is useful when you have a session ID from a previous operation and want to access or manage that session.
8
+
9
+ ## Prerequisites
10
+
11
+ - Node.js 16 or higher
12
+ - TypeScript 4.5 or higher
13
+ - Valid API key set in `AGENTBAY_API_KEY` environment variable
14
+ - wuying-agentbay-sdk package installed
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ npm install wuying-agentbay-sdk
20
+ # or
21
+ yarn add wuying-agentbay-sdk
22
+ ```
23
+
24
+ ## Usage
25
+
26
+ ```bash
27
+ # Set your API key
28
+ export AGENTBAY_API_KEY="your-api-key-here"
29
+
30
+ # Compile and run the example
31
+ npx ts-node main.ts
32
+ ```
33
+
34
+ ## Code Example
35
+
36
+ ```typescript
37
+ import { AgentBay } from "wuying-agentbay-sdk";
38
+
39
+ async function main() {
40
+ // Initialize AgentBay client
41
+ const apiKey = process.env.AGENTBAY_API_KEY;
42
+ const agentBay = new AgentBay({ apiKey });
43
+
44
+ // Retrieve a session by ID
45
+ const sessionId = "your-session-id";
46
+ const result = await agentBay.get(sessionId);
47
+
48
+ if (result.success && result.session) {
49
+ console.log(`Retrieved session: ${result.session.sessionId}`);
50
+ console.log(`Request ID: ${result.requestId}`);
51
+ // Use the session for further operations
52
+ // ...
53
+ } else {
54
+ console.error(`Failed to get session: ${result.errorMessage}`);
55
+ }
56
+ }
57
+
58
+ main();
59
+ ```
60
+
61
+ ## API Reference
62
+
63
+ ### get
64
+
65
+ ```typescript
66
+ async get(sessionId: string): Promise<SessionResult>
67
+ ```
68
+
69
+ Get a session by its ID.
70
+
71
+ **Parameters:**
72
+ - `sessionId` (string): The ID of the session to retrieve
73
+
74
+ **Returns:**
75
+ - `Promise<SessionResult>`: Promise resolving to result object containing:
76
+ - `success` (boolean): Whether the operation succeeded
77
+ - `session` (Session): The Session instance if successful
78
+ - `requestId` (string): The API request ID
79
+ - `errorMessage` (string): Error message if failed
80
+
81
+ ## Expected Output
82
+
83
+ ```
84
+ Creating a session...
85
+ Created session with ID: session-xxxxxxxxxxxxx
86
+
87
+ Retrieving session using Get API...
88
+ Successfully retrieved session:
89
+ Session ID: session-xxxxxxxxxxxxx
90
+ Request ID: DAD825FE-2CD8-19C8-BB30-CC3BA26B9398
91
+
92
+ Session is ready for use
93
+
94
+ Cleaning up...
95
+ Session session-xxxxxxxxxxxxx deleted successfully
96
+ ```
97
+
98
+ ## Notes
99
+
100
+ - The session ID must be valid and from an existing session
101
+ - The get API internally calls the GetSession API endpoint
102
+ - The returned session object can be used for all session operations (commands, files, etc.)
103
+ - Always clean up sessions when done to avoid resource waste
104
+
105
+ ## Error Handling
106
+
107
+ The `get` method returns a `SessionResult` object with error information:
108
+
109
+ 1. **Empty session_id**: Result will have `success: false`
110
+ ```typescript
111
+ const result = await agentBay.get("");
112
+ if (!result.success) {
113
+ console.error(`Error: ${result.errorMessage}`); // "session_id is required"
114
+ }
115
+ ```
116
+
117
+ 2. **Non-existent session**: Result will have `success: false`
118
+ ```typescript
119
+ const result = await agentBay.get("non-existent-session-id");
120
+ if (!result.success) {
121
+ console.error(`Error: ${result.errorMessage}`); // "Failed to get session..."
122
+ }
123
+ ```
124
+
125
+ ## TypeScript Support
126
+
127
+ This example is fully typed with TypeScript. The `get` method returns a typed `SessionResult` object with full IDE autocomplete support.
128
+
129
+ ```typescript
130
+ import { AgentBay, Session } from "wuying-agentbay-sdk";
131
+
132
+ const agentBay = new AgentBay({ apiKey: "your-key" });
133
+ const session: Session = await agentBay.get("session-id");
134
+ // TypeScript knows all methods and properties of session
135
+ ```
136
+
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Example demonstrating how to use the Get API to retrieve a session by its ID.
3
+ *
4
+ * This example shows:
5
+ * 1. Creating a session
6
+ * 2. Retrieving the session using the Get API
7
+ * 3. Using the session for operations
8
+ * 4. Cleaning up resources
9
+ * 5. Attempting to get a deleted session (error handling demonstration)
10
+ */
11
+
12
+ import { AgentBay } from "wuying-agentbay-sdk";
13
+
14
+ async function main() {
15
+ // Get API key from environment variable
16
+ const apiKey = process.env.AGENTBAY_API_KEY;
17
+ if (!apiKey) {
18
+ throw new Error("AGENTBAY_API_KEY environment variable is not set");
19
+ }
20
+
21
+ // Initialize AgentBay client
22
+ const agentBay = new AgentBay({ apiKey });
23
+
24
+ // For demonstration, first create a session
25
+ console.log("Creating a session...");
26
+ const createResult = await agentBay.create();
27
+ if (!createResult.success || !createResult.session) {
28
+ throw new Error(`Failed to create session: ${createResult.errorMessage}`);
29
+ }
30
+
31
+ const sessionId = createResult.session.sessionId;
32
+ console.log(`Created session with ID: ${sessionId}`);
33
+
34
+ // Retrieve the session by ID using Get API
35
+ console.log("\nRetrieving session using Get API...");
36
+ const getResult = await agentBay.get(sessionId);
37
+
38
+ if (!getResult.success || !getResult.session) {
39
+ throw new Error(`Failed to get session: ${getResult.errorMessage}`);
40
+ }
41
+
42
+ const session = getResult.session;
43
+
44
+ // Display session information
45
+ console.log("Successfully retrieved session:");
46
+ console.log(` Session ID: ${session.sessionId}`);
47
+ console.log(` Request ID: ${getResult.requestId}`);
48
+
49
+ // The session object can be used for further operations
50
+ // For example, you can execute commands, work with files, etc.
51
+ console.log("\nSession is ready for use");
52
+
53
+ // Clean up: Delete the session when done
54
+ console.log("\nCleaning up...");
55
+ const deleteResult = await session.delete();
56
+
57
+ if (deleteResult.success) {
58
+ console.log(`Session ${sessionId} deleted successfully`);
59
+ } else {
60
+ console.log(`Failed to delete session ${sessionId}`);
61
+ }
62
+
63
+ // Try to get the session again after deletion (should fail)
64
+ console.log("\nAttempting to get the deleted session...");
65
+ const getAfterDeleteResult = await agentBay.get(sessionId);
66
+
67
+ if (!getAfterDeleteResult.success) {
68
+ console.log("Expected behavior: Cannot retrieve deleted session");
69
+ console.log(`Error message: ${getAfterDeleteResult.errorMessage}`);
70
+ } else {
71
+ console.log("Unexpected: Session still exists after deletion");
72
+ }
73
+ }
74
+
75
+ main().catch((error) => {
76
+ console.error("Error:", error);
77
+ process.exit(1);
78
+ });
79
+
@@ -0,0 +1,54 @@
1
+ # List Sessions Example (TypeScript)
2
+
3
+ This example demonstrates how to use the `list()` API to query and filter sessions in AgentBay.
4
+
5
+ ## Prerequisites
6
+
7
+ 1. **Install dependencies**:
8
+ ```bash
9
+ npm install wuying-agentbay-sdk
10
+ npm install -D typescript ts-node @types/node
11
+ ```
12
+
13
+ 2. **Set API Key**:
14
+ ```bash
15
+ export AGENTBAY_API_KEY='your-api-key-here'
16
+ ```
17
+
18
+ ## Running the Example
19
+
20
+ ```bash
21
+ cd /path/to/wuying-agentbay-sdk/typescript/docs/examples/list_sessions
22
+ npx ts-node main.ts
23
+ ```
24
+
25
+ ## Key Features
26
+
27
+ - List all sessions
28
+ - Filter by single or multiple labels
29
+ - Pagination support
30
+ - Iterate through all pages
31
+
32
+ ## API Usage
33
+
34
+ ```typescript
35
+ import { AgentBay } from "wuying-agentbay-sdk";
36
+
37
+ const agentBay = new AgentBay(apiKey);
38
+
39
+ // List all sessions
40
+ const result = await agentBay.list();
41
+
42
+ // Filter by labels
43
+ const filtered = await agentBay.list({ project: "my-project" });
44
+
45
+ // With pagination
46
+ const page1 = await agentBay.list({ project: "my-project" }, 1, 10);
47
+ const page2 = await agentBay.list({ project: "my-project" }, 2, 10);
48
+ ```
49
+
50
+ ## Related Documentation
51
+
52
+ - [Session Management Guide](../../../../../../docs/guides/common-features/basics/session-management.md)
53
+ - [AgentBay API Reference](../../../../api/common-features/basics/agentbay.md)
54
+
@@ -0,0 +1,258 @@
1
+ /**
2
+ * AgentBay List Sessions Example
3
+ *
4
+ * This example demonstrates how to use the list() API to query sessions with filtering and pagination.
5
+ *
6
+ * Features demonstrated:
7
+ * 1. List all sessions
8
+ * 2. List sessions with label filtering
9
+ * 3. List sessions with pagination
10
+ * 4. Handle pagination to retrieve all results
11
+ *
12
+ * Usage:
13
+ * npx ts-node main.ts
14
+ */
15
+
16
+ import { AgentBay, CreateSessionParams, Session } from "wuying-agentbay-sdk";
17
+
18
+ async function main() {
19
+ // Get API key from environment variable
20
+ const apiKey = process.env.AGENTBAY_API_KEY;
21
+ if (!apiKey) {
22
+ console.error("Error: AGENTBAY_API_KEY environment variable not set");
23
+ console.error(
24
+ "Please set your API key: export AGENTBAY_API_KEY='your-api-key'"
25
+ );
26
+ process.exit(1);
27
+ }
28
+
29
+ // Initialize AgentBay client
30
+ const agentBay = new AgentBay({ apiKey });
31
+ console.log("โœ… AgentBay client initialized");
32
+
33
+ // Create some test sessions with labels for demonstration
34
+ console.log("\n๐Ÿ“ Creating test sessions...");
35
+ const testSessions: Session[] = [];
36
+
37
+ try {
38
+ // Create session 1 with labels
39
+ const params1: CreateSessionParams = {
40
+ labels: {
41
+ project: "list-demo",
42
+ environment: "dev",
43
+ owner: "demo-user",
44
+ },
45
+ };
46
+ const result1 = await agentBay.create(params1);
47
+ if (result1.success && result1.session) {
48
+ testSessions.push(result1.session);
49
+ console.log(`โœ… Created session 1: ${result1.session.sessionId}`);
50
+ console.log(` Request ID: ${result1.requestId}`);
51
+ }
52
+
53
+ // Create session 2 with labels
54
+ const params2: CreateSessionParams = {
55
+ labels: {
56
+ project: "list-demo",
57
+ environment: "staging",
58
+ owner: "demo-user",
59
+ },
60
+ };
61
+ const result2 = await agentBay.create(params2);
62
+ if (result2.success && result2.session) {
63
+ testSessions.push(result2.session);
64
+ console.log(`โœ… Created session 2: ${result2.session.sessionId}`);
65
+ console.log(` Request ID: ${result2.requestId}`);
66
+ }
67
+
68
+ // Create session 3 with labels
69
+ const params3: CreateSessionParams = {
70
+ labels: {
71
+ project: "list-demo",
72
+ environment: "prod",
73
+ owner: "demo-user",
74
+ },
75
+ };
76
+ const result3 = await agentBay.create(params3);
77
+ if (result3.success && result3.session) {
78
+ testSessions.push(result3.session);
79
+ console.log(`โœ… Created session 3: ${result3.session.sessionId}`);
80
+ console.log(` Request ID: ${result3.requestId}`);
81
+ }
82
+ } catch (error) {
83
+ console.error(`โŒ Error creating test sessions: ${error}`);
84
+ process.exit(1);
85
+ }
86
+
87
+ try {
88
+ // Example 1: List all sessions (no filter)
89
+ console.log("\n" + "=".repeat(60));
90
+ console.log("Example 1: List all sessions (no filter)");
91
+ console.log("=".repeat(60));
92
+
93
+ const result = await agentBay.list();
94
+ if (result.success) {
95
+ console.log(`โœ… Found ${result.totalCount} total sessions`);
96
+ console.log(`๐Ÿ“„ Showing ${result.sessionIds.length} session IDs on this page`);
97
+ console.log(`๐Ÿ”‘ Request ID: ${result.requestId}`);
98
+ console.log(`๐Ÿ“Š Max results per page: ${result.maxResults}`);
99
+
100
+ // Display first few sessions
101
+ for (let i = 0; i < Math.min(3, result.sessionIds.length); i++) {
102
+ console.log(` ${i + 1}. Session ID: ${result.sessionIds[i]}`);
103
+ }
104
+ } else {
105
+ console.log(`โŒ Error: ${result.errorMessage}`);
106
+ }
107
+
108
+ // Example 2: List sessions with specific label
109
+ console.log("\n" + "=".repeat(60));
110
+ console.log("Example 2: List sessions filtered by project label");
111
+ console.log("=".repeat(60));
112
+
113
+ const result2 = await agentBay.list({ project: "list-demo" });
114
+ if (result2.success) {
115
+ console.log(
116
+ `โœ… Found ${result2.totalCount} sessions with project='list-demo'`
117
+ );
118
+ console.log(`๐Ÿ“„ Showing ${result2.sessionIds.length} session IDs on this page`);
119
+ console.log(`๐Ÿ”‘ Request ID: ${result2.requestId}`);
120
+
121
+ for (let i = 0; i < result2.sessionIds.length; i++) {
122
+ console.log(` ${i + 1}. Session ID: ${result2.sessionIds[i]}`);
123
+ }
124
+ } else {
125
+ console.log(`โŒ Error: ${result2.errorMessage}`);
126
+ }
127
+
128
+ // Example 3: List sessions with multiple labels
129
+ console.log("\n" + "=".repeat(60));
130
+ console.log("Example 3: List sessions filtered by multiple labels");
131
+ console.log("=".repeat(60));
132
+
133
+ const result3 = await agentBay.list({
134
+ project: "list-demo",
135
+ environment: "dev",
136
+ });
137
+ if (result3.success) {
138
+ console.log(
139
+ `โœ… Found ${result3.totalCount} sessions with project='list-demo' AND environment='dev'`
140
+ );
141
+ console.log(`๐Ÿ“„ Showing ${result3.sessionIds.length} session IDs`);
142
+ console.log(`๐Ÿ”‘ Request ID: ${result3.requestId}`);
143
+
144
+ for (let i = 0; i < result3.sessionIds.length; i++) {
145
+ console.log(` ${i + 1}. Session ID: ${result3.sessionIds[i]}`);
146
+ }
147
+ } else {
148
+ console.log(`โŒ Error: ${result3.errorMessage}`);
149
+ }
150
+
151
+ // Example 4: List sessions with pagination
152
+ console.log("\n" + "=".repeat(60));
153
+ console.log("Example 4: List sessions with pagination (2 per page)");
154
+ console.log("=".repeat(60));
155
+
156
+ // Get first page
157
+ const resultPage1 = await agentBay.list({ project: "list-demo" }, 1, 2);
158
+ if (resultPage1.success) {
159
+ console.log(`๐Ÿ“„ Page 1:`);
160
+ console.log(` Total count: ${resultPage1.totalCount}`);
161
+ console.log(` Session IDs on this page: ${resultPage1.sessionIds.length}`);
162
+ console.log(` Request ID: ${resultPage1.requestId}`);
163
+
164
+ for (let i = 0; i < resultPage1.sessionIds.length; i++) {
165
+ console.log(` ${i + 1}. Session ID: ${resultPage1.sessionIds[i]}`);
166
+ }
167
+
168
+ // Get second page if available
169
+ if (resultPage1.nextToken) {
170
+ console.log(
171
+ `\n Has next page (token: ${resultPage1.nextToken.substring(0, 20)}...)`
172
+ );
173
+
174
+ const resultPage2 = await agentBay.list({ project: "list-demo" }, 2, 2);
175
+ if (resultPage2.success) {
176
+ console.log(`\n๐Ÿ“„ Page 2:`);
177
+ console.log(` Session IDs on this page: ${resultPage2.sessionIds.length}`);
178
+ console.log(` Request ID: ${resultPage2.requestId}`);
179
+
180
+ for (let i = 0; i < resultPage2.sessionIds.length; i++) {
181
+ console.log(
182
+ ` ${i + 1}. Session ID: ${resultPage2.sessionIds[i]}`
183
+ );
184
+ }
185
+ }
186
+ }
187
+ } else {
188
+ console.log(`โŒ Error: ${resultPage1.errorMessage}`);
189
+ }
190
+
191
+ // Example 5: Retrieve all session IDs across multiple pages
192
+ console.log("\n" + "=".repeat(60));
193
+ console.log("Example 5: Retrieve all session IDs with pagination loop");
194
+ console.log("=".repeat(60));
195
+
196
+ const allSessionIds: string[] = [];
197
+ let page = 1;
198
+ const limit = 2;
199
+
200
+ while (true) {
201
+ const result = await agentBay.list({ owner: "demo-user" }, page, limit);
202
+
203
+ if (!result.success) {
204
+ console.log(`โŒ Error on page ${page}: ${result.errorMessage}`);
205
+ break;
206
+ }
207
+
208
+ console.log(`๐Ÿ“„ Page ${page}: Found ${result.sessionIds.length} session IDs`);
209
+ allSessionIds.push(...result.sessionIds);
210
+
211
+ // Break if no more pages
212
+ if (!result.nextToken) {
213
+ break;
214
+ }
215
+
216
+ page++;
217
+ }
218
+
219
+ console.log(
220
+ `\nโœ… Retrieved ${allSessionIds.length} total session IDs across ${page} pages`
221
+ );
222
+ for (let i = 0; i < allSessionIds.length; i++) {
223
+ console.log(` ${i + 1}. Session ID: ${allSessionIds[i]}`);
224
+ }
225
+ } finally {
226
+ // Clean up: Delete test sessions
227
+ console.log("\n" + "=".repeat(60));
228
+ console.log("๐Ÿงน Cleaning up test sessions...");
229
+ console.log("=".repeat(60));
230
+
231
+ for (const session of testSessions) {
232
+ try {
233
+ const deleteResult = await agentBay.delete(session);
234
+ if (deleteResult.success) {
235
+ console.log(`โœ… Deleted session: ${session.sessionId}`);
236
+ console.log(` Request ID: ${deleteResult.requestId}`);
237
+ } else {
238
+ console.log(
239
+ `โŒ Failed to delete session ${session.sessionId}: ${deleteResult.errorMessage}`
240
+ );
241
+ }
242
+ } catch (error) {
243
+ console.error(
244
+ `โŒ Error deleting session ${session.sessionId}: ${error}`
245
+ );
246
+ }
247
+ }
248
+ }
249
+
250
+ console.log("\nโœจ Demo completed successfully!");
251
+ }
252
+
253
+ // Run the main function
254
+ main().catch((error) => {
255
+ console.error("โŒ Unhandled error:", error);
256
+ process.exit(1);
257
+ });
258
+