chrome-devtools-mcp 1.8.0 → 1.10.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 (72) hide show
  1. package/README.md +20 -908
  2. package/build/src/BrowserManager.js +401 -0
  3. package/build/src/McpContext.js +43 -26
  4. package/build/src/McpPage.js +112 -4
  5. package/build/src/McpResponse.js +68 -3
  6. package/build/src/ToolHandler.js +184 -160
  7. package/build/src/bin/chrome-devtools-mcp-main.js +12 -7
  8. package/build/src/bin/chrome-devtools.js +6 -12
  9. package/build/src/collectors/PageCollector.js +66 -3
  10. package/build/src/config/browser-options.js +125 -0
  11. package/build/src/config/category-options.js +89 -0
  12. package/build/src/config/cli-commands.js +26 -0
  13. package/build/src/config/cli-options.js +34 -2
  14. package/build/src/config/mcp-options.js +86 -147
  15. package/build/src/daemon/utils.js +6 -0
  16. package/build/src/devtools/DevToolsCommentBridge.js +91 -0
  17. package/build/src/devtools/DevtoolsUtils.js +27 -21
  18. package/build/src/formatters/CommentFormatter.js +82 -0
  19. package/build/src/formatters/CssFormatter.js +812 -0
  20. package/build/src/formatters/NetworkFormatter.js +5 -2
  21. package/build/src/index.js +175 -128
  22. package/build/src/processors/ChunkedTraceParser.js +361 -0
  23. package/build/src/processors/PerformanceTrace.js +60 -13
  24. package/build/src/telemetry/ClearcutLogger.js +95 -37
  25. package/build/src/telemetry/metricsRegistry.js +3 -0
  26. package/build/src/telemetry/persistence.js +17 -7
  27. package/build/src/telemetry/transformation.js +53 -4
  28. package/build/src/telemetry/types.js +1 -0
  29. package/build/src/third_party/THIRD_PARTY_NOTICES +687 -133
  30. package/build/src/third_party/bundled-packages.json +6 -3
  31. package/build/src/third_party/devtools-formatter-worker.js +158 -5
  32. package/build/src/third_party/devtools-heap-snapshot-worker.js +589 -6
  33. package/build/src/third_party/index.js +59173 -38013
  34. package/build/src/third_party/issue-descriptions/webInstallManifestMissingId.md +3 -0
  35. package/build/src/third_party/issue-descriptions/webInstallManifestMissingNameOrShortName.md +3 -0
  36. package/build/src/third_party/issue-descriptions/webInstallManifestParsingOrNetworkError.md +3 -0
  37. package/build/src/third_party/issue-descriptions/webInstallNoManifest.md +3 -0
  38. package/build/src/third_party/issue-descriptions/webInstallStartUrlInvalid.md +3 -0
  39. package/build/src/tools/ToolDefinition.js +28 -21
  40. package/build/src/tools/categories.js +0 -6
  41. package/build/src/tools/comments.js +169 -0
  42. package/build/src/tools/console.js +3 -3
  43. package/build/src/tools/css.js +45 -0
  44. package/build/src/tools/emulation.js +5 -5
  45. package/build/src/tools/extensions.js +10 -10
  46. package/build/src/tools/input.js +159 -87
  47. package/build/src/tools/lighthouse.js +18 -7
  48. package/build/src/tools/memory.js +26 -26
  49. package/build/src/tools/network.js +5 -5
  50. package/build/src/tools/pages.js +34 -19
  51. package/build/src/tools/performance.js +7 -6
  52. package/build/src/tools/pwa.js +8 -8
  53. package/build/src/tools/screencast.js +5 -4
  54. package/build/src/tools/screenshot.js +2 -2
  55. package/build/src/tools/script.js +8 -7
  56. package/build/src/tools/slim/tools.js +45 -37
  57. package/build/src/tools/snapshot.js +4 -4
  58. package/build/src/tools/thirdPartyDeveloper.js +4 -4
  59. package/build/src/tools/tools.js +6 -9
  60. package/build/src/tools/webmcp.js +4 -4
  61. package/build/src/types.js +4 -1
  62. package/build/src/utils/WaitForHelper.js +26 -9
  63. package/build/src/utils/logger.js +7 -6
  64. package/build/src/utils/url.js +73 -0
  65. package/build/src/version.js +1 -1
  66. package/package.json +9 -6
  67. package/skills/chrome-devtools/SKILL.md +2 -1
  68. package/skills/chrome-devtools-cli/SKILL.md +3 -7
  69. package/skills/cookie-debugging/SKILL.md +149 -0
  70. package/skills/memory-leak-debugging/SKILL.md +4 -0
  71. package/build/src/browser.js +0 -244
  72. package/build/src/third_party/issue-descriptions/cookieExcludeBlockedWithinRelatedWebsiteSet.md +0 -4
