brave-mcp 0.5.0 → 1.2.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 (120) hide show
  1. package/README.md +68 -9
  2. package/build/src/HeapSnapshotManager.js +55 -18
  3. package/build/src/McpContext.js +94 -32
  4. package/build/src/McpPage.js +9 -9
  5. package/build/src/McpResponse.js +167 -63
  6. package/build/src/PageCollector.js +8 -8
  7. package/build/src/ServiceWorkerCollector.js +171 -0
  8. package/build/src/TextSnapshot.js +1 -1
  9. package/build/src/ToolHandler.js +223 -0
  10. package/build/src/WaitForHelper.js +20 -6
  11. package/build/src/bin/brave-devtools-cli-options.js +136 -40
  12. package/build/src/bin/brave-devtools-mcp-cli-options.js +22 -11
  13. package/build/src/bin/brave-devtools-mcp-main.js +45 -6
  14. package/build/src/bin/brave-devtools.js +0 -2
  15. package/build/src/bin/check-latest-version.js +25 -1
  16. package/build/src/browser.js +45 -4
  17. package/build/src/daemon/client.js +19 -13
  18. package/build/src/daemon/daemon.js +74 -17
  19. package/build/src/daemon/utils.js +2 -2
  20. package/build/src/{DevToolsConnectionAdapter.js → devtools/DevToolsConnectionAdapter.js} +1 -1
  21. package/build/src/{DevtoolsUtils.js → devtools/DevtoolsUtils.js} +94 -19
  22. package/build/src/formatters/ConsoleFormatter.js +1 -1
  23. package/build/src/formatters/HeapSnapshotFormatter.js +44 -9
  24. package/build/src/formatters/IssueFormatter.js +4 -4
  25. package/build/src/index.js +24 -165
  26. package/build/src/telemetry/ClearcutLogger.js +35 -119
  27. package/build/src/telemetry/WatchdogClient.js +4 -4
  28. package/build/src/telemetry/errors.js +18 -0
  29. package/build/src/telemetry/flagUtils.js +4 -3
  30. package/build/src/telemetry/{toolMetricsUtils.js → metricsRegistry.js} +3 -3
  31. package/build/src/telemetry/persistence.js +21 -3
  32. package/build/src/telemetry/transformation.js +134 -0
  33. package/build/src/telemetry/types.js +0 -8
  34. package/build/src/telemetry/watchdog/ClearcutSender.js +10 -10
  35. package/build/src/telemetry/watchdog/main.js +5 -5
  36. package/build/src/third_party/THIRD_PARTY_NOTICES +3637 -0
  37. package/build/src/third_party/bundled-packages.json +12 -0
  38. package/build/src/third_party/devtools-formatter-worker.js +15300 -7
  39. package/build/src/third_party/devtools-heap-snapshot-worker.js +9817 -7
  40. package/build/src/third_party/index.js +159331 -27
  41. package/build/src/third_party/issue-descriptions/emailVerificationRequestAccountsEmptyList.md +1 -0
  42. package/build/src/third_party/issue-descriptions/emailVerificationRequestAccountsHttpNotFound.md +1 -0
  43. package/build/src/third_party/issue-descriptions/emailVerificationRequestAccountsInvalidContentType.md +1 -0
  44. package/build/src/third_party/issue-descriptions/emailVerificationRequestAccountsInvalidResponse.md +1 -0
  45. package/build/src/third_party/issue-descriptions/emailVerificationRequestAccountsNoResponse.md +1 -0
  46. package/build/src/third_party/issue-descriptions/emailVerificationRequestDnsFetchFailed.md +1 -0
  47. package/build/src/third_party/issue-descriptions/emailVerificationRequestDnsInvalidRecord.md +1 -0
  48. package/build/src/third_party/issue-descriptions/emailVerificationRequestEmailVerificationWellKnownHttpNotFound.md +1 -0
  49. package/build/src/third_party/issue-descriptions/emailVerificationRequestEmailVerificationWellKnownInvalidContentType.md +1 -0
  50. package/build/src/third_party/issue-descriptions/emailVerificationRequestEmailVerificationWellKnownInvalidResponse.md +1 -0
  51. package/build/src/third_party/issue-descriptions/emailVerificationRequestEmailVerificationWellKnownNoResponse.md +1 -0
  52. package/build/src/third_party/issue-descriptions/emailVerificationRequestInvalidEmail.md +1 -0
  53. package/build/src/third_party/issue-descriptions/emailVerificationRequestJwksHttpNotFound.md +1 -0
  54. package/build/src/third_party/issue-descriptions/emailVerificationRequestJwksInvalidResponse.md +1 -0
  55. package/build/src/third_party/issue-descriptions/emailVerificationRequestKeyBindingSigningFailed.md +1 -0
  56. package/build/src/third_party/issue-descriptions/emailVerificationRequestRpOriginIsOpaque.md +1 -0
  57. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenHttpNotFound.md +1 -0
  58. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenInvalidContentType.md +1 -0
  59. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenInvalidResponse.md +1 -0
  60. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenInvalidSdJwt.md +1 -0
  61. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenMalformedSdJwt.md +1 -0
  62. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenNoResponse.md +1 -0
  63. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbInvalidAudience.md +1 -0
  64. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbInvalidIssuedAt.md +1 -0
  65. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbInvalidNonce.md +1 -0
  66. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbInvalidSdHash.md +1 -0
  67. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbInvalidTyp.md +1 -0
  68. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbMissingAud.md +1 -0
  69. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbMissingCnf.md +1 -0
  70. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbMissingIat.md +1 -0
  71. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbMissingNonce.md +1 -0
  72. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbMissingSdHash.md +1 -0
  73. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationKbSignatureFailed.md +1 -0
  74. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtInvalidEmail.md +1 -0
  75. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtInvalidEmailVerified.md +1 -0
  76. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtInvalidHolderKey.md +1 -0
  77. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtInvalidIssuedAt.md +1 -0
  78. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtInvalidIssuer.md +1 -0
  79. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtJwksMissingKeys.md +1 -0
  80. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtMissingCnf.md +1 -0
  81. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtMissingEmail.md +1 -0
  82. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtMissingIat.md +1 -0
  83. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtMissingIss.md +1 -0
  84. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtSignatureFailed.md +1 -0
  85. package/build/src/third_party/issue-descriptions/emailVerificationRequestTokenVerificationSdJwtUnsupportedHeaderAlg.md +1 -0
  86. package/build/src/third_party/issue-descriptions/emailVerificationRequestUserLoggedOut.md +1 -0
  87. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownAccountsEndpointCrossOrigin.md +1 -0
  88. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownHttpNotFound.md +1 -0
  89. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownInvalidContentType.md +1 -0
  90. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownInvalidResponse.md +1 -0
  91. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownIssuanceEndpointCrossOrigin.md +1 -0
  92. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownListEmpty.md +1 -0
  93. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownMissingAccountsEndpoint.md +1 -0
  94. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownMissingIssuanceEndpoint.md +1 -0
  95. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownNoResponse.md +1 -0
  96. package/build/src/third_party/issue-descriptions/emailVerificationRequestWellKnownUnsupportedSigningAlgorithm.md +1 -0
  97. package/build/src/third_party/issue-descriptions/genericBackUINavigationWouldSkipAd.md +4 -0
  98. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +4236 -4219
  99. package/build/src/tools/ToolDefinition.js +2 -2
  100. package/build/src/tools/console.js +7 -0
  101. package/build/src/tools/emulation.js +29 -2
  102. package/build/src/tools/extensions.js +5 -0
  103. package/build/src/tools/input.js +57 -19
  104. package/build/src/tools/lighthouse.js +18 -13
  105. package/build/src/tools/memory.js +97 -21
  106. package/build/src/tools/network.js +2 -2
  107. package/build/src/tools/pages.js +13 -5
  108. package/build/src/tools/performance.js +15 -11
  109. package/build/src/tools/screencast.js +2 -1
  110. package/build/src/tools/screenshot.js +1 -1
  111. package/build/src/tools/script.js +33 -11
  112. package/build/src/tools/slim/tools.js +3 -0
  113. package/build/src/tools/snapshot.js +3 -2
  114. package/build/src/tools/thirdPartyDeveloper.js +12 -2
  115. package/build/src/tools/webmcp.js +2 -0
  116. package/build/src/trace-processing/parse.js +7 -7
  117. package/build/src/utils/files.js +43 -0
  118. package/build/src/version.js +4 -1
  119. package/package.json +21 -17
  120. package/build/src/telemetry/metricUtils.js +0 -15
