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.
Files changed (108) hide show
  1. package/dist/chunk-BVWUCG4J.mjs +3402 -0
  2. package/dist/chunk-BVWUCG4J.mjs.map +1 -0
  3. package/dist/chunk-SL5GCAQE.cjs +3393 -0
  4. package/dist/chunk-SL5GCAQE.cjs.map +1 -0
  5. package/dist/index.cjs +4623 -3978
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.mts +3934 -1964
  8. package/dist/index.d.ts +3934 -1964
  9. package/dist/index.mjs +4601 -3956
  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-CNCGFWJH.cjs +200 -0
  16. package/dist/model-CNCGFWJH.cjs.map +1 -0
  17. package/dist/model-LGWQJWKQ.mjs +209 -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 +277 -0
  25. package/docs/api/common-features/basics/command.md +83 -0
  26. package/docs/api/common-features/basics/context-manager.md +149 -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 +542 -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 +381 -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/common-features/basics/session-pause-resume/README.md +53 -0
  85. package/docs/examples/common-features/basics/session-pause-resume/session-pause-resume.ts +237 -0
  86. package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
  87. package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
  88. package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
  89. package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
  90. package/docs/examples/mobile-use/mobile-simulate-basic-usage.ts +202 -0
  91. package/docs/examples/mobile-use/mobile-simulate-with-ctx.ts +170 -0
  92. package/package.json +19 -12
  93. package/dist/application-KZWXH46T.mjs +0 -17
  94. package/dist/application-LMA7KSRH.cjs +0 -8
  95. package/dist/application-LMA7KSRH.cjs.map +0 -1
  96. package/dist/chunk-BQNGKBQF.mjs +0 -386
  97. package/dist/chunk-BQNGKBQF.mjs.map +0 -1
  98. package/dist/chunk-IOVGAAJL.cjs +0 -558
  99. package/dist/chunk-IOVGAAJL.cjs.map +0 -1
  100. package/dist/chunk-UF2TC2R4.mjs +0 -567
  101. package/dist/chunk-UF2TC2R4.mjs.map +0 -1
  102. package/dist/chunk-X6MS7Z5L.cjs +0 -377
  103. package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
  104. package/dist/window-DH37ZDD5.mjs +0 -17
  105. package/dist/window-DH37ZDD5.mjs.map +0 -1
  106. package/dist/window-U7N3H735.cjs +0 -8
  107. package/dist/window-U7N3H735.cjs.map +0 -1
  108. /package/dist/{application-KZWXH46T.mjs.map → model-LGWQJWKQ.mjs.map} +0 -0