@@ -0,0 +1,361 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ const DEFAULT_EVENTS_PER_BATCH = 10_000;
7
+ const DEFAULT_MAX_BATCH_BYTES = 32 * 1024 * 1024;
8
+ // ASCII character byte constants used by the state machine.
9
+ // All values are strictly less than 0x80 (standard ASCII).
10
+ // In UTF-8 encoding, multi-byte code units only contain bytes from 0x80 through 0xFF.
11
+ // Therefore, scanning for these byte values will never match bytes inside multi-byte characters.
12
+ const BYTE_QUOTE = 0x22;
13
+ const BYTE_BACKSLASH = 0x5c;
14
+ const BYTE_OPEN_BRACE = 0x7b;
15
+ const BYTE_CLOSE_BRACE = 0x7d;
16
+ const BYTE_OPEN_BRACKET = 0x5b;
17
+ const BYTE_CLOSE_BRACKET = 0x5d;
18
+ const BYTE_COLON = 0x3a;
19
+ const BYTE_COMMA = 0x2c;
20
+ /**
21
+ * Advances past any RFC 8259 JSON whitespace bytes.
22
+ *
23
+ * @param buffer - The trace byte buffer to inspect.
24
+ * @param start - The buffer index where scanning begins.
25
+ * @returns The index of the first non-whitespace byte, or the buffer length if the buffer ends.
26
+ */
27
+ function skipWhitespace(buffer, start) {
28
+ let i = start;
29
+ while (i < buffer.length) {
30
+ const byte = buffer[i];
31
+ if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) {
32
+ break;
33
+ }
34
+ i++;
35
+ }
36
+ return i;
37
+ }
38
+ /**
39
+ * Scans past a JSON string starting at the opening quotation mark.
40
+ *
41
+ * @param buffer - The trace byte buffer to scan.
42
+ * @param startQuotePos - The buffer index of the opening quotation mark.
43
+ * @returns The index immediately following the closing quotation mark.
44
+ * @throws {SyntaxError} If the string is unterminated before the end of the buffer.
45
+ */
46
+ function skipString(buffer, startQuotePos) {
47
+ let pos = startQuotePos + 1;
48
+ while (pos < buffer.length) {
49
+ const byte = buffer[pos];
50
+ if (byte === BYTE_BACKSLASH) {
51
+ if (pos + 1 >= buffer.length) {
52
+ throw new SyntaxError('Unterminated string in JSON');
53
+ }
54
+ pos += 2;
55
+ continue;
56
+ }
57
+ if (byte === BYTE_QUOTE) {
58
+ return pos + 1;
59
+ }
60
+ pos++;
61
+ }
62
+ throw new SyntaxError('Unterminated string in JSON');
63
+ }
64
+ /**
65
+ * Scans past a complete JSON value starting at the specified buffer position.
66
+ * Skips strings, compound objects, arrays, and primitive values without parsing them into memory.
67
+ *
68
+ * @param buffer - The trace byte buffer to scan.
69
+ * @param startPos - The buffer index where the value begins.
70
+ * @returns The index immediately following the skipped JSON value.
71
+ * @throws {SyntaxError} If the value contains unbalanced delimiters, unterminated strings, or empty primitive tokens.
72
+ */
73
+ function skipValue(buffer, startPos) {
74
+ let pos = skipWhitespace(buffer, startPos);
75
+ if (pos >= buffer.length) {
76
+ return pos;
77
+ }
78
+ const firstByte = buffer[pos];
79
+ if (firstByte === BYTE_QUOTE) {
80
+ return skipString(buffer, pos);
81
+ }
82
+ if (firstByte === BYTE_OPEN_BRACE || firstByte === BYTE_OPEN_BRACKET) {
83
+ const delimiterStack = [];
84
+ delimiterStack.push(firstByte === BYTE_OPEN_BRACE ? BYTE_CLOSE_BRACE : BYTE_CLOSE_BRACKET);
85
+ pos++;
86
+ while (pos < buffer.length) {
87
+ const byte = buffer[pos];
88
+ if (byte === BYTE_QUOTE) {
89
+ pos = skipString(buffer, pos);
90
+ continue;
91
+ }
92
+ if (byte === BYTE_OPEN_BRACE) {
93
+ delimiterStack.push(BYTE_CLOSE_BRACE);
94
+ }
95
+ else if (byte === BYTE_OPEN_BRACKET) {
96
+ delimiterStack.push(BYTE_CLOSE_BRACKET);
97
+ }
98
+ else if (byte === BYTE_CLOSE_BRACE || byte === BYTE_CLOSE_BRACKET) {
99
+ const expected = delimiterStack.pop();
100
+ if (expected !== byte) {
101
+ throw new SyntaxError('Unexpected delimiter in JSON');
102
+ }
103
+ if (delimiterStack.length === 0) {
104
+ pos++;
105
+ return pos;
106
+ }
107
+ }
108
+ pos++;
109
+ }
110
+ throw new SyntaxError('Unexpected end of JSON input');
111
+ }
112
+ const valStart = pos;
113
+ while (pos < buffer.length) {
114
+ const byte = buffer[pos];
115
+ if (byte === BYTE_COMMA ||
116
+ byte === BYTE_CLOSE_BRACE ||
117
+ byte === BYTE_CLOSE_BRACKET ||
118
+ byte === 0x20 ||
119
+ byte === 0x09 ||
120
+ byte === 0x0a ||
121
+ byte === 0x0d) {
122
+ break;
123
+ }
124
+ pos++;
125
+ }
126
+ if (pos === valStart) {
127
+ throw new SyntaxError('Expected JSON value');
128
+ }
129
+ return pos;
130
+ }
131
+ /**
132
+ * Scans trace events from a JSON array in bounded batches to limit memory consumption.
133
+ *
134
+ * @param buffer - The raw byte buffer containing the events array.
135
+ * @param startPos - The index immediately after the opening array bracket.
136
+ * @param config - Configuration settings controlling batch sizes and text decoding.
137
+ * @returns An object containing the parsed events and the ending buffer position.
138
+ * @throws {SyntaxError} If the event array contains malformed JSON, unbalanced delimiters, or unexpected tokens.
139
+ */
140
+ function parseEventsArray(buffer, startPos, config) {
141
+ const events = [];
142
+ let batchStart = -1;
143
+ let lastEventEnd = -1;
144
+ let batchEventCount = 0;
145
+ let depth = 0;
146
+ let i = startPos;
147
+ let closed = false;
148
+ let state = 'expect_element_or_end';
149
+ const flushBatch = () => {
150
+ if (batchStart !== -1 && lastEventEnd > batchStart) {
151
+ // Slicing between batchStart and lastEventEnd is safe for UTF-8 decoding.
152
+ // Both boundaries are ASCII structural braces ({ and }) that align with code unit boundaries.
153
+ const slice = buffer.subarray(batchStart, lastEventEnd);
154
+ const chunkText = config.decoder.decode(slice);
155
+ // Wrapping comma-delimited event objects in brackets creates a valid JSON array for the parser.
156
+ const parsed = JSON.parse(`[${chunkText}]`);
157
+ // Append items iteratively to avoid exceeding V8 call stack size limits on large batches.
158
+ for (const event of parsed) {
159
+ events.push(event);
160
+ }
161
+ batchStart = -1;
162
+ batchEventCount = 0;
163
+ }
164
+ };
165
+ while (i < buffer.length) {
166
+ const byte = buffer[i];
167
+ if (depth > 0) {
168
+ if (byte === BYTE_QUOTE) {
169
+ i = skipString(buffer, i);
170
+ continue;
171
+ }
172
+ if (byte === BYTE_OPEN_BRACE) {
173
+ depth++;
174
+ i++;
175
+ continue;
176
+ }
177
+ if (byte === BYTE_CLOSE_BRACE) {
178
+ depth--;
179
+ if (depth === 0) {
180
+ lastEventEnd = i + 1;
181
+ batchEventCount++;
182
+ state = 'expect_comma_or_end';
183
+ // Check thresholds after recording the completed event.
184
+ // Checking batchEventCount after incrementing ensures batches cap at exactly eventsPerBatch.
185
+ // Individual events are atomic JSON objects and cannot be split mid-event; when an event
186
+ // pushes currentBatchBytes over maxBatchBytes, the completed event is flushed immediately.
187
+ const currentBatchBytes = lastEventEnd - batchStart;
188
+ if (batchEventCount >= config.eventsPerBatch ||
189
+ currentBatchBytes >= config.maxBatchBytes) {
190
+ flushBatch();
191
+ }
192
+ }
193
+ i++;
194
+ continue;
195
+ }
196
+ i++;
197
+ continue;
198
+ }
199
+ // When depth is 0, scan top-level array delimiter and separator tokens.
200
+ if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) {
201
+ i++;
202
+ continue;
203
+ }
204
+ if (byte === BYTE_OPEN_BRACE) {
205
+ if (state !== 'expect_element_or_end' && state !== 'expect_element') {
206
+ throw new SyntaxError('Expected "," or "]" in JSON array');
207
+ }
208
+ depth = 1;
209
+ if (batchStart === -1) {
210
+ batchStart = i;
211
+ }
212
+ i++;
213
+ continue;
214
+ }
215
+ if (byte === BYTE_COMMA) {
216
+ if (state !== 'expect_comma_or_end') {
217
+ throw new SyntaxError('Unexpected token "," in JSON array');
218
+ }
219
+ state = 'expect_element';
220
+ i++;
221
+ continue;
222
+ }
223
+ if (byte === BYTE_CLOSE_BRACKET) {
224
+ if (state === 'expect_element') {
225
+ throw new SyntaxError('Unexpected token "]" in JSON array');
226
+ }
227
+ closed = true;
228
+ i++;
229
+ break;
230
+ }
231
+ if (byte === BYTE_CLOSE_BRACE) {
232
+ throw new SyntaxError('Unexpected token "}" in JSON');
233
+ }
234
+ throw new SyntaxError('Unexpected token in JSON array');
235
+ }
236
+ if (!closed || depth !== 0) {
237
+ throw new SyntaxError('Unexpected end of JSON input');
238
+ }
239
+ flushBatch();
240
+ return { events, endPos: i };
241
+ }
242
+ /**
243
+ * Parses Chrome DevTools trace events and metadata from a raw byte buffer.
244
+ * Supports both root array format ([...]) and object container format ({"traceEvents": [...]}).
245
+ * Parses events in chunks to prevent V8 string length and memory exhaustion errors.
246
+ *
247
+ * @param buffer - The raw trace buffer to parse.
248
+ * @param options - Optional configuration settings for batch processing.
249
+ * @returns A {@link ParsedTraceBuffer} containing parsed trace events and optional file metadata, or an object with an empty events array if the buffer is empty or contains only whitespace.
250
+ * @throws {Error} If the buffer contains non-whitespace data that does not begin with a valid JSON array or object.
251
+ * @throws {SyntaxError} If the underlying JSON syntax within batches or metadata is invalid.
252
+ */
253
+ export function parseTraceEventsFromBuffer(buffer, options = {}) {
254
+ const eventsPerBatch = typeof options.eventsPerBatch === 'number' &&
255
+ Number.isFinite(options.eventsPerBatch) &&
256
+ options.eventsPerBatch > 0
257
+ ? options.eventsPerBatch
258
+ : DEFAULT_EVENTS_PER_BATCH;
259
+ const maxBatchBytes = typeof options.maxBatchBytes === 'number' &&
260
+ Number.isFinite(options.maxBatchBytes) &&
261
+ options.maxBatchBytes > 0
262
+ ? options.maxBatchBytes
263
+ : DEFAULT_MAX_BATCH_BYTES;
264
+ const decoder = new TextDecoder();
265
+ const config = {
266
+ eventsPerBatch,
267
+ maxBatchBytes,
268
+ decoder,
269
+ };
270
+ let pos = skipWhitespace(buffer, 0);
271
+ if (pos >= buffer.length) {
272
+ return { events: [] };
273
+ }
274
+ const firstByte = buffer[pos];
275
+ if (firstByte === BYTE_OPEN_BRACKET) {
276
+ const { events, endPos } = parseEventsArray(buffer, pos + 1, config);
277
+ const trailingPos = skipWhitespace(buffer, endPos);
278
+ if (trailingPos < buffer.length) {
279
+ throw new SyntaxError('Unexpected non-whitespace character after JSON');
280
+ }
281
+ return { events };
282
+ }
283
+ if (firstByte === BYTE_OPEN_BRACE) {
284
+ pos++;
285
+ let events = [];
286
+ let metadata;
287
+ let closed = false;
288
+ let expectComma = false;
289
+ while (pos < buffer.length) {
290
+ pos = skipWhitespace(buffer, pos);
291
+ if (pos >= buffer.length) {
292
+ break;
293
+ }
294
+ if (buffer[pos] === BYTE_CLOSE_BRACE) {
295
+ closed = true;
296
+ pos++;
297
+ break;
298
+ }
299
+ if (expectComma) {
300
+ if (buffer[pos] !== BYTE_COMMA) {
301
+ throw new SyntaxError('Expected "," or "}" after property value in JSON');
302
+ }
303
+ pos++;
304
+ pos = skipWhitespace(buffer, pos);
305
+ }
306
+ if (pos >= buffer.length) {
307
+ break;
308
+ }
309
+ if (buffer[pos] !== BYTE_QUOTE) {
310
+ throw new SyntaxError('Expected property name or "}" in JSON');
311
+ }
312
+ const keyStart = pos;
313
+ pos = skipString(buffer, pos);
314
+ const keyJson = decoder.decode(buffer.subarray(keyStart, pos));
315
+ const parsedKey = JSON.parse(keyJson);
316
+ if (typeof parsedKey !== 'string') {
317
+ throw new SyntaxError('Expected property name in JSON');
318
+ }
319
+ const key = parsedKey;
320
+ pos = skipWhitespace(buffer, pos);
321
+ if (pos >= buffer.length || buffer[pos] !== BYTE_COLON) {
322
+ throw new SyntaxError('Expected ":" after property name in JSON');
323
+ }
324
+ pos++;
325
+ pos = skipWhitespace(buffer, pos);
326
+ if (key === 'traceEvents') {
327
+ if (pos >= buffer.length || buffer[pos] !== BYTE_OPEN_BRACKET) {
328
+ throw new SyntaxError('Expected "[" for "traceEvents" in JSON');
329
+ }
330
+ const arrayResult = parseEventsArray(buffer, pos + 1, config);
331
+ events = arrayResult.events;
332
+ pos = arrayResult.endPos;
333
+ }
334
+ else if (key === 'metadata') {
335
+ if (pos >= buffer.length || buffer[pos] !== BYTE_OPEN_BRACE) {
336
+ throw new SyntaxError('Expected "{" for "metadata" in JSON');
337
+ }
338
+ const metaStart = pos;
339
+ pos = skipValue(buffer, pos);
340
+ const metaSlice = buffer.subarray(metaStart, pos);
341
+ const metaText = decoder.decode(metaSlice);
342
+ const parsedMetadata = JSON.parse(metaText);
343
+ metadata = parsedMetadata;
344
+ }
345
+ else {
346
+ pos = skipValue(buffer, pos);
347
+ }
348
+ expectComma = true;
349
+ }
350
+ if (!closed) {
351
+ throw new SyntaxError('Unexpected end of JSON input');
352
+ }
353
+ const trailingPos = skipWhitespace(buffer, pos);
354
+ if (trailingPos < buffer.length) {
355
+ throw new SyntaxError('Unexpected non-whitespace character after JSON');
356
+ }
357
+ return { events, metadata };
358
+ }
359
+ throw new Error('Invalid trace buffer: expected JSON object or array.');
360
+ }
361
+ //# sourceMappingURL=ChunkedTraceParser.js.map
@@ -5,34 +5,65 @@
5
5
  */