@@ -5,13 +5,13 @@
5
5
  */
6
6
  import { ConsoleFormatter } from './formatters/ConsoleFormatter.js';
7
7
  import { HeapSnapshotFormatter } from './formatters/HeapSnapshotFormatter.js';
8
- import { isNodeLike } from './formatters/HeapSnapshotFormatter.js';
8
+ import { isEdgeLike, isNodeLike } from './formatters/HeapSnapshotFormatter.js';
9
9
  import { IssueFormatter } from './formatters/IssueFormatter.js';
10
10
  import { NetworkFormatter } from './formatters/NetworkFormatter.js';
11
11
  import { SnapshotFormatter } from './formatters/SnapshotFormatter.js';
12
12
  import { UncaughtError } from './PageCollector.js';
13
13
  import { TextSnapshot } from './TextSnapshot.js';
14
- import { DevTools } from './third_party/index.js';
14
+ import { DevTools, toonEncode } from './third_party/index.js';
15
15
  import { handleDialog } from './tools/pages.js';
16
16
  import { getInsightOutput, getTraceSummary } from './trace-processing/parse.js';
17
17
  import { paginate } from './utils/pagination.js';
@@ -61,7 +61,7 @@ export function replaceHtmlElementsWithUids(schema) {
61
61
  }
62
62
  }
