-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathBrowserAgentServer.js
More file actions
1545 lines (1362 loc) · 45 KB
/
BrowserAgentServer.js
File metadata and controls
1545 lines (1362 loc) · 45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2025 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import { EventEmitter } from 'events';
import { v4 as uuidv4 } from 'uuid';
import { WebSocketServer } from 'ws';
import { ClientManager } from '../client-manager.js';
import { CONFIG, validateConfig } from '../config.js';
import logger, { logConnection, logRequest } from '../logger.js';
import { RpcClient } from '../rpc-client.js';
/**
* BrowserAgentServer - OpenAI-compatible HTTP API wrapper for Browser Operator
*
* Example usage:
* ```js
* const server = new BrowserAgentServer({
* authKey: 'your-secret-key',
* host: '127.0.0.1',
* port: 8080
* });
*
* server.onConnect(client => {
* console.log(`Client connected: ${client.id}`);
*
* client.execute({
* id: "test_request",
* name: "Bloomberg Task",
* description: "Navigate to Bloomberg and summarize latest news",
* input: {
* objective: "Navigate to Bloomberg, summarize and return sentiment of the latest news."
* }
* }).then(response => {
* console.log('Request response:', response);
* });
* });
*
* server.start();
* ```
*/
export class BrowserAgentServer extends EventEmitter {
constructor(options = {}) {
super();
// Apply configuration options
this.config = {
host: options.host || CONFIG.server.host,
port: options.port || CONFIG.server.port,
authKey: options.authKey || null,
clientsDir: options.clientsDir || './clients',
...options
};
// Internal state
this.connectedClients = new Map();
this.clientManager = new ClientManager(this.config.clientsDir);
this.judge = null; // Judge is optional - can be set later
this.wss = null;
this.isRunning = false;
// Bind methods
this.handleConnection = this.handleConnection.bind(this);
}
/**
* Start the browser agent server
*/
async start() {
if (this.isRunning) {
throw new Error('Server is already running');
}
// Validate configuration - only require LLM if judge is configured
const configErrors = validateConfig(!!this.judge);
if (configErrors.length > 0) {
throw new Error(`Configuration errors: ${configErrors.join(', ')}`);
}
// Create WebSocket server
this.wss = new WebSocketServer({
port: this.config.port,
host: this.config.host
});
this.wss.on('connection', this.handleConnection);
this.wss.on('error', error => {
logger.error('WebSocket server error', { error: error.message });
this.emit('error', error);
});
this.isRunning = true;
logger.info(`Browser agent server started on ws://${this.config.host}:${this.config.port}`);
this.emit('started', { host: this.config.host, port: this.config.port });
return this;
}
/**
* Stop the browser agent server
*/
async stop() {
if (!this.isRunning) {
return;
}
if (this.wss) {
this.wss.close();
this.wss = null;
}
// Close all client connections
for (const [clientId, connection] of this.connectedClients) {
connection.rpcClient.cleanup();
if (connection.ws.readyState === connection.ws.OPEN) {
connection.ws.close();
}
}
this.connectedClients.clear();
this.isRunning = false;
logger.info('Browser agent server stopped');
this.emit('stopped');
}
/**
* Register a callback for when clients connect
* @param {Function} callback - Called with a ClientProxy instance
*/
onConnect(callback) {
this.on('clientConnected', callback);
return this;
}
/**
* Register a callback for when clients disconnect
* @param {Function} callback - Called with client info
*/
onDisconnect(callback) {
this.on('clientDisconnected', callback);
return this;
}
/**
* Set the judge for request validation (optional)
* @param {Judge} judge - Judge instance for request validation
*/
setJudge(judge) {
// If server is already running, validate LLM config when setting judge
if (this.isRunning) {
const configErrors = validateConfig(true);
if (configErrors.length > 0) {
throw new Error(`Cannot set judge: ${configErrors.join(', ')}`);
}
}
this.judge = judge;
return this;
}
/**
* Get current server status
*/
getStatus() {
const connections = Array.from(this.connectedClients.values());
const readyClients = connections.filter(client => client.ready).length;
const uniqueBaseClients = new Set(connections.map(c => c.baseClientId).filter(Boolean)).size;
return {
isRunning: this.isRunning,
connectedClients: this.connectedClients.size,
uniqueBaseClients: uniqueBaseClients,
totalTabs: this.clientManager.getTotalTabCount(),
readyClients: readyClients,
host: this.config.host,
port: this.config.port
};
}
/**
* Get the client manager instance
*/
getClientManager() {
return this.clientManager;
}
/**
* Handle new WebSocket connections
*/
handleConnection(ws, request) {
const connectionId = uuidv4();
const connection = {
id: connectionId,
ws,
rpcClient: new RpcClient(),
connectedAt: new Date().toISOString(),
remoteAddress: request.socket.remoteAddress,
registered: false,
clientId: null
};
this.connectedClients.set(connectionId, connection);
logConnection({
event: 'connected',
connectionId,
remoteAddress: connection.remoteAddress,
totalConnections: this.connectedClients.size
});
ws.on('message', message => {
this.handleMessage(connection, message);
});
ws.on('close', () => {
this.handleDisconnection(connection);
});
ws.on('error', error => {
logger.error('WebSocket connection error', {
connectionId: connection.id,
clientId: connection.clientId,
error: error.message
});
});
// Send welcome message
this.sendMessage(ws, {
type: 'welcome',
serverId: 'server-001',
version: '1.0.0',
timestamp: new Date().toISOString()
});
}
/**
* Handle incoming messages from clients
*/
async handleMessage(connection, message) {
try {
const data = JSON.parse(message);
// Handle RPC responses
if (data.jsonrpc === '2.0' && (data.result || data.error) && data.id) {
if (connection.rpcClient.handleResponse(message)) {
return;
}
logger.debug('RPC response could not be handled', {
connectionId: connection.id,
clientId: connection.clientId,
id: data.id
});
return;
}
// Handle RPC requests from client to server
if (data.jsonrpc === '2.0' && data.method && data.id) {
await this.handleRpcRequest(connection, data);
return;
}
// Handle other message types
switch (data.type) {
case 'register':
await this.handleRegistration(connection, data);
break;
case 'ping':
this.sendMessage(connection.ws, {
type: 'pong',
timestamp: new Date().toISOString()
});
break;
case 'ready':
if (!connection.registered) {
logger.warn('Received ready signal from unregistered client', {
connectionId: connection.id
});
return;
}
connection.ready = true;
logger.info('Client ready for requests', {
clientId: connection.clientId
});
// Create client proxy and emit connection event
const clientProxy = new ClientProxy(connection, this);
this.emit('clientConnected', clientProxy);
break;
case 'status':
this.handleStatusUpdate(connection, data);
break;
case 'auth_verify':
this.handleAuthVerification(connection, data);
break;
default:
logger.warn('Unknown message type', {
connectionId: connection.id,
clientId: connection.clientId,
type: data.type
});
}
} catch (error) {
logger.warn('Failed to parse message', {
connectionId: connection.id,
error: error.message
});
}
}
/**
* Handle RPC requests from client to server
*/
async handleRpcRequest(connection, request) {
try {
const { method, params, id } = request;
logger.info('Received RPC request', {
connectionId: connection.id,
clientId: connection.clientId,
method,
requestId: id
});
let result = null;
switch (method) {
case 'configure_llm':
result = await this.handleConfigureLLM(connection, params);
break;
default:
// JSON-RPC: Method not found
this.sendMessage(connection.ws, {
jsonrpc: '2.0',
error: {
code: -32601,
message: `Method not found: ${method}`
},
id
});
return;
}
// Send success response
this.sendMessage(connection.ws, {
jsonrpc: '2.0',
result,
id
});
} catch (error) {
logger.error('RPC request failed', {
connectionId: connection.id,
clientId: connection.clientId,
method: request.method,
requestId: request.id,
error: error.message
});
// Send error response
this.sendMessage(connection.ws, {
jsonrpc: '2.0',
error: {
code: -32603, // Internal error
message: error.message
},
id: request.id
});
}
}
/**
* Handle configure_llm RPC method
*/
async handleConfigureLLM(connection, params) {
if (!connection.registered) {
throw new Error('Client must be registered before configuring LLM');
}
const { provider, apiKey, endpoint, models, partial = false } = params;
// Validate inputs
const supportedProviders = ['openai', 'litellm', 'groq', 'openrouter'];
if (partial) {
// For partial updates, validate only provided fields
if (provider && !supportedProviders.includes(provider)) {
throw new Error(`Unsupported provider: ${provider}. Supported providers: ${supportedProviders.join(', ')}`);
}
if (models && models.main === '') {
throw new Error('Main model cannot be empty');
}
} else {
// For full updates, require provider and main model
if (!provider || !supportedProviders.includes(provider)) {
throw new Error(`Unsupported or missing provider: ${provider ?? '(none)'}. Supported providers: ${supportedProviders.join(', ')}`);
}
if (!models || !models.main) {
throw new Error('Main model is required');
}
}
// Store configuration for this client connection
if (!connection.llmConfig) {
connection.llmConfig = {};
}
// Apply configuration (full or partial update)
if (partial && connection.llmConfig) {
// Partial update - merge with existing config
connection.llmConfig = {
...connection.llmConfig,
provider: provider || connection.llmConfig.provider,
apiKey: apiKey || connection.llmConfig.apiKey,
endpoint: endpoint || connection.llmConfig.endpoint,
models: {
...connection.llmConfig.models,
...models
}
};
} else {
// Full update - replace entire config
connection.llmConfig = {
provider,
apiKey: apiKey || CONFIG.providers[provider]?.apiKey,
endpoint: endpoint || CONFIG.providers[provider]?.endpoint,
models: {
main: models.main,
mini: models.mini || models.main,
nano: models.nano || models.mini || models.main
}
};
}
logger.info('LLM configuration updated', {
clientId: connection.clientId,
provider: connection.llmConfig.provider,
models: connection.llmConfig.models,
hasApiKey: !!connection.llmConfig.apiKey,
hasEndpoint: !!connection.llmConfig.endpoint
});
return {
status: 'success',
message: 'LLM configuration updated successfully',
appliedConfig: {
provider: connection.llmConfig.provider,
models: connection.llmConfig.models
}
};
}
/**
* Handle client registration
*/
async handleRegistration(connection, data) {
try {
const { clientId, secretKey, capabilities } = data;
const { baseClientId, tabId, isComposite } = this.clientManager.parseCompositeClientId(clientId);
logger.info('Registration attempt', {
clientId,
baseClientId,
tabId: tabId || 'default',
isComposite,
hasSecretKey: !!secretKey
});
// Check if base client exists
const validation = this.clientManager.validateClient(baseClientId, null, true);
if (!validation.valid) {
if (validation.reason === 'Client not found') {
// Auto-create new client configuration
try {
logger.info('Auto-creating new client configuration', { baseClientId, clientId });
await this.clientManager.createClientWithId(baseClientId, `DevTools Client ${baseClientId.substring(0, 8)}`, 'hello');
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'rejected',
reason: 'New client created. Please reconnect to complete registration.',
newClient: true
});
return;
} catch (error) {
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'rejected',
reason: `Failed to create client configuration: ${error.message}`
});
return;
}
} else {
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'rejected',
reason: validation.reason
});
return;
}
}
// Get client info
const client = this.clientManager.getClient(baseClientId);
if (!client) {
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'rejected',
reason: 'Client configuration not found'
});
return;
}
// Send server's secret key to client for verification
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'auth_required',
serverSecretKey: client.secretKey || '',
message: 'Please verify secret key'
});
connection.clientId = clientId;
connection.capabilities = capabilities;
connection.awaitingAuth = true;
} catch (error) {
logger.error('Registration error', { error: error.message });
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId: data.clientId,
status: 'rejected',
reason: error.message
});
}
}
/**
* Handle auth verification
*/
handleAuthVerification(connection, data) {
if (!connection.awaitingAuth) {
return;
}
const { clientId, verified } = data;
if (verified) {
const { baseClientId, tabId, isComposite } = this.clientManager.parseCompositeClientId(clientId);
const result = this.clientManager.registerClient(baseClientId, '', connection.capabilities, true);
connection.registered = true;
connection.awaitingAuth = false;
connection.compositeClientId = clientId;
connection.baseClientId = baseClientId;
connection.tabId = tabId;
// Register tab with client manager
this.clientManager.registerTab(clientId, connection, {
remoteAddress: connection.remoteAddress,
userAgent: connection.userAgent || 'unknown'
});
// Move connection to use composite clientId as key
this.connectedClients.delete(connection.id);
this.connectedClients.set(clientId, connection);
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'accepted',
message: result.clientName ? `Welcome ${result.clientName}` : 'Client authenticated successfully',
requestsCount: result.requestsCount,
tabId: tabId,
isComposite: isComposite
});
logger.info('Client authenticated and registered', {
clientId,
baseClientId,
tabId: tabId || 'default',
isComposite
});
} else {
this.sendMessage(connection.ws, {
type: 'registration_ack',
clientId,
status: 'rejected',
reason: 'Secret key verification failed'
});
connection.ws.close(1008, 'Authentication failed');
}
}
/**
* Handle status updates
*/
handleStatusUpdate(connection, data) {
if (!connection.registered) return;
const { requestId, status, progress, message } = data;
logger.info('Request status update', {
clientId: connection.clientId,
requestId,
status,
progress,
message
});
}
/**
* Handle client disconnection and cleanup stale tab references
*/
handleDisconnection(connection) {
connection.rpcClient.cleanup();
// Clean up stale tab references
if (connection.registered && connection.compositeClientId) {
this.clientManager.unregisterTab(connection.compositeClientId);
this.connectedClients.delete(connection.compositeClientId);
// Additional cleanup: ensure tab is removed from activeTabs
const { baseClientId } = this.clientManager.parseCompositeClientId(connection.compositeClientId);
this.clientManager.cleanupStaleTab(baseClientId, connection.tabId);
} else if (connection.clientId) {
this.connectedClients.delete(connection.clientId);
} else {
this.connectedClients.delete(connection.id);
}
logConnection({
event: 'disconnected',
connectionId: connection.id,
clientId: connection.compositeClientId || connection.clientId,
baseClientId: connection.baseClientId,
tabId: connection.tabId,
totalConnections: this.connectedClients.size
});
this.emit('clientDisconnected', {
clientId: connection.compositeClientId || connection.clientId,
baseClientId: connection.baseClientId,
tabId: connection.tabId
});
}
/**
* Send message to WebSocket client
*/
sendMessage(ws, data) {
if (ws.readyState === ws.OPEN) {
try {
ws.send(JSON.stringify(data));
} catch (error) {
logger.error('Failed to send WebSocket message', {
error: error.message,
messageType: data.type
});
}
} else {
logger.warn('Cannot send message, WebSocket not open', {
readyState: ws.readyState,
messageType: data.type
});
}
}
/**
* Execute request on a specific client
*/
async executeRequest(connection, request) {
const startTime = Date.now();
const rpcId = `rpc-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
try {
logger.info('Starting request', {
clientId: connection.clientId,
requestId: request.id,
tool: request.tool
});
// Prepare model configuration - use client config if available, otherwise request config, otherwise defaults
let modelConfig = request.model || {};
if (connection.llmConfig) {
// New nested format: separate config objects for each model tier
modelConfig = {
main_model: {
provider: connection.llmConfig.provider,
model: connection.llmConfig.models.main,
api_key: connection.llmConfig.apiKey,
endpoint: connection.llmConfig.endpoint
},
mini_model: {
provider: connection.llmConfig.provider,
model: connection.llmConfig.models.mini,
api_key: connection.llmConfig.apiKey,
endpoint: connection.llmConfig.endpoint
},
nano_model: {
provider: connection.llmConfig.provider,
model: connection.llmConfig.models.nano,
api_key: connection.llmConfig.apiKey,
endpoint: connection.llmConfig.endpoint
},
// Include any request-specific overrides
...modelConfig
};
}
// Prepare RPC request
const rpcRequest = {
jsonrpc: '2.0',
method: 'evaluate',
params: {
requestId: request.id,
name: request.name,
url: request.target?.url || request.url,
tool: request.tool,
input: request.input,
model: modelConfig,
timeout: request.timeout || 30000,
metadata: {
tags: request.metadata?.tags || [],
retries: request.settings?.retry_policy?.max_retries || 0
}
},
id: rpcId
};
// Send RPC request
const response = await connection.rpcClient.callMethod(
connection.ws,
'evaluate',
rpcRequest.params,
request.timeout || 45000
);
// Log request
logRequest({
requestId: request.id,
clientId: connection.clientId,
name: request.name,
tool: request.tool,
response,
timestamp: new Date().toISOString(),
duration: Date.now() - startTime
});
return response;
} catch (error) {
logger.error('Request failed', {
clientId: connection.clientId,
requestId: request.id,
error: error.message
});
throw error;
}
}
/**
* Get the browser-level CDP WebSocket endpoint
* @returns {Promise<string>} WebSocket URL
*/
async getCDPBrowserEndpoint() {
try {
const path = '/json/version';
logger.info('Attempting to connect to CDP', {
host: CONFIG.cdp.host,
port: CONFIG.cdp.port,
path
});
// When connecting via host.docker.internal, we need to set Host header to localhost
// because Chrome only accepts CDP requests with localhost/127.0.0.1 in the Host header
const headers = {};
if (CONFIG.cdp.host === 'host.docker.internal') {
headers['Host'] = `localhost:${CONFIG.cdp.port}`;
logger.info('Using Host header override for host.docker.internal', headers);
}
const options = {
hostname: CONFIG.cdp.host,
port: CONFIG.cdp.port,
path: path,
method: 'GET',
headers: headers
};
const http = await import('http');
return new Promise((resolve, reject) => {
const req = http.default.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const jsonData = JSON.parse(data);
let wsUrl = jsonData.webSocketDebuggerUrl;
// Replace localhost with host.docker.internal when running in Docker
if (CONFIG.cdp.host === 'host.docker.internal' && wsUrl) {
wsUrl = wsUrl.replace('ws://localhost:', 'ws://host.docker.internal:');
wsUrl = wsUrl.replace('ws://127.0.0.1:', 'ws://host.docker.internal:');
logger.info('Rewrote WebSocket URL for Docker', { original: jsonData.webSocketDebuggerUrl, rewritten: wsUrl });
}
resolve(wsUrl);
} catch (parseError) {
logger.error('Failed to parse CDP response', { error: parseError.message, data });
reject(new Error('Failed to connect to Chrome DevTools Protocol'));
}
});
});
req.on('error', (error) => {
logger.error('Failed to get CDP browser endpoint', { error: error.message });
reject(new Error('Failed to connect to Chrome DevTools Protocol'));
});
req.end();
});
} catch (error) {
logger.error('Failed to get CDP browser endpoint', { error: error.message });
throw new Error('Failed to connect to Chrome DevTools Protocol');
}
}
/**
* Send a CDP command via WebSocket
* @param {string} method - CDP method name
* @param {Object} params - CDP method parameters
* @returns {Promise<Object>} CDP response
*/
async sendCDPCommand(method, params = {}) {
return new Promise(async (resolve, reject) => {
try {
const { default: WebSocket } = await import('ws');
const cdpEndpoint = await this.getCDPBrowserEndpoint();
const ws = new WebSocket(cdpEndpoint);
// Use a simple counter for CDP message IDs (must be a reasonable integer)
const id = Math.floor(Math.random() * 1000000);
const timeout = setTimeout(() => {
ws.close();
reject(new Error(`CDP command timeout: ${method}`));
}, 10000);
ws.on('open', () => {
const message = JSON.stringify({
id,
method,
params
});
logger.info('CDP WebSocket opened, sending command', { method, params, cdpEndpoint });
ws.send(message);
});
ws.on('message', (data) => {
try {
const response = JSON.parse(data.toString());
logger.info('CDP WebSocket message received', {
method,
responseId: response.id,
expectedId: id,
hasResult: !!response.result,
hasError: !!response.error,
fullResponse: JSON.stringify(response)
});
if (response.id === id) {
clearTimeout(timeout);
ws.close();
if (response.error) {
logger.error('CDP command error', { method, error: response.error });
reject(new Error(`CDP error: ${response.error.message}`));
} else {
logger.info('CDP command success', { method, result: response.result });
resolve(response.result);
}
} else {
logger.warn('CDP message ID mismatch', {
method,
receivedId: response.id,
expectedId: id,
responseType: response.method ? 'event' : 'response'
});
}
} catch (error) {
clearTimeout(timeout);
ws.close();
logger.error('CDP message parse error', { error: error.message });
reject(error);
}
});
ws.on('error', (error) => {
clearTimeout(timeout);
logger.error('CDP WebSocket error', { error: error.message });
reject(error);
});
} catch (error) {
reject(error);
}
});
}
/**
* Send a CDP command to a specific target (tab)
* This requires attaching to the target first, then detaching after
* @param {string} targetId - Target ID (tab ID)
* @param {string} method - CDP method name
* @param {Object} params - CDP method parameters
* @returns {Promise<Object>} CDP response
*/
async sendCDPCommandToTarget(targetId, method, params = {}) {
return new Promise(async (resolve, reject) => {
try {
const { default: WebSocket } = await import('ws');
const cdpEndpoint = await this.getCDPBrowserEndpoint();
const ws = new WebSocket(cdpEndpoint);
let sessionId = null;
const attachId = Math.floor(Math.random() * 1000000);
const commandId = Math.floor(Math.random() * 1000000);
const timeout = setTimeout(() => {
ws.close();
reject(new Error(`CDP target command timeout: ${method} on ${targetId}`));
}, 15000);
ws.on('open', () => {
// First, attach to the target
const attachMessage = JSON.stringify({
id: attachId,
method: 'Target.attachToTarget',
params: {
targetId,
flatten: true
}
});
logger.info('CDP attaching to target', { targetId, method });
ws.send(attachMessage);
});
ws.on('message', (data) => {
try {
const response = JSON.parse(data.toString());
// Handle attach response
if (response.id === attachId) {
if (response.error) {
clearTimeout(timeout);
ws.close();
logger.error('CDP attach error', { targetId, error: response.error });
reject(new Error(`CDP attach error: ${response.error.message}`));
return;
}
sessionId = response.result.sessionId;
logger.info('CDP attached to target, sending command', { sessionId, method });
// Now send the actual command with the session ID
const commandMessage = JSON.stringify({
id: commandId,
method,
params,
sessionId
});
ws.send(commandMessage);
}
// Handle command response
else if (response.id === commandId) {
clearTimeout(timeout);
if (response.error) {
logger.error('CDP target command error', { method, targetId, error: response.error });
ws.close();
reject(new Error(`CDP error: ${response.error.message}`));
} else {
logger.info('CDP target command success', { method, targetId });
ws.close();
resolve(response.result);
}
}
// Ignore other messages (events, etc.)