-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathclient.ts
More file actions
190 lines (167 loc) · 4.82 KB
/
client.ts
File metadata and controls
190 lines (167 loc) · 4.82 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
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import {spawn} from 'node:child_process';
import fs from 'node:fs';
import net from 'node:net';
import {logger} from '../logger.js';
import type {CallToolResult} from '../third_party/index.js';
import {PipeTransport} from '../third_party/index.js';
import {getTempFilePath} from '../utils/files.js';
import type {DaemonMessage, DaemonResponse} from './types.js';
import {
DAEMON_SCRIPT_PATH,
getSocketPath,
getPidFilePath,
isDaemonRunning,
} from './utils.js';
const FILE_TIMEOUT = 10_000;
/**
* Waits for a file to be created and populated (removed = false) or removed (removed = true).
*/
function waitForFile(filePath: string, removed = false) {
return new Promise<void>((resolve, reject) => {
const check = () => {
const exists = fs.existsSync(filePath);
if (removed) {
return !exists;
}
if (!exists) {
return false;
}
try {
return fs.statSync(filePath).size > 0;
} catch {
return false;
}
};
if (check()) {
resolve();
return;
}
const timer = setTimeout(() => {
fs.unwatchFile(filePath);
reject(
new Error(
`Timeout: file ${filePath} ${removed ? 'not removed' : 'not found'} within ${FILE_TIMEOUT}ms`,
),
);
}, FILE_TIMEOUT);
fs.watchFile(filePath, {interval: 500}, () => {
if (check()) {
clearTimeout(timer);
fs.unwatchFile(filePath);
resolve();
}
});
});
}
export async function startDaemon(mcpArgs: string[] = [], sessionId: string) {
if (isDaemonRunning(sessionId)) {
logger('Daemon is already running');
return;
}
const pidFilePath = getPidFilePath(sessionId);
if (fs.existsSync(pidFilePath)) {
fs.unlinkSync(pidFilePath);
}
logger('Starting daemon...', ...mcpArgs);
const child = spawn(process.execPath, [DAEMON_SCRIPT_PATH, ...mcpArgs], {
detached: true,
stdio: 'ignore',
env: {...process.env, CHROME_DEVTOOLS_MCP_SESSION_ID: sessionId},
cwd: process.cwd(),
windowsHide: true,
});
child.unref();
await waitForFile(pidFilePath);
}
const SEND_COMMAND_TIMEOUT = 60_000; // ms
/**
* `sendCommand` opens a socket connection sends a single command and disconnects.
*/
export async function sendCommand(
command: DaemonMessage,
sessionId: string,
): Promise<DaemonResponse> {
const socketPath = getSocketPath(sessionId);
const socket = net.createConnection({
path: socketPath,
});
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
socket.destroy();
reject(new Error('Timeout waiting for daemon response'));
}, SEND_COMMAND_TIMEOUT);
const transport = new PipeTransport(socket, socket);
transport.onmessage = async (message: string) => {
clearTimeout(timer);
logger('onmessage', message);
resolve(JSON.parse(message));
};
socket.on('error', error => {
clearTimeout(timer);
logger('Socket error:', error);
reject(error);
});
socket.on('close', () => {
clearTimeout(timer);
logger('Socket closed:');
reject(new Error('Socket closed'));
});
logger('Sending message', command);
transport.send(JSON.stringify(command));
});
}
export async function stopDaemon(sessionId: string) {
if (!isDaemonRunning(sessionId)) {
logger('Daemon is not running');
return;
}
const pidFilePath = getPidFilePath(sessionId);
await sendCommand({method: 'stop'}, sessionId);
await waitForFile(pidFilePath, /*removed=*/ true);
}
export async function handleResponse(
response: CallToolResult,
format: 'json' | 'md',
): Promise<string> {
if (response.isError) {
return JSON.stringify(response.content);
}
if (format === 'json') {
if (response.structuredContent) {
return JSON.stringify(response.structuredContent);
}
// Fall-through to text for backward compatibility.
}
const chunks = [];
for (const content of response.content) {
if (content.type === 'text') {
chunks.push(content.text);
} else if (content.type === 'image') {
const imageData = content.data;
const mimeType = content.mimeType;
let extension = '.png';
switch (mimeType) {
case 'image/jpg':
case 'image/jpeg':
extension = '.jpeg';
break;
case 'image/webp':
extension = '.webp';
break;
}
const data = Buffer.from(imageData, 'base64');
const name = crypto.randomUUID();
const filepath = await getTempFilePath(`${name}${extension}`);
fs.writeFileSync(filepath, data);
chunks.push(`Saved to ${filepath}.`);
} else {
throw new Error('Not supported response content type');
}
}
return format === 'md' ? chunks.join(' ') : JSON.stringify(chunks);
}