@@ -0,0 +1,142 @@
1
+ # MCP Tool Direct Call Example (TypeScript)
2
+
3
+ This example demonstrates how to list available MCP tools and call them directly using the AgentBay TypeScript SDK.
4
+
5
+ ## Prerequisites
6
+
7
+ - Node.js 16 or higher
8
+ - AgentBay TypeScript SDK installed (`npm install wuying-agentbay-sdk`)
9
+ - AgentBay API Key (set as environment variable `AGENTBAY_API_KEY`)
10
+
11
+ ## Running the Example
12
+
13
+ ```bash
14
+ # Set your API key
15
+ export AGENTBAY_API_KEY=your_api_key_here
16
+
17
+ # Run the example
18
+ cd typescript/docs/examples/common-features/advanced/mcp_tool_direct_call
19
+ npx ts-node main.ts
20
+ ```
21
+
22
+ ## What This Example Does
23
+
24
+ 1. **Creates a Session**: Initializes an AgentBay session
25
+ 2. **Lists MCP Tools**: Retrieves all available MCP tools using `session.listMcpTools()`
26
+ 3. **Finds Shell Tool**: Locates the 'shell' tool and displays its details
27
+ 4. **Calls Shell Tool**: Executes commands using `session.callMcpTool()`:
28
+ - Echo command: `echo 'Hello from MCP Tool!'`
29
+ - Directory command: `pwd`
30
+ - Error handling: Invalid command demonstration
31
+ 5. **Cleanup**: Properly deletes the session
32
+
33
+ ## Expected Output
34
+
35
+ ```
36
+ Initializing AgentBay client...
37
+
38
+ 1. Creating session...
39
+ ✓ Session created successfully
40
+ Session ID: sess-xxxxx
41
+ Request ID: req-xxxxx
42
+
43
+ 2. Listing available MCP tools...
44
+ ✓ Found 69 MCP tools
45
+ Request ID: req-xxxxx
46
+
47
+ Available tools (showing first 10):
48
+ 1. get_resource
49
+ Description: The command to retrieve a wuying mcp runtime URL...
50
+ Server: mcp-server
51
+
52
+ 2. system_screenshot
53
+ Description: Captures a full-screen screenshot...
54
+ Server: mcp-server
55
+
56
+ ...
57
+
58
+ 3. Finding 'shell' tool details...
59
+ ✓ Found 'shell' tool
60
+ Description: Executes an shell command with timeout...
61
+ Server: wuying_shell
62
+ Input Schema:
63
+ {
64
+ "type": "object",
65
+ "required": ["command", "timeout_ms"],
66
+ "properties": {
67
+ "command": {
68
+ "type": "string",
69
+ "description": "client input command"
70
+ },
71
+ "timeout_ms": {
72
+ "type": "integer",
73
+ "default": 1000,
74
+ "description": "Command execution timeout (unit: milliseconds)..."
75
+ }
76
+ }
77
+ }
78
+
79
+ 4. Calling 'shell' tool...
80
+ ✓ Tool call successful
81
+ Request ID: req-xxxxx
82
+ Output:
83
+ Hello from MCP Tool!
84
+
85
+ 5. Calling 'shell' tool with different command...
86
+ ✓ Tool call successful
87
+ Request ID: req-xxxxx
88
+ Current directory:
89
+ /home/wuying
90
+
91
+ 6. Demonstrating error handling (invalid command)...
92
+ ✓ Error handled correctly
93
+ Request ID: req-xxxxx
94
+ Error message: Execution failed. Error code:127 Error message: sh: 1: this_command_does_not_exist_12345: not found
95
+
96
+ 7. Cleaning up...
97
+ ✓ Session deleted successfully
98
+ Request ID: req-xxxxx
99
+
100
+ ============================================================
101
+ Example completed successfully!
102
+ ============================================================
103
+ ```
104
+
105
+ ## Key API Methods
106
+
107
+ ### `session.listMcpTools()`
108
+
109
+ Lists all available MCP tools for the session.
110
+
111
+ **Returns:** `Promise<McpToolsResult>` containing:
112
+ - `tools`: Array of `McpTool` objects
113
+ - `requestId`: API request identifier
114
+
115
+ ### `session.callMcpTool(toolName, args)`
116
+
117
+ Calls an MCP tool directly.
118
+
119
+ **Parameters:**
120
+ - `toolName` (string): Name of the MCP tool
121
+ - `args` (Record<string, any>): Tool arguments
122
+
123
+ **Returns:** `Promise<McpToolResult>` containing:
124
+ - `success` (boolean): Whether the call succeeded
125
+ - `data` (string): Tool output
126
+ - `errorMessage` (string): Error message if failed
127
+ - `requestId` (string): API request identifier
128
+
129
+ ## Use Cases
130
+
131
+ This direct MCP tool calling approach is useful when you need to:
132
+
133
+ 1. **Discover Available Tools**: List all tools before deciding which to use
134
+ 2. **Call Tools Directly**: Bypass module-specific wrappers for direct access
135
+ 3. **Custom Tool Integration**: Build custom workflows with any available tool
136
+ 4. **Tool Exploration**: Inspect tool schemas and test different arguments
137
+
138
+ ## Related Documentation
139
+
140
+ - [Session API Reference](../../../../api/common-features/basics/session.md#callmcptool)
141
+ - [Common Features Guide](../../../../../../docs/guides/common-features/README.md)
142
+
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Example: List MCP Tools and Call a Tool
3
+ *
4
+ * This example demonstrates:
5
+ * 1. Creating a session
6
+ * 2. Listing all available MCP tools
7
+ * 3. Calling a specific tool (shell command)
8
+ * 4. Cleaning up the session
9
+ */
10
+
11
+ import { AgentBay } from 'wuying-agentbay-sdk';
12
+
13
+ async function main() {
14
+ // Initialize AgentBay client
15
+ console.log('Initializing AgentBay client...');
16
+ const agentBay = new AgentBay();
17
+
18
+ // Create a session
19
+ console.log('\n1. Creating session...');
20
+ const sessionResult = await agentBay.create();
21
+ const session = sessionResult.session;
22
+ console.log('✓ Session created successfully');
23
+ console.log(` Session ID: ${session.getSessionId()}`);
24
+ console.log(` Request ID: ${sessionResult.requestId}`);
25
+
26
+ try {
27
+ // List all available MCP tools
28
+ console.log('\n2. Listing available MCP tools...');
29
+ const toolsResult = await session.listMcpTools();
30
+ console.log(`✓ Found ${toolsResult.tools.length} MCP tools`);
31
+ console.log(` Request ID: ${toolsResult.requestId}`);
32
+
33
+ // Display first 10 tools
34
+ console.log('\n Available tools (showing first 10):');
35
+ for (let i = 0; i < Math.min(10, toolsResult.tools.length); i++) {
36
+ const tool = toolsResult.tools[i];
37
+ console.log(` ${i + 1}. ${tool.name}`);
38
+ console.log(` Description: ${tool.description}`);
39
+ console.log(` Server: ${tool.server}`);
40
+ if (tool.inputSchema.required) {
41
+ console.log(` Required params: ${tool.inputSchema.required.join(', ')}`);
42
+ }
43
+ console.log();
44
+ }
45
+
46
+ // Find and display the shell tool details
47
+ console.log("\n3. Finding 'shell' tool details...");
48
+ const shellTool = toolsResult.tools.find((tool: any) => tool.name === 'shell');
49
+
50
+ if (shellTool) {
51
+ console.log("✓ Found 'shell' tool");
52
+ console.log(` Description: ${shellTool.description}`);
53
+ console.log(` Server: ${shellTool.server}`);
54
+ console.log(` Input Schema:`);
55
+ console.log(` ${JSON.stringify(shellTool.inputSchema, null, 4)}`);
56
+ } else {
57
+ console.log("✗ 'shell' tool not found");
58
+ return;
59
+ }
60
+
61
+ // Call the shell tool
62
+ console.log("\n4. Calling 'shell' tool...");
63
+ const result = await session.callMcpTool('shell', {
64
+ command: "echo 'Hello from MCP Tool!'",
65
+ timeout_ms: 1000
66
+ });
67
+
68
+ if (result.success) {
69
+ console.log('✓ Tool call successful');
70
+ console.log(` Request ID: ${result.requestId}`);
71
+ console.log(` Output:`);
72
+ console.log(` ${result.data}`);
73
+ } else {
74
+ console.log('✗ Tool call failed');
75
+ console.log(` Error: ${result.errorMessage}`);
76
+ console.log(` Request ID: ${result.requestId}`);
77
+ }
78
+
79
+ // Call another command to demonstrate flexibility
80
+ console.log("\n5. Calling 'shell' tool with different command...");
81
+ const result2 = await session.callMcpTool('shell', {
82
+ command: 'pwd',
83
+ timeout_ms: 1000
84
+ });
85
+
86
+ if (result2.success) {
87
+ console.log('✓ Tool call successful');
88
+ console.log(` Request ID: ${result2.requestId}`);
89
+ console.log(` Current directory:`);
90
+ console.log(` ${result2.data}`);
91
+ } else {
92
+ console.log('✗ Tool call failed');
93
+ console.log(` Error: ${result2.errorMessage}`);
94
+ }
95
+
96
+ // Demonstrate error handling
97
+ console.log('\n6. Demonstrating error handling (invalid command)...');
98
+ const result3 = await session.callMcpTool('shell', {
99
+ command: 'this_command_does_not_exist_12345',
100
+ timeout_ms: 1000
101
+ });
102
+
103
+ if (result3.success) {
104
+ console.log('✓ Command executed');
105
+ console.log(` Output: ${result3.data}`);
106
+ } else {
107
+ console.log('✓ Error handled correctly');
108
+ console.log(` Request ID: ${result3.requestId}`);
109
+ console.log(` Error message: ${result3.errorMessage.substring(0, 100)}...`);
110
+ }
111
+
112
+ } finally {
113
+ // Clean up - delete the session
114
+ console.log('\n7. Cleaning up...');
115
+ const deleteResult = await agentBay.delete(session);
116
+ if (deleteResult.success) {
117
+ console.log('✓ Session deleted successfully');
118
+ console.log(` Request ID: ${deleteResult.requestId}`);
119
+ } else {
120
+ console.log('✗ Failed to delete session');
121
+ console.log(` Error: ${deleteResult.errorMessage}`);
122
+ }
123
+ }
124
+
125
+ console.log('\n' + '='.repeat(60));
126
+ console.log('Example completed successfully!');
127
+ console.log('='.repeat(60));
128
+ }
129
+
130
+ // Run the example
131
+ main().catch((error) => {
132
+ console.error('Error running example:', error);
133
+ process.exit(1);
134
+ });
135
+
@@ -0,0 +1,28 @@
1
+ # Session Creation and Management Example
2
+
3
+ This example demonstrates how to create, list, and delete sessions using the Wuying AgentBay SDK. It covers:
4
+
5
+ - Initializing the AgentBay client
6
+ - Creating a session with default parameters
7
+ - Listing all available sessions
8
+ - Creating multiple sessions
9
+ - Deleting sessions
10
+ - Verifying session deletion
11
+
12
+ This example is useful for understanding the session lifecycle and how to manage multiple sessions.
13
+
14
+ ## Running the Example
15
+
16
+ ```bash
17
+ cd session-creation
18
+ npx ts-node session-creation.ts
19
+ ```
20
+
21
+ Make sure you have set the `AGENTBAY_API_KEY` environment variable or replace the placeholder in the code with your actual API key.
22
+
23
+ ## Prerequisites
24
+
25
+ - Node.js installed
26
+ - TypeScript installed
27
+ - ts-node installed (`npm install -g ts-node`)
28
+ - Required dependencies installed (`npm install`)
@@ -0,0 +1,295 @@
1
+
2
+ import { AgentBay, log, logError, CreateSessionParams, ContextSync, newSyncPolicy, ContextStatusData, newCreateSessionParams, MobileExtraConfig, AppManagerRule, ExtraConfigs } from 'wuying-agentbay-sdk'
3
+
4
+
5
+
6
+ /**
7
+ * Create a session with default parameters
8
+ */
9
+ async function createSessionWithDefaultParams() {
10
+ // Initialize the AgentBay client
11
+ const agent_bay = new AgentBay({ apiKey: process.env.AGENTBAY_API_KEY });
12
+
13
+ try {
14
+ // Create a session with default parameters
15
+ const result = await agent_bay.create();
16
+
17
+ if (result.success && result.session) {
18
+ log(`Session created successfully with ID: ${result.session.sessionId}`);
19
+ log(`Request ID: ${result.requestId}`);
20
+
21
+ // Clean up
22
+ const deleteResult = await agent_bay.delete(result.session);
23
+ if (deleteResult.success) {
24
+ log('Session deleted successfully');
25
+ } else {
26
+ log(`Failed to delete session: ${deleteResult.errorMessage}`);
27
+ }
28
+ } else {
29
+ log(`Failed to create session: ${result.errorMessage}`);
30
+ }
31
+ } catch (error) {
32
+ logError('Error:', error);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Create a session with labels
38
+ */
39
+ async function createSessionWithLabels() {
40
+ // Initialize the AgentBay client
41
+ const agent_bay = new AgentBay({ apiKey: process.env.AGENTBAY_API_KEY });
42
+
43
+ try {
44
+ // Define labels
45
+ const labels = {
46
+ environment: 'development',
47
+ project: 'example',
48
+ owner: 'user123'
49
+ };
50
+
51
+ // Create session parameters with labels
52
+ const params: CreateSessionParams = {
53
+ labels
54
+ };
55
+
56
+ // Create a session with the parameters
57
+ const result = await agent_bay.create(params);
58
+
59
+ if (result.success && result.session) {
60
+ log(`Session with labels created successfully with ID: ${result.session.sessionId}`);
61
+ log(`Request ID: ${result.requestId}`);
62
+
63
+ // Verify the labels were set
64
+ const labelResult = await result.session.getLabels();
65
+ if (labelResult.success && labelResult.data) {
66
+ log('Retrieved labels:');
67
+ Object.entries(labelResult.data).forEach(([key, value]) => {
68
+ log(` ${key}: ${value}`);
69
+ });
70
+ }
71
+
72
+ // Clean up
73
+ const deleteResult = await agent_bay.delete(result.session);
74
+ if (deleteResult.success) {
75
+ log('Session deleted successfully');
76
+ } else {
77
+ log(`Failed to delete session: ${deleteResult.errorMessage}`);
78
+ }
79
+ } else {
80
+ log(`Failed to create session with labels: ${result.errorMessage}`);
81
+ }
82
+ } catch (error) {
83
+ logError('Error:', error);
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Create a session with persistent context
89
+ */
90
+ async function createSessionWithContext() {
91
+ // Initialize the AgentBay client
92
+ const agent_bay = new AgentBay({ apiKey: process.env.AGENTBAY_API_KEY });
93
+
94
+ try {
95
+ // Create or get a persistent context
96
+ const contextResult = await agent_bay.context.get('example-context', true);
97
+
98
+ if (contextResult.success && contextResult.context) {
99
+ log(`Using context with ID: ${contextResult.context.id}`);
100
+
101
+ // Create a session linked to the context
102
+ const params = newCreateSessionParams()
103
+ .addContextSync(contextResult.context.id, "/home/wuying");
104
+
105
+ const sessionResult = await agent_bay.create(params);
106
+
107
+ if (sessionResult.success && sessionResult.session) {
108
+ log(`Session with context created successfully with ID: ${sessionResult.session.sessionId}`);
109
+ log(`Request ID: ${sessionResult.requestId}`);
110
+
111
+ // Clean up
112
+ const deleteResult = await agent_bay.delete(sessionResult.session);
113
+ if (deleteResult.success) {
114
+ log('Session deleted successfully');
115
+ } else {
116
+ log(`Failed to delete session: ${deleteResult.errorMessage}`);
117
+ }
118
+ } else {
119
+ log(`Failed to create session with context: ${sessionResult.errorMessage}`);
120
+ }
121
+ } else {
122
+ log(`Failed to get or create context: ${contextResult.errorMessage}`);
123
+ }
124
+ } catch (error) {
125
+ logError('Error:', error);
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Create a session with context synchronization
131
+ */
132
+ async function createSessionWithContextSync() {
133
+ // Initialize the AgentBay client
134
+ const agent_bay = new AgentBay({ apiKey: process.env.AGENTBAY_API_KEY });
135
+
136
+ try {
137
+ // Create or get a persistent context
138
+ const contextResult = await agent_bay.context.get('example-sync-context', true);
139
+
140
+ if (contextResult.success && contextResult.context) {
141
+ log(`Using context with ID: ${contextResult.context.id}`);
142
+
143
+ // Create a context sync configuration with default policy
144
+ const contextId = contextResult.context.id;
145
+ const path = '/mnt/persistent'
146
+ const policy = newSyncPolicy();
147
+ const contextSync = new ContextSync(contextId,path,policy);
148
+
149
+ // Create a session with context synchronization
150
+ const params: CreateSessionParams = {
151
+ contextSync: [contextSync]
152
+ };
153
+
154
+ const sessionResult = await agent_bay.create(params);
155
+
156
+ if (sessionResult.success && sessionResult.session) {
157
+ log(`Session with context sync created successfully with ID: ${sessionResult.session.sessionId}`);
158
+ log(`Request ID: ${sessionResult.requestId}`);
159
+
160
+ // List the synchronized contexts
161
+ // Wait for context to be synchronized
162
+ await new Promise(resolve => setTimeout(resolve, 2000));
163
+
164
+ const listResult = await sessionResult.session.context.info();
165
+ if (listResult.requestId && listResult.contextStatusData.length > 0) {
166
+ log(`Found ${listResult.contextStatusData.length} synchronized contexts:`);
167
+ listResult.contextStatusData.forEach((ctx:ContextStatusData) => {
168
+
169
+ log(`Context ID: ${ctx.contextId}, Path: ${ctx.path}, State: ${ctx.status}`);
170
+ });
171
+ }
172
+
173
+ // Clean up
174
+ const deleteResult = await agent_bay.delete(sessionResult.session);
175
+ if (deleteResult.success) {
176
+ log('Session deleted successfully');
177
+ } else {
178
+ log(`Failed to delete session: ${deleteResult.errorMessage}`);
179
+ }
180
+ } else {
181
+ log(`Failed to create session with context sync: ${sessionResult.errorMessage}`);
182
+ }
183
+ } else {
184
+ log(`Failed to get or create context: ${contextResult.errorMessage}`);
185
+ }
186
+ } catch (error) {
187
+ logError('Error:', error);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Create a mobile session with extra configurations
193
+ */
194
+ async function createMobileSessionWithExtraConfigs() {
195
+ // Initialize the AgentBay client
196
+ const agent_bay = new AgentBay({ apiKey: process.env.AGENTBAY_API_KEY });
197
+
198
+ try {
199
+ // Create mobile configuration with app manager rule, resolution lock, navigation bar control, and uninstall protection
200
+ const appRule: AppManagerRule = {
201
+ ruleType: "White",
202
+ appPackageNameList: [
203
+ "com.android.settings",
204
+ "com.example.test.app",
205
+ "com.trusted.service",
206
+ "com.system.essential.service"
207
+ ]
208
+ };
209
+
210
+ const mobileConfig: MobileExtraConfig = {
211
+ lockResolution: true, // Lock screen resolution for consistent testing
212
+ appManagerRule: appRule,
213
+ hideNavigationBar: true, // Hide navigation bar for immersive experience
214
+ uninstallBlacklist: [ // Protect critical apps from uninstallation
215
+ "com.android.systemui",
216
+ "com.android.settings",
217
+ "com.google.android.gms"
218
+ ]
219
+ };
220
+
221
+ const extraConfigs: ExtraConfigs = {
222
+ mobile: mobileConfig
223
+ };
224
+
225
+ // Create session parameters with extra configurations
226
+ const params = newCreateSessionParams()
227
+ .withImageId("mobile_latest")
228
+ .withLabels({
229
+ project: "mobile-testing",
230
+ environment: "development",
231
+ config_type: "comprehensive"
232
+ })
233
+ .withExtraConfigs(extraConfigs);
234
+
235
+ // Create session
236
+ const result = await agent_bay.create(params);
237
+
238
+ if (result.success && result.session) {
239
+ log(`Mobile session with extra configs created with ID: ${result.session.sessionId}`);
240
+ log(`Request ID: ${result.requestId}`);
241
+ log('Extra configurations applied:');
242
+ log(`- Lock Resolution: ${mobileConfig.lockResolution}`);
243
+ log(`- Hide Navigation Bar: ${mobileConfig.hideNavigationBar}`);
244
+ log(`- App Manager Rule Type: ${appRule.ruleType}`);
245
+ log(`- Managed Apps: ${appRule.appPackageNameList.length}`);
246
+ appRule.appPackageNameList.forEach(pkg => {
247
+ log(` - ${pkg}`);
248
+ });
249
+ log(`- Uninstall Protection: ${mobileConfig.uninstallBlacklist?.length} packages`);
250
+ mobileConfig.uninstallBlacklist?.forEach(pkg => {
251
+ log(` - ${pkg}`);
252
+ });
253
+
254
+ // Clean up
255
+ const deleteResult = await agent_bay.delete(result.session);
256
+ if (deleteResult.success) {
257
+ log('Mobile session deleted successfully');
258
+ } else {
259
+ log(`Failed to delete mobile session: ${deleteResult.errorMessage}`);
260
+ }
261
+ } else {
262
+ log(`Failed to create mobile session: ${result.errorMessage}`);
263
+ }
264
+ } catch (error) {
265
+ logError('Error:', error);
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Run all examples
271
+ */
272
+ async function main() {
273
+ log('Session Creation Examples');
274
+ log('=========================');
275
+
276
+ log('\n1. Creating session with default parameters...');
277
+ await createSessionWithDefaultParams();
278
+
279
+ log('\n2. Creating session with labels...');
280
+ await createSessionWithLabels();
281
+
282
+ log('\n3. Creating session with context...');
283
+ await createSessionWithContext();
284
+
285
+ log('\n4. Creating session with context synchronization...');
286
+ await createSessionWithContextSync();
287
+
288
+ log('\n5. Creating mobile session with extra configurations...');
289
+ await createMobileSessionWithExtraConfigs();
290
+ }
291
+
292
+ main().catch(error => {
293
+ logError('Error in main:', error);
294
+ process.exit(1);
295
+ });
@@ -0,0 +1,53 @@
1
+ # Session Pause and Resume Example
2
+
3
+ This example demonstrates how to pause and resume sessions using the Wuying AgentBay SDK. Pausing a session puts it into a dormant state, consuming fewer resources while maintaining its state. Resuming a session brings it back to an active state.
4
+
5
+ ## Features Demonstrated
6
+
7
+ - Pausing and resuming sessions
8
+ - Handling non-existent session operations
9
+ - Using custom timeout and polling interval parameters
10
+ - Checking session status before and after operations
11
+ - Performing work in sessions before and after pause/resume cycles
12
+
13
+ ## Running the Example
14
+
15
+ ```bash
16
+ cd session-pause-resume
17
+ npx ts-node session-pause-resume.ts
18
+ ```
19
+
20
+ Make sure you have set the `AGENTBAY_API_KEY` environment variable or replace the placeholder in the code with your actual API key.
21
+
22
+ ## Prerequisites
23
+
24
+ - Node.js installed
25
+ - TypeScript installed
26
+ - ts-node installed (`npm install -g ts-node`)
27
+ - Required dependencies installed (`npm install`)
28
+
29
+ ## Understanding Session States
30
+
31
+ When working with pause and resume operations, sessions can be in different states:
32
+
33
+ 1. **RUNNING**: Session is active and ready to accept commands
34
+ 2. **PAUSING**: Session is transitioning to paused state
35
+ 3. **PAUSED**: Session is in dormant state, consuming fewer resources
36
+ 4. **RESUMING**: Session is transitioning back to running state
37
+
38
+ The pause and resume operations are asynchronous, meaning they initiate the state transition and then poll for completion.
39
+
40
+ ## Best Practices
41
+
42
+ 1. **Always check operation results**: Verify that pause and resume operations succeeded
43
+ 2. **Handle errors gracefully**: Non-existent sessions and other errors should be handled appropriately
44
+ 3. **Use appropriate timeouts**: Custom timeout values can be used based on your specific requirements
45
+ 4. **Verify session state**: Check session status before and after operations to ensure expected behavior
46
+ 5. **Clean up resources**: Always delete sessions when done to avoid resource leaks
47
+
48
+ ## Use Cases
49
+
50
+ - **Cost optimization**: Pause sessions during idle periods to reduce resource consumption
51
+ - **Long-running workflows**: Suspend sessions overnight or during maintenance windows
52
+ - **Development and testing**: Pause test environments when not actively working on them
53
+ - **Batch processing**: Pause and resume processing jobs based on system load