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,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,92 @@
1
+ # Mobile GetAdbUrl Example
2
+
3
+ This example demonstrates how to retrieve an ADB (Android Debug Bridge) connection URL for a mobile session.
4
+
5
+ ## Prerequisites
6
+
7
+ - Node.js 14 or higher
8
+ - AgentBay API key
9
+ - A mobile session (`mobile_latest` image)
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install @aliyun/wuying-agentbay-sdk
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ 1. Set your API key:
20
+ ```bash
21
+ export AGENTBAY_API_KEY=your_api_key_here
22
+ ```
23
+
24
+ 2. Run the example:
25
+ ```bash
26
+ npx ts-node index.ts
27
+ ```
28
+
29
+ ## Expected Output
30
+
31
+ ```
32
+ === Mobile GetAdbUrl Example ===
33
+
34
+ Creating mobile session...
35
+ ✅ Session created successfully
36
+ Session ID: session-xxxxx
37
+ Image ID: mobile_latest
38
+
39
+ Getting ADB connection URL...
40
+ ✅ ADB URL retrieved successfully
41
+ URL: adb connect xx.xx.xx.xx:xxxxx
42
+ Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
43
+
44
+ You can now connect to the mobile device using:
45
+ adb connect xx.xx.xx.xx:xxxxx
46
+
47
+ === Example completed successfully ===
48
+
49
+ Cleaning up session...
50
+ ✅ Session deleted successfully (RequestID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
51
+ ```
52
+
53
+ ## Using the ADB Connection
54
+
55
+ Once you have the ADB URL, you can connect to the mobile device:
56
+
57
+ ```bash
58
+ # Connect to the device
59
+ adb connect xx.xx.xx.xx:xxxxx
60
+
61
+ # Verify the connection
62
+ adb devices
63
+
64
+ # Now you can use standard ADB commands
65
+ adb shell
66
+ adb install app.apk
67
+ adb logcat
68
+ adb pull /sdcard/file.txt
69
+ adb push file.txt /sdcard/
70
+ ```
71
+
72
+ ## Important Notes
73
+
74
+ 1. **Environment Requirement**: This method only works with `mobile_latest` image sessions
75
+ 2. **ADB Public Key**: You need to provide your ADB public key for authentication
76
+ 3. **Connection URL Format**: The returned URL is in the format `adb connect <IP>:<Port>`
77
+ 4. **Session Cleanup**: Always delete the session when done to avoid resource leaks
78
+
79
+ ## Error Handling
80
+
81
+ The example includes proper error handling for common scenarios:
82
+ - Missing API key
83
+ - Session creation failure
84
+ - ADB URL retrieval failure
85
+ - Session deletion issues
86
+
87
+ ## See Also
88
+
89
+ - [Mobile API Documentation](../../../api/mobile-use/mobile.md)
90
+ - [Session Management Guide](../../../../../docs/guides/common-features/basics/session-management.md)
91
+ - [Mobile Use Guide](../../../../../docs/guides/mobile-use/README.md)
92
+