6
6
  import { DevTools } from '../third_party/index.js';
7
7
  import { logger } from '../utils/logger.js';
8
- const engine = DevTools.TraceEngine.TraceModel.Model.createWithAllHandlers();
8
+ import { parseTraceEventsFromBuffer } from './ChunkedTraceParser.js';
9
+ /**
10
+ * Type guard that verifies if an operation returned a valid TraceResult.
11
+ *
12
+ * @param x - The result or error object to inspect.
13
+ * @returns True if the object is a TraceResult; otherwise false.
14
+ */
9
15
  export function traceResultIsSuccess(x) {
10
16
  return 'parsedTrace' in x;
11
17
  }
18
+ /**
19
+ * Parses raw JSON trace buffer bytes into a DevTools TraceEngine representation.
20
+ *
21
+ * Accepts either a JSON array of trace events or an object with a `traceEvents` field.
22
+ * Events are parsed in chunks directly from the raw byte buffer to avoid V8 string
23
+ * allocation limits. A new trace engine model is created per call to ensure session
24
+ * isolation and prevent memory retention.
25
+ *
26
+ * @param buffer - Raw binary trace data representing trace events and metadata.
27
+ * @param metadata - Optional throttling configurations applied during recording; overrides embedded file metadata when defined.
28
+ * @returns A promise resolving to a {@link TraceResult} with parsed traces and insights, or a {@link TraceParseError} on failure.
29
+ */
12
30
  export async function parseRawTraceBuffer(buffer, metadata) {
13
- engine.resetProcessor();
14
- if (!buffer) {
31
+ if (!buffer || buffer.length === 0) {
15
32
  return {
16
33
  error: 'No buffer was provided.',
17
34
  };
18
35
  }
19
- const asString = new TextDecoder().decode(buffer);
20
- if (!asString) {
21
- return {
22
- error: 'Decoding the trace buffer returned an empty string.',
23
- };
24
- }
25
36
  try {
26
- const data = JSON.parse(asString);
27
- const events = Array.isArray(data) ? data : data.traceEvents;
28
- await engine.parse(events, { metadata });
37
+ const { events, metadata: fileMetadata } = parseTraceEventsFromBuffer(buffer);
38
+ if (events.length === 0) {
39
+ return {
40
+ error: 'No trace events were found in the trace buffer.',
41
+ };
42
+ }
43
+ const combinedMetadata = {
44
+ ...fileMetadata,
45
+ ...(metadata?.cpuThrottling !== undefined
46
+ ? { cpuThrottling: metadata.cpuThrottling }
47
+ : {}),
48
+ ...(metadata?.networkThrottling !== undefined
49
+ ? { networkThrottling: metadata.networkThrottling }
50
+ : {}),
51
+ };
52
+ const hasMetadata = Object.keys(combinedMetadata).length > 0;
53
+ // Instantiate a fresh TraceModel per invocation because Model permanently
54
+ // retains parsed traces in its internal `#traces` array, which causes an
55
+ // unbounded memory leak if reused across sessions.
56
+ const engine = DevTools.TraceEngine.TraceModel.Model.createWithAllHandlers();
57
+ await engine.parse(events, {
58
+ metadata: hasMetadata ? combinedMetadata : undefined,
59
+ });
29
60
  const parsedTrace = engine.parsedTrace();
30
61
  if (!parsedTrace) {
31
62
  return {
32
63
  error: 'No parsed trace was returned from the trace engine.',
33
64
  };
34
65
  }
35
- const insights = parsedTrace?.insights ?? null;
66
+ const insights = parsedTrace.insights ?? null;
36
67
  return {
37
68
  parsedTrace,
38
69
  insights,
@@ -51,6 +82,13 @@ const extraFormatDescriptions = `Information on performance traces may contain m
51
82
  ${DevTools.PerformanceTraceFormatter.callFrameDataFormatDescription}
52
83
 
53
84
  ${DevTools.PerformanceTraceFormatter.networkDataFormatDescription}`;
85
+ /**
86
+ * Generates a Markdown summary of main thread activity and network metrics from a parsed trace.
87
+ *
88
+ * @param result - The parsed trace result to summarize.
89
+ * @param deviceScope - Optional CrUX device scope to filter field data.
90
+ * @returns Formatted Markdown text describing performance findings.
91
+ */
54
92
  export function getTraceSummary(result, deviceScope) {
55
93
  const focus = DevTools.AgentFocus.fromParsedTrace(result.parsedTrace);
56
94
  const formatter = new DevTools.PerformanceTraceFormatter(focus, deviceScope);
@@ -61,6 +99,15 @@ ${summaryText}
61
99
  ## Details on call tree & network request formats:
62
100
  ${extraFormatDescriptions}`;
63
101
  }
102
+ /**
103
+ * Formats a specific performance insight from a parsed trace for display.
104
+ *
105
+ * @param result - The parsed trace result containing computed insight sets.
106
+ * @param insightSetId - The identifier of the target insight set.
107
+ * @param insightName - The name of the insight model to extract.
108
+ * @param deviceScope - Optional CrUX device scope to contextualize metrics.
109
+ * @returns An object containing the formatted insight output text or an error message.
110
+ */
64
111
  export function getInsightOutput(result, insightSetId, insightName, deviceScope) {
65
112
  if (!result.insights) {
66
113
  return {
@@ -6,7 +6,7 @@
6
6
  import process from 'node:process';
7
7
  import { DAEMON_CLIENT_NAME } from '../daemon/utils.js';
8
8
  import { logger } from '../utils/logger.js';
9
- import { sanitizeParams, stripUnderscoreBeforeNumber } from './transformation.js';
9
+ import { bucketizeDaysSince, bucketizeLatency, buildContext, sanitizeClientName, sanitizeParams, stripUnderscoreBeforeNumber, } from './transformation.js';
10
10
  import { McpClient, WatchdogMessageType, OsType, } from './types.js';
11
11
  import { WatchdogClient } from './WatchdogClient.js';
12
12
  const MS_PER_DAY = 24 * 60 * 60 * 1000;
@@ -22,12 +22,33 @@ function detectOsType() {
22
22
  return OsType.OS_TYPE_UNSPECIFIED;
23
23
  }
24
24
  }
25
+ function isSameDay(d1, d2) {
26
+ return (d1.getUTCFullYear() === d2.getUTCFullYear() &&
27
+ d1.getUTCMonth() === d2.getUTCMonth() &&
28
+ d1.getUTCDate() === d2.getUTCDate());
29
+ }
30
+ function shouldLogDailyActive(state) {
31
+ if (!state.lastActive) {
32
+ return true;
33
+ }
34
+ return !isSameDay(new Date(state.lastActive), new Date());
35
+ }
36
+ function calculateDaysSince(lastDateString, now = new Date()) {
37
+ if (!lastDateString) {
38
+ return -1;
39
+ }
40
+ const lastDate = new Date(lastDateString);
41
+ const diffTime = Math.abs(now.getTime() - lastDate.getTime());
42
+ return Math.ceil(diffTime / MS_PER_DAY);
43
+ }
25
44
  // Not const to allow resetting the instance for testing purposes.
26
45
  let _clearcut_logger_instance;
27
46
  export class ClearcutLogger {
28
47
  #persistence;
29
48
  #watchdog;
30
49
  #mcpClient;
50
+ #rawClientName;
51
+ #state;
31
52
  static initialize(options) {
32
53
  if (_clearcut_logger_instance) {
33
54
  throw new Error('ClearcutLogger is already initialized');
@@ -55,6 +76,15 @@ export class ClearcutLogger {
55
76
  clearcutIncludePidHeader: options.clearcutIncludePidHeader,
56
77
  });
57
78
  this.#mcpClient = McpClient.MCP_CLIENT_UNSPECIFIED;
79
+ void this.#persistence
80
+ .loadState()
81
+ .then(state => {
82
+ this.#state = state;
83
+ })
84
+ .catch(error => {
85
+ this.#state = undefined;
86
+ logger?.('Failed to load telemetry state:', error);
87
+ });
58
88
  }
59
89
  setClientName(clientName) {
60
90
  const lowerName = clientName.toLowerCase();
@@ -88,19 +118,40 @@ export class ClearcutLogger {
88
118
  else if (lowerName.includes('copilot')) {
89
119
  this.#mcpClient = McpClient.MCP_CLIENT_GITHUB_COPILOT;
90
120
  }
121
+ else if (lowerName.includes('hermes-agent')) {
122
+ this.#mcpClient = McpClient.MCP_CLIENT_HERMES;
123
+ }
91
124
  else {
92
125
  this.#mcpClient = McpClient.MCP_CLIENT_OTHER;
126
+ this.#rawClientName = sanitizeClientName(clientName);
127
+ }
128
+ }
129
+ #addMcpClient(payload) {
130
+ const ext = {
131
+ ...payload,
132
+ mcp_client: this.#mcpClient,
133
+ };
134
+ if (this.#mcpClient === McpClient.MCP_CLIENT_OTHER &&
135
+ this.#rawClientName !== undefined) {
136
+ ext.raw_mcp_client_info = {
137
+ raw_client_name: this.#rawClientName,
138
+ };
93
139
  }
140
+ return ext;
94
141
  }
95
142
  async logToolInvocation(args) {
143
+ void this.#logToolActiveIfNeeded().catch(error => {
144
+ logger?.('Error in logToolActiveIfNeeded:', error);
145
+ });
146
+ const context = buildContext(args.devToolsData, args.pageUrl);
96
147
  const sanitizedToolName = stripUnderscoreBeforeNumber(args.toolName);
97
148
  const tool_invocation = {
98
149
  tool_name: sanitizedToolName,
99
150
  success: args.success,
100
- latency_ms: args.latencyMs,
151
+ latency_ms: bucketizeLatency(args.latencyMs),
101
152
  };
102
- if (Object.keys(args.context).length > 0) {
103
- tool_invocation.context = args.context;
153
+ if (Object.keys(context).length > 0) {
154
+ tool_invocation.context = context;
104
155
  }
105
156
  if (Object.keys(args.params).length > 0) {
106
157
  tool_invocation.tool_params = {
@@ -109,45 +160,36 @@ export class ClearcutLogger {
109
160
  }
110
161
  this.#watchdog.send({
111
162
  type: WatchdogMessageType.LOG_EVENT,
112
- payload: {
113
- mcp_client: this.#mcpClient,
163
+ payload: this.#addMcpClient({
114
164
  tool_invocation: tool_invocation,
115
- },
165
+ }),
116
166
  });
117
167
  }
118
168
  async logServerStart(flagUsage) {
119
169
  this.#watchdog.send({
120
170
  type: WatchdogMessageType.LOG_EVENT,
121
- payload: {
122
- mcp_client: this.#mcpClient,
171
+ payload: this.#addMcpClient({
123
172
  server_start: {
124
173
  flag_usage: flagUsage,
125
174
  },
126
- },
175
+ }),
127
176
  });
128
177
  }
129
178
  async logDailyActiveIfNeeded() {
130
179
  try {
131
- const state = await this.#persistence.loadState();
132
- if (this.#shouldLogDailyActive(state)) {
133
- let daysSince = -1;
134
- if (state.lastActive) {
135
- const lastActiveDate = new Date(state.lastActive);
136
- const now = new Date();
137
- const diffTime = Math.abs(now.getTime() - lastActiveDate.getTime());
138
- daysSince = Math.ceil(diffTime / MS_PER_DAY);
139
- }
180
+ this.#state = await this.#persistence.loadState();
181
+ if (shouldLogDailyActive(this.#state)) {
182
+ const daysSince = calculateDaysSince(this.#state.lastActive);
140
183
  this.#watchdog.send({
141
184
  type: WatchdogMessageType.LOG_EVENT,
142
- payload: {
143
- mcp_client: this.#mcpClient,
185
+ payload: this.#addMcpClient({
144
186
  daily_active: {
145
- days_since_last_active: daysSince,
187
+ days_since_last_active: bucketizeDaysSince(daysSince),
146
188
  },
147
- },
189
+ }),
148
190
  });
149
- state.lastActive = new Date().toISOString();
150
- await this.#persistence.saveState(state);
191
+ this.#state.lastActive = new Date().toISOString();
192
+ await this.#persistence.saveState(this.#state);
151
193
  }
152
194
  }
153
195
  catch (err) {
@@ -157,28 +199,44 @@ export class ClearcutLogger {
157
199
  async logServerError(args) {
158
200
  this.#watchdog.send({
159
201
  type: WatchdogMessageType.LOG_EVENT,
160
- payload: {
161
- mcp_client: this.#mcpClient,
202
+ payload: this.#addMcpClient({
162
203
  server_error: {
163
204
  tool_name: args.toolName
164
205
  ? stripUnderscoreBeforeNumber(args.toolName)
165
206
  : '',
166
207
  error_code: args.errorCode,
167
208
  },
168
- },
209
+ }),
169
210
  });
170
211
  }
171
- #shouldLogDailyActive(state) {
172
- if (!state.lastActive) {
173
- return true;
212
+ async #logToolActiveIfNeeded() {
213
+ // Expect state loaded at first tool call, if not, just skip logging.
214
+ if (!this.#state) {
215
+ return;
174
216
  }
175
- const lastActiveDate = new Date(state.lastActive);
217
+ // Don't log tool active if it has already been logged today.
176
218
  const now = new Date();
177
- // Compare UTC dates
178
- const isSameDay = lastActiveDate.getUTCFullYear() === now.getUTCFullYear() &&
179
- lastActiveDate.getUTCMonth() === now.getUTCMonth() &&
180
- lastActiveDate.getUTCDate() === now.getUTCDate();
181
- return !isSameDay;
219
+ if (this.#state.lastToolCall &&
220
+ isSameDay(now, new Date(this.#state.lastToolCall))) {
221
+ return;
222
+ }
223
+ // Refresh state in case it now contains more recent value, and test again.
224
+ const state = await this.#persistence.loadState();
225
+ this.#state = state;
226
+ if (state.lastToolCall && isSameDay(now, new Date(state.lastToolCall))) {
227
+ return;
228
+ }
229
+ const daysSinceToolCall = calculateDaysSince(state.lastToolCall, now);
230
+ this.#watchdog.send({
231
+ type: WatchdogMessageType.LOG_EVENT,
232
+ payload: this.#addMcpClient({
233
+ tool_active: {
234
+ days_since_last_tool_call: bucketizeDaysSince(daysSinceToolCall),
235
+ },
236
+ }),
237
+ });
238
+ this.#state.lastToolCall = now.toISOString();
239
+ await this.#persistence.saveState(this.#state);
182
240
  }
183
241
  }
184
242
  //# sourceMappingURL=ClearcutLogger.js.map