63
63
  }
64
- async function getToolGroup(page) {
64
+ async function getToolGroups(page) {
65
65
  // Check if there is a `devtoolstooldiscovery` event listener
66
66
  const windowHandle = await page.pptrPage.evaluateHandle(() => window);
67
67
  // @ts-expect-error internal API
@@ -70,43 +70,78 @@ async function getToolGroup(page) {
70
70
  objectId: windowHandle.remoteObject().objectId,
71
71
  });
72
72
  if (listeners.find(l => l.type === 'devtoolstooldiscovery') === undefined) {
73
- return;
73
+ return [];
74
74
  }
75
- const toolGroup = await page.pptrPage.evaluate(() => {
75
+ const toolGroups = await page.pptrPage.evaluate(() => {
76
76
  return new Promise(resolve => {
77
77
  const event = new CustomEvent('devtoolstooldiscovery');
78
+ const groups = [];
78
79
  // @ts-expect-error Adding custom property
79
- event.respondWith = (toolGroup) => {
80
+ event.respondWith = toolGroup => {
80
81
  if (!window.__dtmcp) {
81
82
  window.__dtmcp = {};
82
83
  }
83
- window.__dtmcp.toolGroup = toolGroup;
84
+ if (!window.__dtmcp.toolGroups) {
85
+ window.__dtmcp.toolGroups = [];
86
+ }
87
+ if (typeof toolGroup.name !== 'string' ||
88
+ typeof toolGroup.description !== 'string' ||
89
+ !Array.isArray(toolGroup.tools)) {
90
+ console.error('Invalid toolGroup:', toolGroup);
91
+ return;
92
+ }
93
+ for (const tool of toolGroup.tools) {
94
+ if (typeof tool.name !== 'string' ||
95
+ typeof tool.description !== 'string' ||
96
+ typeof tool.inputSchema !== 'object' ||
97
+ typeof tool.execute !== 'function') {
98
+ console.error('Invalid tool:', tool);
99
+ return;
100
+ }
101
+ }
102
+ window.__dtmcp.toolGroups.push(toolGroup);
84
103
  // When receiving a toolGroup for the first time, expose a simple execution helper
85
104
  if (!window.__dtmcp.executeTool) {
86
105
  window.__dtmcp.executeTool = async (toolName, args) => {
87
- if (!window.__dtmcp?.toolGroup) {
106
+ if (!window.__dtmcp?.toolGroups ||
107
+ window.__dtmcp.toolGroups.length === 0) {
88
108
  throw new Error('No tools found on the page');
89
109
  }
90
- const tool = window.__dtmcp.toolGroup.tools.find(t => t.name === toolName);
91
- if (!tool) {
92
- throw new Error(`Tool ${toolName} not found`);
110
+ for (const group of window.__dtmcp.toolGroups) {
111
+ const tool = group.tools?.find(t => t.name === toolName);
112
+ if (tool) {
113
+ return await tool.execute(args);
114
+ }
93
115
  }
94
- return await tool.execute(args);
116
+ throw new Error(`Tool ${toolName} not found`);
95
117
  };
96
118
  }
97
- resolve(toolGroup);
119
+ groups.push(toolGroup);
98
120
  };
99
121
  window.dispatchEvent(event);
100
- // If the page does not synchronously call `event.respondWith`, return instead of timing out
101
- setTimeout(() => {
102
- resolve(undefined);
103
- }, 0);
122
+ // If at least one toolGroup was added synchronously, resolve with the array.
123
+ // Otherwise, use setTimeout to allow for any microtask/asynchronous respondWith calls, or resolve with an empty array.
124
+ if (groups.length > 0) {
125
+ resolve(groups);
126
+ }
127
+ else {
128
+ setTimeout(() => {
129
+ if (groups.length > 0) {
130
+ resolve(groups);
131
+ }
132
+ else {
133
+ resolve([]);
134
+ }
135
+ }, 0);
136
+ }
104
137
  });
105
138
  });
106
- for (const tool of toolGroup?.tools ?? []) {
107
- replaceHtmlElementsWithUids(tool.inputSchema);
139
+ for (const group of toolGroups) {
140
+ for (const tool of group.tools ?? []) {
141
+ replaceHtmlElementsWithUids(tool.inputSchema);
142
+ }
108
143
  }
109
- return toolGroup;
144
+ return toolGroups;
110
145
  }
111
146
  export class McpResponse {
112
147
  #includePages = false;
@@ -133,6 +168,10 @@ export class McpResponse {
133
168
  #page;
134
169
  #redactNetworkHeaders = true;
135
170
  #error;
171
+ #attachedWaitForResult;
172
+ get #deviceScope() {
173
+ return this.#page?.viewport?.isMobile ? 'PHONE' : 'DESKTOP';
174
+ }
136
175
  constructor(args) {
137
176
  this.#args = args;
138
177
  }
@@ -164,9 +203,7 @@ export class McpResponse {
164
203
  this.#listExtensions = true;
165
204
  }
166
205
  setListThirdPartyDeveloperTools() {
167
- if (this.#args.categoryExperimentalThirdParty) {
168
- this.#listThirdPartyDeveloperTools = true;
169
- }
206
+ this.#listThirdPartyDeveloperTools = true;
170
207
  }
171
208
  setListWebMcpTools() {
172
209
  this.#listWebMcpTools = true;
@@ -204,6 +241,7 @@ export class McpResponse {
204
241
  : undefined,
205
242
  types: options?.types,
206
243
  includePreservedMessages: options?.includePreservedMessages,
244
+ serviceWorkerId: options?.serviceWorkerId,
207
245
  };
208
246
  }
209
247
  setError(error) {
@@ -265,6 +303,9 @@ export class McpResponse {
265
303
  appendResponseLine(value) {
266
304
  this.#textResponseLines.push(value);
267
305
  }
306
+ attachWaitForResult(result) {
307
+ this.#attachedWaitForResult = result;
308
+ }
268
309
  setHeapSnapshotAggregates(aggregates, options) {
269
310
  this.#heapSnapshotOptions = {
270
311
  ...this.#heapSnapshotOptions,
@@ -289,6 +330,13 @@ export class McpResponse {
289
330
  pagination: options,
290
331
  };
291
332
  }
333
+ setHeapSnapshotRetainingPaths(retainingPaths) {
334
+ this.#heapSnapshotOptions = {
335
+ ...this.#heapSnapshotOptions,
336
+ include: true,
337
+ retainingPaths,
338
+ };
339
+ }
292
340
  attachImage(value) {
293
341
  this.#images.push(value);
294
342
  }
@@ -304,7 +352,7 @@ export class McpResponse {
304
352
  get listWebMcpTools() {
305
353
  return this.#listWebMcpTools;
306
354
  }
307
- async handle(toolName, context) {
355
+ async handle(toolName, context, useToon = false) {
308
356
  if (this.#includePages) {
309
357
  await context.createPagesSnapshot();
310
358
  }
@@ -381,24 +429,35 @@ export class McpResponse {
381
429
  if (this.#listExtensions) {
382
430
  extensions = await context.listExtensions();
383
431
  }
384
- let thirdPartyDeveloperTools;
385
- if (this.#listThirdPartyDeveloperTools) {
386
- const page = this.#page ?? context.getSelectedMcpPage();
387
- thirdPartyDeveloperTools = await getToolGroup(page);
388
- page.thirdPartyDeveloperTools = thirdPartyDeveloperTools;
432
+ let thirdPartyDeveloperTools = [];
433
+ if (this.#args.categoryExperimentalThirdParty &&
434
+ this.#listThirdPartyDeveloperTools &&
435
+ this.#page) {
436
+ thirdPartyDeveloperTools = await getToolGroups(this.#page);
437
+ if (thirdPartyDeveloperTools) {
438
+ this.#page.thirdPartyDeveloperTools = thirdPartyDeveloperTools;
439
+ }
389
440
  }
390
441
  let webmcpTools;
391
- if (this.#listWebMcpTools && this.#args.categoryExperimentalWebmcp) {
392
- const page = this.#page ?? context.getSelectedMcpPage();
393
- webmcpTools = page.getWebMcpTools();
442
+ if (this.#args.categoryExperimentalWebmcp &&
443
+ this.#listWebMcpTools &&
444
+ this.#page) {
445
+ webmcpTools = this.#page.getWebMcpTools();
394
446
  }
395
447
  let consoleMessages;
396
448
  if (this.#consoleDataOptions?.include) {
397
- if (!this.#page) {
398
- throw new Error(`Response must have an McpPage`);
449
+ let messages;
450
+ let page;
451
+ if (this.#consoleDataOptions.serviceWorkerId) {
452
+ messages = context.getServiceWorkerConsoleData(this.#consoleDataOptions.serviceWorkerId);
453
+ }
454
+ else {
455
+ page = this.#page;
456
+ if (!page) {
457
+ throw new Error(`Response must have an McpPage`);
458
+ }
459
+ messages = context.getConsoleData(page, this.#consoleDataOptions.includePreservedMessages);
399
460
  }
400
- const page = this.#page;
401
- let messages = context.getConsoleData(this.#page, this.#consoleDataOptions.includePreservedMessages);
402
461
  if (this.#consoleDataOptions.types?.length) {
403
462
  const normalizedTypes = new Set(this.#consoleDataOptions.types);
404
463
  messages = messages.filter(message => {
@@ -415,7 +474,9 @@ export class McpResponse {
415
474
  const consoleMessageStableId = context.getConsoleMessageStableId(item);
416
475
  if ('args' in item || item instanceof UncaughtError) {
417
476
  const consoleMessage = item;
418
- const devTools = context.getDevToolsUniverse(page);
477
+ const devTools = page
478
+ ? context.getDevToolsUniverse(page)
479
+ : null;
419
480
  return await ConsoleFormatter.from(consoleMessage, {
420
481
  id: consoleMessageStableId,
421
482
  fetchDetailedData: false,
@@ -472,15 +533,22 @@ export class McpResponse {
472
533
  thirdPartyDeveloperTools,
473
534
  webmcpTools,
474
535
  errorMessage: this.#error?.message,
475
- });
536
+ }, useToon);
476
537
  }
477
- format(toolName, context, data) {
538
+ format(toolName, context, data, useToon) {
478
539
  const structuredContent = {};
479
540
  const response = [];
480
541
  if (this.#textResponseLines.length) {
481
542
  structuredContent.message = this.#textResponseLines.join('\n');
482
543
  response.push(...this.#textResponseLines);
483
544
  }
545
+ if (this.#attachedWaitForResult) {
546
+ if (this.#attachedWaitForResult.navigatedToUrl) {
547
+ response.push(`Page navigated to ${this.#attachedWaitForResult.navigatedToUrl}.`);
548
+ structuredContent.navigatedToUrl =
549
+ this.#attachedWaitForResult.navigatedToUrl;
550
+ }
551
+ }
484
552
  const networkConditions = this.#page?.networkConditions;
485
553
  if (networkConditions) {
486
554
  const timeout = this.#page.pptrPage.getDefaultNavigationTimeout();
@@ -489,6 +557,11 @@ export class McpResponse {
489
557
  structuredContent.networkConditions = networkConditions;
490
558
  structuredContent.navigationTimeout = timeout;
491
559
  }
560
+ const geolocation = this.#page?.geolocation;
561
+ if (geolocation) {
562
+ response.push(`Emulating geolocation: latitude=${geolocation.latitude}, longitude=${geolocation.longitude}`);
563
+ structuredContent.geolocation = geolocation;
564
+ }
492
565
  const viewport = this.#page?.viewport;
493
566
  if (viewport) {
494
567
  response.push(`Emulating viewport: ${JSON.stringify(viewport)}`);
@@ -584,7 +657,7 @@ Call ${handleDialog.name} to handle it before continuing.`);
584
657
  structuredContent.tabId = this.#tabId;
585
658
  }
586
659
  if (data.traceSummary) {
587
- const summary = getTraceSummary(data.traceSummary);
660
+ const summary = getTraceSummary(data.traceSummary, this.#deviceScope);
588
661
  response.push(summary);
589
662
  structuredContent.traceSummary = summary;
590
663
  structuredContent.traceInsights = [];
@@ -598,7 +671,7 @@ Call ${handleDialog.name} to handle it before continuing.`);
598
671
  }
599
672
  }
600
673
  if (data.traceInsight) {
601
- const insightOutput = getInsightOutput(data.traceInsight.trace, data.traceInsight.insightSetId, data.traceInsight.insightName);
674
+ const insightOutput = getInsightOutput(data.traceInsight.trace, data.traceInsight.insightSetId, data.traceInsight.insightName, this.#deviceScope);
602
675
  if ('error' in insightOutput) {
603
676
  response.push(insightOutput.error);
604
677
  }
@@ -632,9 +705,11 @@ Call ${handleDialog.name} to handle it before continuing.`);
632
705
  structuredContent.snapshotFilePath = data.snapshot;
633
706
  }
634
707
  else {
635
- response.push('## Latest page snapshot');
636
- response.push(data.snapshot.toString());
637
708
  structuredContent.snapshot = data.snapshot.toJSON();
709
+ response.push('## Latest page snapshot');
710
+ response.push(useToon
711
+ ? toonEncode(structuredContent.snapshot)
712
+ : data.snapshot.toString());
638
713
  }
639
714
  }
640
715
  if (this.#heapSnapshotOptions?.include) {
@@ -659,20 +734,50 @@ Call ${handleDialog.name} to handle it before continuing.`);
659
734
  response.push(...paginationData.info);
660
735
  const paginatedRecord = Object.fromEntries(paginationData.items);
661
736
  const formatter = new HeapSnapshotFormatter(paginatedRecord);
662
- response.push(formatter.toString());
663
737
  structuredContent.heapSnapshotData = formatter.toJSON();
738
+ response.push(useToon
739
+ ? toonEncode(structuredContent.heapSnapshotData)
740
+ : formatter.toString());
664
741
  }
665
742
  const nodes = this.#heapSnapshotOptions.nodes;
666
743
  if (nodes) {
667
- const sortedItems = nodes.items
668
- .filter(isNodeLike)
669
- .sort((a, b) => b.retainedSize - a.retainedSize);
670
- const paginationData = this.#dataWithPagination(sortedItems, this.#heapSnapshotOptions.pagination);
744
+ let items = Array.from(nodes.items);
745
+ const firstItem = nodes.items[0];
746
+ if (firstItem) {
747
+ if (isNodeLike(firstItem)) {
748
+ items = items
749
+ .filter(isNodeLike)
750
+ .sort((a, b) => b.retainedSize - a.retainedSize);
751
+ }
752
+ else if (isEdgeLike(firstItem)) {
753
+ items = items.filter(isEdgeLike);
754
+ }
755
+ }
756
+ const paginationData = this.#dataWithPagination(items, this.#heapSnapshotOptions.pagination);
671
757
  response.push(HeapSnapshotFormatter.formatNodes(paginationData.items));
672
758
  structuredContent.pagination = paginationData.pagination;
673
759
  response.push(...paginationData.info);
674
760
  structuredContent.heapSnapshotNodes = paginationData.items;
675
761
  }
762
+ const retainingPaths = this.#heapSnapshotOptions.retainingPaths;
763
+ if (retainingPaths) {
764
+ response.push('### Retaining Paths');
765
+ const { paths, limitsReached } = retainingPaths;
766
+ if (paths.length === 0) {
767
+ response.push('No retaining paths found.');
768
+ }
769
+ else {
770
+ response.push(HeapSnapshotFormatter.formatRetainingPaths(paths));
771
+ }
772
+ const reached = Object.entries(limitsReached)
773
+ .filter(([, hit]) => hit)
774
+ .map(([limit]) => limit);
775
+ if (reached.length > 0) {
776
+ response.push(`Note: results are truncated, the following limits were reached: ${reached.join(', ')}.`);
777
+ }
778
+ structuredContent.heapSnapshotRetainingPaths =
779
+ retainingPaths;
780
+ }
676
781
  }
677
782
  if (data.detailedNetworkRequest) {
678
783
  response.push(data.detailedNetworkRequest.toStringDetailed());
@@ -700,16 +805,11 @@ Call ${handleDialog.name} to handle it before continuing.`);
700
805
  response.push(extensionsMessage);
701
806
  }
702
807
  }
703
- if (this.#listThirdPartyDeveloperTools) {
808
+ if (data.thirdPartyDeveloperTools.length) {
704
809
  structuredContent.thirdPartyDeveloperTools =
705
- data.thirdPartyDeveloperTools ?? undefined;
810
+ data.thirdPartyDeveloperTools;
706
811
  response.push('## Third-party developer tools');
707
- if (!data.thirdPartyDeveloperTools ||
708
- !data.thirdPartyDeveloperTools.tools) {
709
- response.push('No third-party developer tools available.');
710
- }
711
- else {
712
- const toolGroup = data.thirdPartyDeveloperTools;
812
+ for (const toolGroup of data.thirdPartyDeveloperTools) {
713
813
  response.push(`${toolGroup.name}: ${toolGroup.description}`);
714
814
  response.push('Available tools:');
715
815
  const toolDefinitionsMessage = toolGroup.tools
@@ -748,11 +848,10 @@ Call ${handleDialog.name} to handle it before continuing.`);
748
848
  structuredContent.pagination = paginationData.pagination;
749
849
  response.push(...paginationData.info);
750
850
  if (data.networkRequests) {
751
- structuredContent.networkRequests = [];
752
- for (const formatter of paginationData.items) {
753
- response.push(formatter.toString());
754
- structuredContent.networkRequests.push(formatter.toJSON());
755
- }
851
+ structuredContent.networkRequests = paginationData.items.map(i => i.toJSON());
852
+ response.push(...(useToon
853
+ ? [toonEncode(structuredContent.networkRequests)]
854
+ : paginationData.items.map(i => i.toString())));
756
855
  }
757
856
  }
758
857
  else {
@@ -766,9 +865,14 @@ Call ${handleDialog.name} to handle it before continuing.`);
766
865
  const grouped = ConsoleFormatter.groupConsecutive(messages);
767
866
  const paginationData = this.#dataWithPagination(grouped, this.#consoleDataOptions.pagination);
768
867
  structuredContent.pagination = paginationData.pagination;
769
- response.push(...paginationData.info);
770
- response.push(...paginationData.items.map(item => item.toString()));
771
868
  structuredContent.consoleMessages = paginationData.items.map(item => item.toJSON());
869
+ response.push(...paginationData.info);
870
+ if (useToon) {
871
+ response.push(toonEncode(structuredContent.consoleMessages));
872
+ }
873
+ else {
874
+ response.push(...paginationData.items.map(item => item.toString()));
875
+ }
772
876
  }
773
877
  else {
774
878
  response.push('<no console messages found>');
@@ -3,7 +3,7 @@
3
3
  * Copyright 2025 Google LLC
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
- import { FakeIssuesManager } from './DevtoolsUtils.js';
6
+ import { FakeIssuesManager } from './devtools/DevtoolsUtils.js';
7
7
  import { logger } from './logger.js';
8
8
  import { DevTools } from './third_party/index.js';
9
9
  import { createIdGenerator, stableIdSymbol, } from './utils/id.js';
@@ -50,7 +50,7 @@ export class PageCollector {
50
50
  this.addPage(page);
51
51
  }
52
52
  catch (err) {
53
- logger('Error getting a page for a target onTargetCreated', err);
53
+ logger?.('Error getting a page for a target onTargetCreated', err);
54
54
  }
55
55
  };
56
56
  #onTargetDestroyed = async (target) => {
@@ -62,7 +62,7 @@ export class PageCollector {
62
62
  this.cleanupPageDestroyed(page);
63
63
  }
64
64
  catch (err) {
65
- logger('Error getting a page for a target onTargetDestroyed', err);
65
+ logger?.('Error getting a page for a target onTargetDestroyed', err);
66
66
  }
67
67
  };
68
68
  addPage(page) {
@@ -136,10 +136,10 @@ export class PageCollector {
136
136
  throw new Error('No requests found for selected page');
137
137
  }
138
138
  const item = this.find(page, item => item[stableIdSymbol] === stableId);
139
- if (item) {
140
- return item;
139
+ if (!item) {
140
+ throw new Error('Request not found for selected page');
141
141
  }
142
- throw new Error('Request not found for selected page');
142
+ return item;
143
143
  }
144
144
  find(page, filter) {
145
145
  const navigations = this.storage.get(page);
@@ -241,7 +241,7 @@ class PageEventSubscriber {
241
241
  // @ts-expect-error Protocol types diverge.
242
242
  inspectorIssue)[0];
243
243
  if (!issue) {
244
- logger('No issue mapping for for the issue: ', inspectorIssue.code);
244
+ logger?.('No issue mapping for for the issue: ', inspectorIssue.code);
245
245
  return;
246
246
  }
247
247
  const primaryKey = issue.primaryKey();
@@ -256,7 +256,7 @@ class PageEventSubscriber {
256
256
  });
257
257
  }
258
258
  catch (error) {
259
- logger('Error creating a new issue', error);
259
+ logger?.('Error creating a new issue', error);
260
260
  }
261
261
  };
262
262
  }
@@ -0,0 +1,171 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { UncaughtError } from './PageCollector.js';
7
+ import { createIdGenerator, stableIdSymbol } from './utils/id.js';
8
+ const CHROME_EXTENSION_PREFIX = 'chrome-extension://';
9
+ export class ServiceWorkerSubscriber {
10
+ #target;
11
+ #callback;
12
+ #session;
13
+ #worker;
14
+ constructor(target, callback) {
15
+ this.#target = target;
16
+ this.#callback = callback;
17
+ }
18
+ async subscribe() {
19
+ this.#session = await this.#target.createCDPSession();
20
+ await this.#session.send('Runtime.enable');
21
+ this.#session.on('Runtime.exceptionThrown', this.#onExceptionThrown);
22
+ this.#worker = (await this.#target.worker()) ?? undefined;
23
+ if (this.#worker) {
24
+ this.#worker.on('console', this.#onConsole);
25
+ }
26
+ }
27
+ async unsubscribe() {
28
+ if (this.#worker) {
29
+ this.#worker.off('console', this.#onConsole);
30
+ }
31
+ await this.#session?.detach();
32
+ }
33
+ #onConsole = (message) => {
34
+ this.#callback(message);
35
+ };
36
+ #onExceptionThrown = (event) => {
37
+ const url = this.#target.url();
38
+ const extensionId = extractExtensionId(url);
39
+ if (extensionId) {
40
+ this.#callback(new UncaughtError(event.exceptionDetails, extensionId));
41
+ }
42
+ };
43
+ }
44
+ export class ServiceWorkerConsoleCollector {
45
+ #storage = new Map();
46
+ #maxLogs;
47
+ #browser;
48
+ #serviceWorkerSubscribers = new Map();
49
+ #idGenerator = createIdGenerator();
50
+ constructor(browser, maxLogs = 1000) {
51
+ this.#browser = browser;
52
+ this.#maxLogs = maxLogs;
53
+ }
54
+ async init(workers) {
55
+ if (!this.#browser) {
56
+ return;
57
+ }
58
+ this.#browser.on('targetcreated', this.#onTargetCreated);
59
+ this.#browser.on('targetdestroyed', this.#onTargetDestroyed);
60
+ for (const worker of workers) {
61
+ void this.#onTargetCreated(worker.target);
62
+ }
63
+ }
64
+ dispose() {
65
+ if (!this.#browser) {
66
+ return;
67
+ }
68
+ this.#browser.off('targetcreated', this.#onTargetCreated);
69
+ this.#browser.off('targetdestroyed', this.#onTargetDestroyed);
70
+ for (const subscriber of this.#serviceWorkerSubscribers.values()) {
71
+ subscriber.unsubscribe().catch(err => {
72
+ if (err instanceof Error &&
73
+ !err.message.includes('Target closed') &&
74
+ !err.message.includes('Session closed')) {
75
+ // Swallow error as we are tearing down the system
76
+ }
77
+ });
78
+ }
79
+ this.#serviceWorkerSubscribers.clear();
80
+ }
81
+ #onTargetCreated = async (target) => {
82
+ if (this.#serviceWorkerSubscribers.has(target)) {
83
+ return;
84
+ }
85
+ const origin = target.url();
86
+ if (target.type() === 'service_worker' && isExtensionOrigin(origin)) {
87
+ const extensionId = extractExtensionId(origin);
88
+ if (!extensionId) {
89
+ return;
90
+ }
91
+ const subscriber = new ServiceWorkerSubscriber(target, item => {
92
+ this.addLog(extensionId, item);
93
+ });
94
+ try {
95
+ await subscriber.subscribe();
96
+ }
97
+ catch (err) {
98
+ if (err instanceof Error &&
99
+ !err.message.includes('Target closed') &&
100
+ !err.message.includes('Session closed')) {
101
+ throw err;
102
+ }
103
+ }
104
+ this.#serviceWorkerSubscribers.set(target, subscriber);
105
+ }
106
+ };
107
+ #onTargetDestroyed = async (target) => {
108
+ const subscriber = this.#serviceWorkerSubscribers.get(target);
109
+ if (subscriber) {
110
+ try {
111
+ await subscriber.unsubscribe();
112
+ }
113
+ catch (err) {
114
+ if (err instanceof Error &&
115
+ !err.message.includes('Target closed') &&
116
+ !err.message.includes('Session closed')) {
117
+ throw err;
118
+ }
119
+ }
120
+ this.#serviceWorkerSubscribers.delete(target);
121
+ }
122
+ };
123
+ addLog(extensionId, log) {
124
+ const logs = this.#storage.get(extensionId) ?? [];
125
+ const withId = log;
126
+ withId[stableIdSymbol] = this.#idGenerator();
127
+ logs.push(withId);
128
+ if (logs.length > this.#maxLogs) {
129
+ logs.shift();
130
+ }
131
+ this.#storage.set(extensionId, logs);
132
+ }
133
+ getData(extensionId) {
134
+ return this.#storage.get(extensionId) ?? [];
135
+ }
136
+ getById(extensionId, stableId) {
137
+ const logs = this.#storage.get(extensionId);
138
+ if (!logs) {
139
+ throw new Error('No logs found for selected extension');
140
+ }
141
+ const item = logs.find(item => item[stableIdSymbol] === stableId);
142
+ if (item) {
143
+ return item;
144
+ }
145
+ throw new Error('Log not found for selected extension');
146
+ }
147
+ find(extensionId, filter) {
148
+ const logs = this.#storage.get(extensionId);
149
+ if (!logs) {
150
+ return;
151
+ }
152
+ return logs.find(filter);
153
+ }
154
+ clearLogs(extensionId) {
155
+ this.#storage.delete(extensionId);
156
+ }
157
+ }
158
+ function extractExtensionId(origin) {
159
+ if (!origin || !isExtensionOrigin(origin)) {
160
+ return null;
161
+ }
162
+ const pathPart = origin.substring(CHROME_EXTENSION_PREFIX.length);
163
+ const slashIndex = pathPart.indexOf('/');
164
+ // if there's no / it means that pathPart is now the extensionId, otherwise
165
+ // we take everything until the first /
166
+ return slashIndex === -1 ? pathPart : pathPart.substring(0, slashIndex);
167
+ }
168
+ function isExtensionOrigin(origin) {
169
+ return origin.startsWith(CHROME_EXTENSION_PREFIX);
170
+ }
171
+ //# sourceMappingURL=ServiceWorkerCollector.js.map
@@ -186,7 +186,7 @@ export class TextSnapshot {
186
186
  }
187
187
  }
188
188
  catch (e) {
189
- logger(`Failed to collect descendants for backend node ${backendNodeId}`, e);
189
+ logger?.(`Failed to collect descendants for backend node ${backendNodeId}`, e);
190
190
  }
191
191
  return descendantIds;
192
192
  };