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,242 @@
1
+ /**
2
+ * Integration test for browser fingerprint persistence functionality.
3
+ * This test verifies that browser fingerprint can be persisted
4
+ * across sessions using the same ContextId and FingerprintContextId.
5
+ */
6
+
7
+ // @ts-nocheck
8
+ import { AgentBay, CreateSessionParams } from 'wuying-agentbay-sdk';
9
+ import { BrowserOption, BrowserFingerprint, BrowserContext, BrowserFingerprintContext } from 'wuying-agentbay-sdk';
10
+ import { chromium } from 'playwright';
11
+
12
+ // Global variables for persistent context and fingerprint context
13
+ let persistentContext: any = null;
14
+ let persistentFingerprintContext: any = null;
15
+
16
+ function getTestApiKey(): string {
17
+ const apiKey = process.env.AGENTBAY_API_KEY;
18
+ if (!apiKey) {
19
+ throw new Error("AGENTBAY_API_KEY environment variable not set");
20
+ }
21
+ return apiKey;
22
+ }
23
+
24
+ function isWindowsUserAgent(userAgent: string): boolean {
25
+ if (!userAgent) {
26
+ return false;
27
+ }
28
+ const userAgentLower = userAgent.toLowerCase();
29
+ const windowsIndicators = [
30
+ 'windows nt',
31
+ 'win32',
32
+ 'win64',
33
+ 'windows',
34
+ 'wow64'
35
+ ];
36
+ return windowsIndicators.some(indicator => userAgentLower.includes(indicator));
37
+ }
38
+
39
+ async function runAsFirstTime(): Promise<void> {
40
+ console.log("====================");
41
+ console.log("Run as first time");
42
+ console.log("====================");
43
+
44
+ const apiKey = getTestApiKey();
45
+ const agentBay = new AgentBay({ apiKey });
46
+
47
+ // Create a browser context for first time
48
+ const sessionContextName = `test-browser-context-${Date.now()}`;
49
+ const contextResult = await agentBay.context.get(sessionContextName, true);
50
+ if (!contextResult.success || !contextResult.context) {
51
+ console.log("Failed to create browser context");
52
+ return;
53
+ }
54
+
55
+ persistentContext = contextResult.context;
56
+ console.log(`Created browser context: ${persistentContext.name} (ID: ${persistentContext.id})`);
57
+
58
+ // Create a browser fingerprint context for first time
59
+ const fingerprintContextName = `test-browser-fingerprint-${Date.now()}`;
60
+ const fingerprintContextResult = await agentBay.context.get(fingerprintContextName, true);
61
+ if (!fingerprintContextResult.success || !fingerprintContextResult.context) {
62
+ console.log("Failed to create fingerprint context");
63
+ return;
64
+ }
65
+
66
+ persistentFingerprintContext = fingerprintContextResult.context;
67
+ console.log(`Created fingerprint context: ${persistentFingerprintContext.name} (ID: ${persistentFingerprintContext.id})`);
68
+
69
+ // Create session with BrowserContext and FingerprintContext
70
+ console.log(`Creating session with browser context ID: ${persistentContext.id} ` +
71
+ `and fingerprint context ID: ${persistentFingerprintContext.id}`);
72
+
73
+ const fingerprintContext = new BrowserFingerprintContext(persistentFingerprintContext.id);
74
+ const browserContext = new BrowserContext(persistentContext.id, true, undefined, fingerprintContext);
75
+
76
+ const params = new CreateSessionParams()
77
+ .withImageId("browser_latest")
78
+ .withBrowserContext(browserContext);
79
+
80
+ const sessionResult = await agentBay.create(params);
81
+ if (!sessionResult.success || !sessionResult.session) {
82
+ console.log(`Failed to create first session: ${sessionResult.errorMessage}`);
83
+ return;
84
+ }
85
+
86
+ const session = sessionResult.session;
87
+ console.log(`First session created with ID: ${session.sessionId}`);
88
+
89
+ // Get browser object and generate fingerprint for persistence
90
+ async function firstSessionOperations(): Promise<void> {
91
+ // Initialize browser with fingerprint persistent enabled and set fingerprint generation options
92
+ const browserOption: BrowserOption = {
93
+ useStealth: true,
94
+ fingerprintPersistent: true,
95
+ fingerprint: {
96
+ devices: ["desktop"],
97
+ operatingSystems: ["windows"],
98
+ locales: ["zh-CN"]
99
+ } as BrowserFingerprint
100
+ };
101
+
102
+ const initSuccess = await session.browser.initializeAsync(browserOption);
103
+ if (!initSuccess) {
104
+ console.log("Failed to initialize browser");
105
+ return;
106
+ }
107
+ console.log("First session browser initialized successfully");
108
+
109
+ // Get endpoint URL
110
+ const endpointUrl = await session.browser.getEndpointUrl();
111
+ if (!endpointUrl) {
112
+ console.log("Failed to get browser endpoint URL");
113
+ return;
114
+ }
115
+ console.log(`First session browser endpoint URL: ${endpointUrl}`);
116
+
117
+ // Connect with playwright, test first session fingerprint
118
+ console.log("Opening https://httpbin.org/user-agent and test user agent...");
119
+ const browser = await chromium.connectOverCDP(endpointUrl);
120
+ const context = browser.contexts().length > 0 ? browser.contexts()[0] : await browser.newContext();
121
+
122
+ const page = await context.newPage();
123
+ await page.goto("https://httpbin.org/user-agent", { timeout: 60000 });
124
+ const response = await page.evaluate(() => JSON.parse(document.body.textContent));
125
+ const userAgent = response["user-agent"];
126
+ console.log("user_agent =", userAgent);
127
+
128
+ const isWindows = isWindowsUserAgent(userAgent);
129
+ if (!isWindows) {
130
+ console.log("Failed to get windows user agent");
131
+ return;
132
+ }
133
+
134
+ await context.close();
135
+ console.log("First session browser fingerprint check completed");
136
+ }
137
+
138
+ // Run first session operations
139
+ await firstSessionOperations();
140
+
141
+ // Delete first session with syncContext=true
142
+ console.log("Deleting first session with syncContext=true...");
143
+ const deleteResult = await agentBay.delete(session, { syncContext: true });
144
+ console.log(`First session deleted successfully (RequestID: ${deleteResult.requestId})`);
145
+ }
146
+
147
+ async function runAsSecondTime(): Promise<void> {
148
+ console.log("====================");
149
+ console.log("Run as second time");
150
+ console.log("====================");
151
+
152
+ const apiKey = getTestApiKey();
153
+ const agentBay = new AgentBay({ apiKey });
154
+
155
+ // Create second session with same browser context and fingerprint context
156
+ console.log(`Creating second session with same browser context ID: ${persistentContext.id} ` +
157
+ `and fingerprint context ID: ${persistentFingerprintContext.id}`);
158
+
159
+ const fingerprintContext = new BrowserFingerprintContext(persistentFingerprintContext.id);
160
+ const browserContext = new BrowserContext(persistentContext.id, true, undefined, fingerprintContext);
161
+
162
+ const params = new CreateSessionParams()
163
+ .withImageId("browser_latest")
164
+ .withBrowserContext(browserContext);
165
+
166
+ const sessionResult = await agentBay.create(params);
167
+ if (!sessionResult.success || !sessionResult.session) {
168
+ console.log(`Failed to create second session: ${sessionResult.errorMessage}`);
169
+ return;
170
+ }
171
+
172
+ const session = sessionResult.session;
173
+ console.log(`Second session created with ID: ${session.sessionId}`);
174
+
175
+ // Get browser object and check if second session fingerprint is the same as first session
176
+ async function secondSessionOperations(): Promise<void> {
177
+ // Initialize browser with fingerprint persistent enabled but not specific fingerprint generation options
178
+ const browserOption: BrowserOption = {
179
+ useStealth: true,
180
+ fingerprintPersistent: true
181
+ };
182
+
183
+ const initSuccess = await session.browser.initializeAsync(browserOption);
184
+ if (!initSuccess) {
185
+ console.log("Failed to initialize browser in second session");
186
+ return;
187
+ }
188
+ console.log("Second session browser initialized successfully");
189
+
190
+ // Get endpoint URL
191
+ const endpointUrl = await session.browser.getEndpointUrl();
192
+ if (!endpointUrl) {
193
+ console.log("Failed to get browser endpoint URL in second session");
194
+ return;
195
+ }
196
+ console.log(`Second session browser endpoint URL: ${endpointUrl}`);
197
+
198
+ // Connect with playwright and test second session fingerprint
199
+ const browser = await chromium.connectOverCDP(endpointUrl);
200
+ const context = browser.contexts().length > 0 ? browser.contexts()[0] : await browser.newContext();
201
+ const page = await context.newPage();
202
+ await page.goto("https://httpbin.org/user-agent", { timeout: 60000 });
203
+ const response = await page.evaluate(() => JSON.parse(document.body.textContent));
204
+ const userAgent = response["user-agent"];
205
+ console.log("user_agent =", userAgent);
206
+
207
+ const isWindows = isWindowsUserAgent(userAgent);
208
+ if (!isWindows) {
209
+ console.log("Failed to get windows user agent in second session");
210
+ return;
211
+ }
212
+ console.log("SUCCESS: fingerprint persisted correctly!");
213
+
214
+ await context.close();
215
+ console.log("Second session browser fingerprint check completed");
216
+ }
217
+
218
+ // Run second session operations
219
+ await secondSessionOperations();
220
+
221
+ // Delete second session with syncContext=true
222
+ console.log("Deleting second session with syncContext=true...");
223
+ const deleteResult = await agentBay.delete(session, { syncContext: true });
224
+ console.log(`Second session deleted successfully (RequestID: ${deleteResult.requestId})`);
225
+ }
226
+
227
+ async function main(): Promise<void> {
228
+ /**
229
+ * Test browser fingerprint persist across sessions with the same browser and fingerprint context.
230
+ */
231
+ try {
232
+ await runAsFirstTime();
233
+ await new Promise(resolve => setTimeout(resolve, 3000)); // Wait 3 seconds
234
+ await runAsSecondTime();
235
+ } catch (error) {
236
+ console.error("Error in main function:", error);
237
+ }
238
+ }
239
+
240
+ if (require.main === module) {
241
+ main().catch(console.error);
242
+ }
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Example demonstrating Browser Proxy configuration with AgentBay SDK.
3
+ *
4
+ * This example shows how to use proxy functionality with AgentBay SDK.
5
+ * AgentBay supports two types of proxies:
6
+ *
7
+ * 1. Custom Proxy:
8
+ * - Uses user-provided proxy servers
9
+ * - Supports HTTP/HTTPS/SOCKS proxies
10
+ * - Optionally provides username and password for authentication
11
+ *
12
+ * 2. Wuying Proxy:
13
+ * - Uses Alibaba Cloud Wuying proxy service
14
+ * - Supports two strategies:
15
+ * * restricted: Uses fixed proxy nodes
16
+ * * polling: Rotates through proxy pool nodes
17
+ *
18
+ * This example demonstrates:
19
+ * - Create AIBrowser session with proxy configuration
20
+ * - Use playwright to connect to AIBrowser instance through CDP protocol
21
+ * - Verify the proxy's public IP address
22
+ */
23
+
24
+ // @ts-nocheck
25
+ import { AgentBay, CreateSessionParams } from 'wuying-agentbay-sdk';
26
+ import { BrowserOption, BrowserProxy } from 'wuying-agentbay-sdk';
27
+ import { chromium } from 'playwright';
28
+
29
+ interface IpResponse {
30
+ origin: string;
31
+ }
32
+
33
+ async function main(): Promise<void> {
34
+ // Get API key from environment variable
35
+ const apiKey = process.env.AGENTBAY_API_KEY;
36
+ if (!apiKey) {
37
+ console.log('Error: AGENTBAY_API_KEY environment variable not set');
38
+ return;
39
+ }
40
+
41
+ try {
42
+ // Initialize AgentBay client
43
+ console.log('Initializing AgentBay client...');
44
+ const agentBay = new AgentBay({ apiKey });
45
+
46
+ // Create a session
47
+ console.log('Creating a new session...');
48
+ const params: CreateSessionParams = {
49
+ imageId: 'browser_latest',
50
+ };
51
+ const sessionResult = await agentBay.create(params);
52
+
53
+ if (!sessionResult.success) {
54
+ console.log('Failed to create session');
55
+ return;
56
+ }
57
+
58
+ const session = sessionResult.session;
59
+ console.log(`Session created with ID: ${session.sessionId}`);
60
+
61
+ // ==================== Proxy Configuration Examples ====================
62
+
63
+ // Example 1: Custom Proxy Configuration
64
+ // Suitable for users who have their own proxy servers
65
+ // const browserProxy: BrowserProxy = {
66
+ // type: 'custom',
67
+ // server: 'http://127.0.0.1:9090',
68
+ // username: 'username',
69
+ // password: 'password',
70
+ // toMap: function() {
71
+ // return {
72
+ // type: this.type,
73
+ // server: this.server,
74
+ // username: this.username,
75
+ // password: this.password
76
+ // };
77
+ // }
78
+ // };
79
+
80
+ // Example 2: Wuying Proxy - Polling Strategy
81
+ // Rotates through proxy pool nodes, suitable for scenarios requiring frequent IP switching
82
+ const browserProxy: BrowserProxy = {
83
+ type: 'wuying',
84
+ strategy: 'polling',
85
+ pollsize: 2,
86
+ toMap: function() {
87
+ return {
88
+ type: this.type,
89
+ strategy: this.strategy,
90
+ pollsize: this.pollsize
91
+ };
92
+ }
93
+ };
94
+
95
+ // Example 3: Wuying Proxy - Restricted Strategy
96
+ // Uses fixed proxy nodes, suitable for scenarios requiring stable IP
97
+ // const browserProxy: BrowserProxy = {
98
+ // type: 'wuying',
99
+ // strategy: 'restricted',
100
+ // toMap: function() {
101
+ // return {
102
+ // type: this.type,
103
+ // strategy: this.strategy
104
+ // };
105
+ // }
106
+ // };
107
+
108
+ // Create browser option with proxy configuration, now only support one proxy
109
+ const browserOption: BrowserOption = {
110
+ proxies: [browserProxy]
111
+ };
112
+
113
+ const initialized = await session.browser.initializeAsync(browserOption);
114
+ if (initialized) {
115
+ const endpointUrl = await session.browser.getEndpointUrl();
116
+ console.log('endpoint_url =', endpointUrl);
117
+
118
+ const browser = await chromium.connectOverCDP(endpointUrl);
119
+ const context = browser.contexts()[0];
120
+ const page = await context.newPage();
121
+
122
+ try {
123
+ // ==================== Verify Proxy IP ====================
124
+ console.log('\n--- Check proxy public IP start ---');
125
+ await page.goto('https://httpbin.org/ip');
126
+
127
+ const response = await page.evaluate((): IpResponse => {
128
+ return JSON.parse(document.body.textContent || '{}');
129
+ });
130
+ const publicIp = response.origin || '';
131
+ console.log('proxy public IP:', publicIp);
132
+ console.log('--- Check proxy public IP end ---');
133
+
134
+ await page.waitForTimeout(3000);
135
+ } finally {
136
+ await browser.close();
137
+ }
138
+ }
139
+
140
+ // Clean up session
141
+ await agentBay.delete(session);
142
+ } catch (error) {
143
+ console.error('Error:', error);
144
+ }
145
+ }
146
+
147
+ if (require.main === module) {
148
+ main().catch(console.error);
149
+ }
@@ -0,0 +1,266 @@
1
+ // @ts-nocheck
2
+ /**
3
+ * Browser Type Selection Example
4
+ *
5
+ * This example demonstrates how to select between Chrome and Chromium browsers
6
+ * when using computer use images in AgentBay.
7
+ *
8
+ * Features demonstrated:
9
+ * - Chrome browser selection
10
+ * - Chromium browser selection
11
+ * - Default browser (undefined)
12
+ * - Browser type verification
13
+ * - Configuration comparison
14
+ *
15
+ * Note: The browserType option is only available for computer use images.
16
+ */
17
+
18
+ import { AgentBay, CreateSessionParams, BrowserOption } from 'wuying-agentbay-sdk';
19
+ import { chromium } from 'playwright';
20
+
21
+ /**
22
+ * Test a specific browser type configuration
23
+ */
24
+ async function testBrowserType(
25
+ browserType: 'chrome' | 'chromium' | undefined,
26
+ description: string
27
+ ): Promise<void> {
28
+ console.log('\n' + '='.repeat(60));
29
+ console.log(`Testing: ${description}`);
30
+ console.log('='.repeat(60));
31
+
32
+ const apiKey = process.env.AGENTBAY_API_KEY;
33
+ if (!apiKey) {
34
+ throw new Error('AGENTBAY_API_KEY environment variable not set');
35
+ }
36
+
37
+ const agentBay = new AgentBay({ apiKey });
38
+
39
+ // Create session with computer use image
40
+ console.log('\n1. Creating session with computer use image...');
41
+ const params: CreateSessionParams = { imageId: 'browser_latest' };
42
+ const result = await agentBay.create(params);
43
+
44
+ if (!result.success || !result.session) {
45
+ throw new Error('Failed to create session');
46
+ }
47
+
48
+ const session = result.session;
49
+ console.log(` ✓ Session created: ${session.getSessionId()}`);
50
+
51
+ try {
52
+ // Initialize browser with specified type
53
+ console.log(`\n2. Initializing browser with type: ${browserType || 'default (undefined)'}...`);
54
+
55
+ // Using plain object (recommended)
56
+ const option: BrowserOption = {
57
+ browserType: browserType,
58
+ viewport: { width: 1920, height: 1080 }
59
+ };
60
+
61
+ const success = await session.browser.initializeAsync(option);
62
+ if (!success) {
63
+ throw new Error('Browser initialization failed');
64
+ }
65
+
66
+ console.log(' ✓ Browser initialized successfully');
67
+
68
+ // Get endpoint URL
69
+ const endpointUrl = session.browser.getEndpointUrl();
70
+ console.log(`\n3. CDP endpoint: ${String(endpointUrl).substring(0, 50)}...`);
71
+
72
+ // Connect Playwright and verify browser
73
+ console.log('\n4. Connecting to browser via CDP...');
74
+ const browser = await chromium.connectOverCDP(endpointUrl);
75
+ const context = browser.contexts()[0];
76
+ const page = await context.newPage();
77
+
78
+ console.log(' ✓ Connected successfully');
79
+ console.log('\n5. Verifying browser configuration...');
80
+
81
+ // Navigate to a page that shows browser info
82
+ await page.goto('https://www.whatismybrowser.com/');
83
+ await page.waitForLoadState('networkidle');
84
+
85
+ // Get browser information
86
+ const userAgent = await page.evaluate(() => (navigator as any).userAgent);
87
+ const viewportWidth = await page.evaluate(() => (window as any).innerWidth);
88
+ const viewportHeight = await page.evaluate(() => (window as any).innerHeight);
89
+
90
+ console.log('\n Browser Information:');
91
+ console.log(` - User Agent: ${userAgent.substring(0, 80)}...`);
92
+ console.log(` - Viewport: ${viewportWidth} x ${viewportHeight}`);
93
+ console.log(` - Configured Type: ${browserType || 'default'}`);
94
+
95
+ // Check if Chrome or Chromium is in user agent
96
+ if (userAgent.includes('Chrome')) {
97
+ const detected = userAgent.includes('Chromium') ? 'Chromium' : 'Chrome';
98
+ console.log(` - Detected Browser: ${detected}`);
99
+ }
100
+
101
+ await browser.close();
102
+
103
+ console.log(`\n ✓ Test completed successfully for ${description}`);
104
+
105
+ } finally {
106
+ console.log('\n6. Cleaning up...');
107
+ session.delete();
108
+ console.log(' ✓ Session deleted');
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Main function to run all browser type examples
114
+ */
115
+ async function main(): Promise<void> {
116
+ console.log('Browser Type Selection Example');
117
+ console.log('='.repeat(60));
118
+ console.log('\nThis example demonstrates browser type selection in AgentBay.');
119
+ console.log('Note: browserType is only available for computer use images.');
120
+
121
+ // Test 1: Chrome browser
122
+ await testBrowserType('chrome', 'Chrome Browser (Google Chrome)');
123
+
124
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Brief pause
125
+
126
+ // Test 2: Chromium browser
127
+ await testBrowserType('chromium', 'Chromium Browser (Open Source)');
128
+
129
+ await new Promise(resolve => setTimeout(resolve, 2000)); // Brief pause
130
+
131
+ // Test 3: Default (undefined)
132
+ await testBrowserType(undefined, 'Default Browser (Platform decides)');
133
+
134
+ console.log('\n' + '='.repeat(60));
135
+ console.log('All browser type tests completed successfully!');
136
+ console.log('='.repeat(60));
137
+
138
+ // Summary
139
+ console.log('\nSummary:');
140
+ console.log('- Chrome: Use when you need Google Chrome specific features');
141
+ console.log('- Chromium: Use for open-source, lighter resource usage');
142
+ console.log('- Default (undefined): Let the platform choose the optimal browser');
143
+ console.log('\nBest Practice: Use undefined unless you have a specific requirement');
144
+ }
145
+
146
+ /**
147
+ * Quick example showing the most common usage
148
+ */
149
+ async function quickExample(): Promise<void> {
150
+ console.log('\n' + '='.repeat(60));
151
+ console.log('Quick Example: Using Chrome Browser');
152
+ console.log('='.repeat(60));
153
+
154
+ const apiKey = process.env.AGENTBAY_API_KEY;
155
+ if (!apiKey) {
156
+ throw new Error('AGENTBAY_API_KEY not set');
157
+ }
158
+
159
+ const agentBay = new AgentBay({ apiKey });
160
+
161
+ // Create session
162
+ const params: CreateSessionParams = { imageId: 'browser_latest' };
163
+ const result = await agentBay.create(params);
164
+ if (!result.success || !result.session) {
165
+ throw new Error('Failed to create session');
166
+ }
167
+
168
+ const session = result.session;
169
+
170
+ try {
171
+ // Simply specify browserType in BrowserOption
172
+ const option: BrowserOption = {
173
+ browserType: 'chrome'
174
+ };
175
+
176
+ const success = await session.browser.initializeAsync(option);
177
+
178
+ if (success) {
179
+ console.log('✓ Chrome browser initialized successfully');
180
+
181
+ // Get endpoint and use with Playwright
182
+ const endpointUrl = session.browser.getEndpointUrl();
183
+ const browser = await chromium.connectOverCDP(endpointUrl);
184
+ const page = await browser.contexts()[0].newPage();
185
+
186
+ await page.goto('https://example.com');
187
+ const title = await page.title();
188
+ console.log(`✓ Page title: ${title}`);
189
+
190
+ await browser.close();
191
+ }
192
+ } finally {
193
+ session.delete();
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Type-safe example showing all options
199
+ */
200
+ async function typeSafeExample(): Promise<void> {
201
+ console.log('\n' + '='.repeat(60));
202
+ console.log('Type-Safe Example: Using TypeScript Types');
203
+ console.log('='.repeat(60));
204
+
205
+ const apiKey = process.env.AGENTBAY_API_KEY;
206
+ if (!apiKey) {
207
+ throw new Error('AGENTBAY_API_KEY not set');
208
+ }
209
+
210
+ const agentBay = new AgentBay({ apiKey });
211
+ const params: CreateSessionParams = { imageId: 'browser_latest' };
212
+ const result = await agentBay.create(params);
213
+
214
+ if (!result.success || !result.session) {
215
+ throw new Error('Failed to create session');
216
+ }
217
+
218
+ const session = result.session;
219
+
220
+ try {
221
+ // TypeScript ensures type safety
222
+ const browserTypes: Array<'chrome' | 'chromium' | undefined> = [
223
+ 'chrome',
224
+ 'chromium',
225
+ undefined
226
+ ];
227
+
228
+ for (const type of browserTypes) {
229
+ console.log(`\nTesting with type: ${type || 'undefined'}`);
230
+
231
+ // Type-safe option creation
232
+ const option: BrowserOption = {
233
+ browserType: type,
234
+ viewport: { width: 1920, height: 1080 }
235
+ };
236
+
237
+ const success = await session.browser.initializeAsync(option);
238
+ console.log(` ✓ Initialization: ${success ? 'Success' : 'Failed'}`);
239
+
240
+ if (success) {
241
+ // Verify configuration
242
+ const currentOption = session.browser.getOption();
243
+ if (currentOption) {
244
+ console.log(` ✓ Configured type: ${currentOption.browserType || 'undefined'}`);
245
+ }
246
+ }
247
+
248
+ // Brief pause between iterations
249
+ await new Promise(resolve => setTimeout(resolve, 1000));
250
+ }
251
+
252
+ console.log('\n✓ Type-safe example completed');
253
+
254
+ } finally {
255
+ session.delete();
256
+ }
257
+ }
258
+
259
+ // Run the main example
260
+ main()
261
+ .then(() => process.exit(0))
262
+ .catch(error => {
263
+ console.error('Error:', error.message);
264
+ process.exit(1);
265
+ });
266
+