@pyrokine/mcp-chrome 3.0.0 → 3.1.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 (144) hide show
  1. package/README.md +721 -303
  2. package/README_zh.md +750 -292
  3. package/dist/cdp/client.d.ts +7 -3
  4. package/dist/cdp/client.d.ts.map +1 -1
  5. package/dist/cdp/client.js +252 -63
  6. package/dist/cdp/client.js.map +1 -1
  7. package/dist/cdp/launcher.d.ts +1 -1
  8. package/dist/cdp/launcher.d.ts.map +1 -1
  9. package/dist/cdp/launcher.js +33 -12
  10. package/dist/cdp/launcher.js.map +1 -1
  11. package/dist/core/auto-wait.d.ts.map +1 -1
  12. package/dist/core/auto-wait.js +88 -52
  13. package/dist/core/auto-wait.js.map +1 -1
  14. package/dist/core/browser-driver.d.ts +76 -18
  15. package/dist/core/browser-driver.d.ts.map +1 -1
  16. package/dist/core/browser-driver.js.map +1 -1
  17. package/dist/core/browser-event-schema.d.ts +287 -0
  18. package/dist/core/browser-event-schema.d.ts.map +1 -0
  19. package/dist/core/browser-event-schema.js +104 -0
  20. package/dist/core/browser-event-schema.js.map +1 -0
  21. package/dist/core/browser-events.d.ts +99 -0
  22. package/dist/core/browser-events.d.ts.map +1 -0
  23. package/dist/core/browser-events.js +1312 -0
  24. package/dist/core/browser-events.js.map +1 -0
  25. package/dist/core/challenge-page.d.ts +39 -0
  26. package/dist/core/challenge-page.d.ts.map +1 -0
  27. package/dist/core/challenge-page.js +226 -0
  28. package/dist/core/challenge-page.js.map +1 -0
  29. package/dist/core/dom-helpers.d.ts +28 -0
  30. package/dist/core/dom-helpers.d.ts.map +1 -0
  31. package/dist/core/dom-helpers.js +311 -0
  32. package/dist/core/dom-helpers.js.map +1 -0
  33. package/dist/core/errors.d.ts +10 -4
  34. package/dist/core/errors.d.ts.map +1 -1
  35. package/dist/core/errors.js +63 -13
  36. package/dist/core/errors.js.map +1 -1
  37. package/dist/core/file-upload.d.ts +22 -0
  38. package/dist/core/file-upload.d.ts.map +1 -0
  39. package/dist/core/file-upload.js +194 -0
  40. package/dist/core/file-upload.js.map +1 -0
  41. package/dist/core/locator.d.ts +17 -2
  42. package/dist/core/locator.d.ts.map +1 -1
  43. package/dist/core/locator.js +156 -212
  44. package/dist/core/locator.js.map +1 -1
  45. package/dist/core/os-mouse.d.ts +11 -0
  46. package/dist/core/os-mouse.d.ts.map +1 -1
  47. package/dist/core/os-mouse.js +102 -29
  48. package/dist/core/os-mouse.js.map +1 -1
  49. package/dist/core/retry.d.ts.map +1 -1
  50. package/dist/core/retry.js +4 -1
  51. package/dist/core/retry.js.map +1 -1
  52. package/dist/core/session.d.ts +65 -14
  53. package/dist/core/session.d.ts.map +1 -1
  54. package/dist/core/session.js +1089 -273
  55. package/dist/core/session.js.map +1 -1
  56. package/dist/core/types.d.ts +5 -1
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/core/types.js +16 -1
  59. package/dist/core/types.js.map +1 -1
  60. package/dist/core/unified-session.d.ts +50 -41
  61. package/dist/core/unified-session.d.ts.map +1 -1
  62. package/dist/core/unified-session.js +938 -285
  63. package/dist/core/unified-session.js.map +1 -1
  64. package/dist/core/utils.d.ts +5 -4
  65. package/dist/core/utils.d.ts.map +1 -1
  66. package/dist/core/utils.js +73 -18
  67. package/dist/core/utils.js.map +1 -1
  68. package/dist/extension/bridge.d.ts +50 -19
  69. package/dist/extension/bridge.d.ts.map +1 -1
  70. package/dist/extension/bridge.js +289 -57
  71. package/dist/extension/bridge.js.map +1 -1
  72. package/dist/extension/http-server.d.ts +7 -2
  73. package/dist/extension/http-server.d.ts.map +1 -1
  74. package/dist/extension/http-server.js +219 -48
  75. package/dist/extension/http-server.js.map +1 -1
  76. package/dist/index.js +14 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/tools/browse.d.ts.map +1 -1
  79. package/dist/tools/browse.js +66 -32
  80. package/dist/tools/browse.js.map +1 -1
  81. package/dist/tools/browser-event-output.d.ts +7 -0
  82. package/dist/tools/browser-event-output.d.ts.map +1 -0
  83. package/dist/tools/browser-event-output.js +19 -0
  84. package/dist/tools/browser-event-output.js.map +1 -0
  85. package/dist/tools/challenge.d.ts +17 -5
  86. package/dist/tools/challenge.d.ts.map +1 -1
  87. package/dist/tools/challenge.js +113 -195
  88. package/dist/tools/challenge.js.map +1 -1
  89. package/dist/tools/cookies.d.ts.map +1 -1
  90. package/dist/tools/cookies.js +33 -8
  91. package/dist/tools/cookies.js.map +1 -1
  92. package/dist/tools/diagnostics.d.ts.map +1 -1
  93. package/dist/tools/diagnostics.js +14 -0
  94. package/dist/tools/diagnostics.js.map +1 -1
  95. package/dist/tools/evaluate.d.ts +6 -5
  96. package/dist/tools/evaluate.d.ts.map +1 -1
  97. package/dist/tools/evaluate.js +102 -52
  98. package/dist/tools/evaluate.js.map +1 -1
  99. package/dist/tools/extract.d.ts.map +1 -1
  100. package/dist/tools/extract.js +178 -124
  101. package/dist/tools/extract.js.map +1 -1
  102. package/dist/tools/input.d.ts.map +1 -1
  103. package/dist/tools/input.js +623 -271
  104. package/dist/tools/input.js.map +1 -1
  105. package/dist/tools/logs.d.ts.map +1 -1
  106. package/dist/tools/logs.js +50 -11
  107. package/dist/tools/logs.js.map +1 -1
  108. package/dist/tools/manage.d.ts.map +1 -1
  109. package/dist/tools/manage.js +127 -46
  110. package/dist/tools/manage.js.map +1 -1
  111. package/dist/tools/network-sanitizer.d.ts +1 -0
  112. package/dist/tools/network-sanitizer.d.ts.map +1 -1
  113. package/dist/tools/network-sanitizer.js +30 -1
  114. package/dist/tools/network-sanitizer.js.map +1 -1
  115. package/dist/tools/page-context.d.ts +4 -3
  116. package/dist/tools/page-context.d.ts.map +1 -1
  117. package/dist/tools/page-context.js +56 -14
  118. package/dist/tools/page-context.js.map +1 -1
  119. package/dist/tools/post-condition.d.ts +1 -1
  120. package/dist/tools/post-condition.d.ts.map +1 -1
  121. package/dist/tools/post-condition.js +153 -47
  122. package/dist/tools/post-condition.js.map +1 -1
  123. package/dist/tools/schema.d.ts +7 -4
  124. package/dist/tools/schema.d.ts.map +1 -1
  125. package/dist/tools/schema.js +32 -122
  126. package/dist/tools/schema.js.map +1 -1
  127. package/dist/tools/target-diagnostics.d.ts +10 -2
  128. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  129. package/dist/tools/target-diagnostics.js +74 -21
  130. package/dist/tools/target-diagnostics.js.map +1 -1
  131. package/dist/tools/wait.d.ts.map +1 -1
  132. package/dist/tools/wait.js +108 -42
  133. package/dist/tools/wait.js.map +1 -1
  134. package/extension/dist/assets/{content.ts-C4imZ6A9.js → content.ts-BAMOcF3R.js} +1 -1
  135. package/extension/dist/assets/{content.ts-loader-CnJuCGhl.js → content.ts-loader-4F9a1EWZ.js} +1 -1
  136. package/extension/dist/assets/index.ts-B79g2ikq.js +19820 -0
  137. package/extension/dist/assets/{page-scripts-CMIY1zhd.js → page-scripts-CSxn58h1.js} +300 -410
  138. package/extension/dist/assets/{popup.html-CgtWL6Py.js → popup.html-DwwHo00N.js} +8 -6
  139. package/extension/dist/manifest.json +4 -4
  140. package/extension/dist/service-worker-loader.js +1 -1
  141. package/extension/dist/src/popup/popup.html +3 -3
  142. package/package.json +15 -7
  143. package/scripts/start-chrome.ps1 +9 -1
  144. package/extension/dist/assets/index.ts-GeHNZBml.js +0 -8972
@@ -13,14 +13,20 @@
13
13
  import { readFile, stat } from 'fs/promises';
14
14
  import { basename, extname, join } from 'path';
15
15
  import { z } from 'zod';
16
- import { CWD_PATH_PREFIX, formatErrorResponse, formatResponse, getSession, getUnifiedSession, resolveScopedOutputPath, TMP_PATH_PREFIX, writePrivateFile, } from '../core/index.js';
17
- import { sanitizeUrlRecords } from './network-sanitizer.js';
16
+ import { installDomHelpers } from '../core/dom-helpers.js';
17
+ import { ElementNotFoundError } from '../core/errors.js';
18
+ import { CWD_PATH_PREFIX, formatErrorResponse, formatResponse, getSession, getUnifiedSession, resolveScopedOutputPath, StructuredToolError, TMP_PATH_PREFIX, writePrivateFile, } from '../core/index.js';
19
+ import { DEFAULT_TIMEOUT } from '../core/types.js';
20
+ import { remainingNavigationTimeout } from '../core/utils.js';
21
+ import { sanitizePageUrls, sanitizeUrlRecord, sanitizeUrlRecords } from './network-sanitizer.js';
18
22
  import { withPageContext } from './page-context.js';
19
23
  import { assertPngFileBudget, assertScreenshotBase64Budget, assertScreenshotBudget, comparePngImages, MAX_COMPARE_PIXELS, MAX_COMPARE_PNG_BYTES, readPngHeader, } from './png.js';
20
- import { pageTargetIdSchema, resolvePageTargetId, targetToFindParams, targetZodSchema } from './schema.js';
21
- import { buildTargetDiagnostics, TargetNotFoundError, TargetTimeoutError } from './target-diagnostics.js';
24
+ import { frameZodSchema, pageTargetIdSchema, resolvePageTargetId, targetToFindParams, targetZodSchema, } from './schema.js';
25
+ import { buildTargetDiagnostics, enrichTargetError, targetLookupTimeout, TargetNotFoundError, TargetTimeoutError, } from './target-diagnostics.js';
22
26
  /** 无 output 时附录返回的最大图片数 */
23
27
  const MAX_APPENDIX_IMAGES = 20;
28
+ const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
29
+ const MAX_IMAGE_REQUEST_BYTES = 8 * 1024 * 1024;
24
30
  /**
25
31
  * extract 参数 schema
26
32
  */
@@ -80,12 +86,12 @@ const extractSchema = z
80
86
  .enum(['accessibility', 'domsnapshot'])
81
87
  .optional()
82
88
  .describe('页面状态提取模式(state 类型有效),accessibility=可访问性树(默认,与原 read_page 一致),' +
83
- 'domsnapshot=CDP DOMSnapshot 全量快照(仅 CDP 模式)'),
84
- timeout: z.number().optional().describe('等待目标元素超时'),
85
- frame: z
86
- .union([z.string(), z.number()])
89
+ 'domsnapshot=DOMSnapshot 全量快照(CDP 或受控 Extension 页面,不支持 target/frame/depth 限定)'),
90
+ timeout: z
91
+ .number()
87
92
  .optional()
88
- .describe('iframe 定位(可选,仅 Extension 模式),CSS 选择器(如 "iframe#main")或索引(如 0),不指定则在主框架操作'),
93
+ .describe('浏览器操作总预算(毫秒,默认 30000),包含排队、页面/frame 准备、目标等待、内容读取和页面元信息读取'),
94
+ frame: frameZodSchema.describe('iframe selector/索引或逐层路径(如 ["iframe#outer", 0]),省略时使用主文档'),
89
95
  })
90
96
  .superRefine((args, context) => {
91
97
  if (args.diffOutput && !args.compareWith) {
@@ -96,8 +102,15 @@ const extractSchema = z
96
102
  });
97
103
  }
98
104
  });
99
- async function handleExtract(args) {
105
+ async function handleExtract(args, signal) {
106
+ const timeout = args.timeout ?? DEFAULT_TIMEOUT;
107
+ const deadline = Date.now() + timeout;
100
108
  try {
109
+ if (args.type === 'state' &&
110
+ args.mode === 'domsnapshot' &&
111
+ [args.target, args.frame, args.depth].some((value) => value !== undefined)) {
112
+ return formatErrorResponse(new StructuredToolError('INVALID_ARGUMENT', 'domsnapshot 返回整页快照,不支持 target、frame 或 depth 限定', '局部页面状态请使用 mode="accessibility"', { actionExecuted: false }));
113
+ }
101
114
  const unifiedSession = getUnifiedSession();
102
115
  // 多 tab 并行:临时切换到指定 tab
103
116
  return await withPageContext(unifiedSession, resolvePageTargetId(args), async () => {
@@ -110,11 +123,26 @@ async function handleExtract(args) {
110
123
  const session = getSession();
111
124
  // Extension 路径:等待目标元素出现(如果指定了 target + timeout)
112
125
  if (useExtension && args.target && args.timeout !== undefined) {
113
- await waitForTargetExtension(unifiedSession, args.target, args.timeout, args.frame);
126
+ await waitForTargetExtension(unifiedSession, args.target, remainingNavigationTimeout(deadline), args.frame);
127
+ }
128
+ try {
129
+ const scopedArgs = !useExtension && args.target
130
+ ? { ...args, timeout: targetLookupTimeout(Math.max(1, deadline - Date.now())) }
131
+ : args;
132
+ return await handleExtractInFrame({ unifiedSession, session, useExtension }, scopedArgs);
114
133
  }
115
- return handleExtractInFrame({ unifiedSession, session, useExtension }, args);
116
- }); // withFrame
117
- }); // withTabId
134
+ catch (error) {
135
+ if (!useExtension && args.target && error instanceof ElementNotFoundError) {
136
+ await enrichTargetError(error, unifiedSession, args.target, {
137
+ timeout,
138
+ deadline,
139
+ frame: args.frame,
140
+ });
141
+ }
142
+ throw error;
143
+ }
144
+ }, deadline); // withFrame
145
+ }, deadline, signal); // withTabId
118
146
  }
119
147
  catch (error) {
120
148
  return formatErrorResponse(error);
@@ -221,7 +249,7 @@ async function handleAttributeExtract({ unifiedSession, session, useExtension },
221
249
  async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
222
250
  let clip;
223
251
  if (args.target && !args.clip) {
224
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(args.target);
252
+ const { selector, text, xpath, nth: nthParam, semantic, } = targetToFindParams(args.target);
225
253
  const nth = nthParam ?? 0;
226
254
  const pointTarget = 'x' in args.target && 'y' in args.target ? args.target : null;
227
255
  const found = pointTarget
@@ -229,7 +257,10 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
229
257
  ? await unifiedSession.findAtPoint(pointTarget.x, pointTarget.y, nth, args.timeout)
230
258
  : await unifiedSession
231
259
  .evaluate(`(() => {
232
- const element = document.elementFromPoint(${pointTarget.x}, ${pointTarget.y});
260
+ (${installDomHelpers.toString()})();
261
+ const element = globalThis.__mcpDomHelpers.deepElementFromPoint(
262
+ ${pointTarget.x}, ${pointTarget.y}
263
+ );
233
264
  if (!element) return null;
234
265
  const rect = element.getBoundingClientRect();
235
266
  return {
@@ -238,14 +269,14 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
238
269
  };
239
270
  })()`, undefined, args.timeout)
240
271
  .then((element) => (element && nth === 0 ? [element] : []))
241
- : await unifiedSession.find(selector, text, xpath, args.timeout);
242
- const target = found[pointTarget ? 0 : nth];
272
+ : await unifiedSession.find(selector, text, xpath, args.timeout, semantic, nth);
273
+ const target = found[0];
243
274
  if (!target || target.rect.width <= 0 || target.rect.height <= 0) {
244
275
  throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
245
276
  nth,
246
277
  timeout: args.timeout,
247
278
  frame: args.frame,
248
- matchCount: found.length,
279
+ matchCount: null,
249
280
  lastState: target ? 'zero-size' : 'not-found',
250
281
  candidates: found,
251
282
  }));
@@ -280,6 +311,9 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
280
311
  const dimensions = encodedDimensions ?? fallbackDimensions;
281
312
  const metadata = {
282
313
  format: screenshot.format,
314
+ ...(screenshot.degraded !== undefined ? { degraded: screenshot.degraded } : {}),
315
+ ...(screenshot.fallback !== undefined ? { fallback: screenshot.fallback } : {}),
316
+ ...(screenshot.limitations !== undefined ? { limitations: screenshot.limitations } : {}),
283
317
  width: dimensions?.width,
284
318
  height: dimensions?.height,
285
319
  dimensionSource: dimensions?.source,
@@ -326,23 +360,23 @@ async function handleScreenshotExtract({ unifiedSession, useExtension }, args) {
326
360
  ],
327
361
  };
328
362
  }
329
- async function handleStateExtract({ unifiedSession, useExtension }, args) {
363
+ async function handleStateExtract({ unifiedSession, session, useExtension }, args) {
330
364
  if (args.mode === 'domsnapshot') {
331
- return handleDomSnapshotState(unifiedSession, useExtension, args);
365
+ return handleDomSnapshotState(unifiedSession, args);
332
366
  }
333
367
  let refId;
334
368
  if (args.target && useExtension) {
335
369
  refId = await findTargetRefExtension(unifiedSession, args.target, args.timeout);
336
370
  if (!refId) {
337
- const { selector, text, xpath, nth: nthParam, } = targetToFindParams(args.target);
371
+ const { selector, text, xpath, nth: nthParam, semantic, } = targetToFindParams(args.target);
338
372
  const candidates = 'x' in args.target && 'y' in args.target
339
373
  ? await unifiedSession.findAtPoint(args.target.x, args.target.y)
340
- : await unifiedSession.find(selector, text, xpath, args.timeout);
374
+ : await unifiedSession.find(selector, text, xpath, args.timeout, semantic);
341
375
  throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
342
376
  nth: nthParam ?? 0,
343
377
  timeout: args.timeout,
344
378
  frame: args.frame,
345
- matchCount: candidates.length,
379
+ matchCount: candidates.length < 50 ? candidates.length : null,
346
380
  lastState: 'not-found',
347
381
  candidates,
348
382
  }));
@@ -355,30 +389,16 @@ async function handleStateExtract({ unifiedSession, useExtension }, args) {
355
389
  if (args.depth !== undefined) {
356
390
  readPageOptions.depth = args.depth;
357
391
  }
358
- const state = await unifiedSession.readPage(Object.keys(readPageOptions).length > 0 ? readPageOptions : undefined);
392
+ const state = sanitizePageUrls(useExtension
393
+ ? await unifiedSession.readPage(Object.keys(readPageOptions).length > 0 ? readPageOptions : undefined)
394
+ : await session.readPage({ target: args.target, depth: args.depth, timeout: args.timeout }));
359
395
  if (args.output) {
360
396
  const outputPath = await writeOutputFile(args.output, JSON.stringify(state, null, 2), 'utf-8');
361
397
  return formatResponse({ success: true, type: 'state', output: outputPath });
362
398
  }
363
399
  return formatResponse({ success: true, type: 'state', state });
364
400
  }
365
- async function handleDomSnapshotState(unifiedSession, useExtension, args) {
366
- if (useExtension) {
367
- return {
368
- content: [
369
- {
370
- type: 'text',
371
- text: JSON.stringify({
372
- error: {
373
- code: 'INVALID_ARGUMENT',
374
- message: 'mode=domsnapshot 仅 CDP 模式支持,Extension 模式请用默认 accessibility',
375
- },
376
- }),
377
- },
378
- ],
379
- isError: true,
380
- };
381
- }
401
+ async function handleDomSnapshotState(unifiedSession, args) {
382
402
  const snapshot = await unifiedSession.sendCdpCommand('DOMSnapshot.captureSnapshot', {
383
403
  computedStyles: ['display', 'visibility', 'opacity'],
384
404
  includePaintOrder: false,
@@ -392,15 +412,15 @@ async function handleDomSnapshotState(unifiedSession, useExtension, args) {
392
412
  }
393
413
  async function handleDiagnosticBundleExtract({ unifiedSession }, args) {
394
414
  const state = await unifiedSession.getLiveState().catch(() => null);
395
- const metadata = await unifiedSession.getMetadata();
396
- const frames = await unifiedSession.getFrames();
415
+ const metadata = sanitizePageUrls(await unifiedSession.getMetadata());
416
+ const frames = sanitizePageUrls(await unifiedSession.getFrames());
397
417
  await unifiedSession.enableConsole();
398
418
  await unifiedSession.enableNetwork();
399
419
  const consoleLogs = sanitizeUrlRecords(await unifiedSession.getConsoleLogs());
400
420
  const networkRequests = sanitizeUrlRecords(await unifiedSession.getNetworkRequests());
401
421
  const bundle = {
402
422
  schema: 'mcp-chrome.diagnosticBundle.v1',
403
- url: state?.url,
423
+ ...sanitizeUrlRecord({ url: state?.url }),
404
424
  title: state?.title,
405
425
  managed: state?.managed ?? false,
406
426
  mode: unifiedSession.getMode(),
@@ -423,12 +443,12 @@ async function handleDiagnosticBundleExtract({ unifiedSession }, args) {
423
443
  },
424
444
  };
425
445
  const summary = {
426
- url: bundle.url,
446
+ ...sanitizeUrlRecord({ url: state?.url }),
427
447
  title: bundle.title,
428
448
  managed: bundle.managed,
429
449
  mode: bundle.mode,
430
450
  frameCount: Array.isArray(frames.frames) ? frames.frames.length : 0,
431
- consoleErrors: bundle.consoleSummary.recentErrors.length,
451
+ consoleErrors: bundle.consoleSummary.recentErrors.filter((item) => item.level === 'error').length,
432
452
  networkFailures: bundle.networkSummary.recentFailures.length,
433
453
  };
434
454
  if (args.output) {
@@ -445,8 +465,8 @@ async function handleDiagnosticBundleExtract({ unifiedSession }, args) {
445
465
  });
446
466
  }
447
467
  async function handleMetadataExtract({ unifiedSession }, args) {
448
- const metadata = await unifiedSession.getMetadata();
449
- const frames = await unifiedSession.getFrames();
468
+ const metadata = sanitizePageUrls(await unifiedSession.getMetadata());
469
+ const frames = sanitizePageUrls(await unifiedSession.getFrames());
450
470
  if (args.output) {
451
471
  const outputPath = await writeOutputFile(args.output, JSON.stringify({ ...metadata, ...frames }, null, 2), 'utf-8');
452
472
  return formatResponse({ success: true, type: 'metadata', output: outputPath });
@@ -469,8 +489,10 @@ function invalidExtractTypeResponse(args) {
469
489
  // ==================== HTML + 图片提取 ====================
470
490
  /** 写入文件前自动创建父目录,并收敛到受控范围 */
471
491
  async function writeOutputFile(path, data, encoding) {
492
+ const session = getUnifiedSession();
493
+ session.assertRequestActive();
472
494
  const resolvedPath = await resolveScopedOutputPath(path, 'mcp-chrome');
473
- await writePrivateFile(resolvedPath.absolutePath, data, encoding);
495
+ await writePrivateFile(resolvedPath.absolutePath, data, encoding, () => session.assertRequestActive());
474
496
  return resolvedPath.absolutePath;
475
497
  }
476
498
  async function getPageScrollOffset(unifiedSession, timeout) {
@@ -613,18 +635,18 @@ function readWebpDimensions(buffer) {
613
635
  async function handleHtmlWithImages(unifiedSession, session, useExtension, args) {
614
636
  let result;
615
637
  if (args.target) {
616
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(args.target);
638
+ const { selector, text, xpath, nth: nthParam, semantic, } = targetToFindParams(args.target);
617
639
  const nth = nthParam ?? 0;
618
640
  if (useExtension) {
619
641
  const refId = await findTargetRefExtension(unifiedSession, args.target, args.timeout);
620
642
  if (!refId) {
621
643
  const matches = 'x' in args.target && 'y' in args.target
622
644
  ? await unifiedSession.findAtPoint(args.target.x, args.target.y)
623
- : await unifiedSession.find(selector, text, xpath, args.timeout);
645
+ : await unifiedSession.find(selector, text, xpath, args.timeout, semantic);
624
646
  throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
625
647
  nth,
626
648
  timeout: args.timeout,
627
- matchCount: matches.length,
649
+ matchCount: matches.length < 50 ? matches.length : null,
628
650
  lastState: 'not-found',
629
651
  candidates: matches,
630
652
  }));
@@ -632,12 +654,12 @@ async function handleHtmlWithImages(unifiedSession, session, useExtension, args)
632
654
  result = await unifiedSession.getHtmlWithImagesByRef(refId);
633
655
  }
634
656
  else {
635
- const matches = await unifiedSession.find(selector, text, xpath, args.timeout);
636
- if (matches.length <= nth) {
657
+ const matches = await unifiedSession.find(selector, text, xpath, args.timeout, semantic, nth);
658
+ if (matches.length === 0) {
637
659
  throw new TargetNotFoundError(await buildTargetDiagnostics(unifiedSession, args.target, {
638
660
  nth,
639
661
  timeout: args.timeout,
640
- matchCount: matches.length,
662
+ matchCount: null,
641
663
  lastState: 'not-found',
642
664
  candidates: matches,
643
665
  }));
@@ -669,20 +691,25 @@ async function handleHtmlWithImages(unifiedSession, session, useExtension, args)
669
691
  }
670
692
  // data 模式:获取图片数据
671
693
  const appendixMode = !args.output;
672
- const imageDataList = await fetchImageData(unifiedSession, result.images, appendixMode ? MAX_APPENDIX_IMAGES : undefined);
694
+ const imageData = fetchImageData(unifiedSession, result.images, appendixMode ? MAX_APPENDIX_IMAGES : undefined, !appendixMode);
673
695
  if (args.output) {
674
696
  const outputDir = (await resolveScopedOutputPath(args.output, 'mcp-chrome')).absolutePath;
675
- // 写入目录
676
- await writeImageDirectory(outputDir, result.html, result.images, imageDataList);
697
+ const omittedImages = await writeImageDirectory(outputDir, result.html, result.images, imageData, () => unifiedSession.assertRequestActive());
677
698
  return formatResponse({
678
699
  success: true,
679
700
  type: 'html',
680
701
  output: outputDir,
681
702
  imageCount: result.images.length,
682
703
  index: join(outputDir, 'index.json'),
704
+ omittedImages,
705
+ imageByteLimit: MAX_IMAGE_BYTES,
706
+ imageRequestByteLimit: MAX_IMAGE_REQUEST_BYTES,
683
707
  });
684
708
  }
685
- // 无 output:MCP 附录方式返回
709
+ const imageDataList = [];
710
+ for await (const data of imageData) {
711
+ imageDataList.push(data);
712
+ }
686
713
  return buildImageAppendixResponse(result.html, result.images, imageDataList);
687
714
  }
688
715
  async function extractHtmlWithImagesByTarget(unifiedSession, selector, text, xpath, nth, timeout) {
@@ -771,68 +798,73 @@ async function extractHtmlWithImagesCdp(session, selector, timeout) {
771
798
  *
772
799
  * 策略:
773
800
  * 1. data: URL → 直接解码
774
- * 2. CDP Page.getResourceContent(批量) → 从浏览器缓存读取(零网络请求)
801
+ * 2. CDP Page.getResourceContent → 逐图读取浏览器缓存(零网络请求)
775
802
  *
776
803
  * @param unifiedSession 会话管理器,用于 CDP 资源获取
777
804
  * @param images 图片元信息列表
778
- * @param limit 最多获取前 N 张图片数据(附录模式限流),超出的返回 null
805
+ * @param limit 最多获取前 N 张图片数据(附录模式限流),超出的图片 base64 为 null
806
+ * @param skipDuplicates 是否跳过重复图片来源
779
807
  */
780
- async function fetchImageData(unifiedSession, images, limit) {
781
- const effectiveLimit = limit ?? images.length;
782
- // 第一趟:解析 data: URL + 收集需要 CDP 获取的 URL(去重)
783
- const preResolved = [];
784
- const cdpUrlSet = new Set();
785
- for (let i = 0; i < images.length; i++) {
808
+ async function* fetchImageData(unifiedSession, images, limit = images.length, skipDuplicates = false) {
809
+ let usedBytes = 0;
810
+ const sources = new Set();
811
+ for (let i = 0; i < images.length; ++i) {
812
+ unifiedSession.assertRequestActive();
786
813
  const img = images[i];
787
- const effectiveSrc = img.src || img.dataSrc;
788
- if (i >= effectiveLimit || !effectiveSrc) {
789
- preResolved.push({ base64: null, mimeType: 'image/png' });
814
+ const src = img.src || img.dataSrc;
815
+ const mimeType = guessMimeType(src);
816
+ if (skipDuplicates && sources.has(src)) {
817
+ yield { base64: null, mimeType };
790
818
  continue;
791
819
  }
792
- if (effectiveSrc.startsWith('data:')) {
793
- const match = effectiveSrc.match(/^data:(?<mime>[^;]+);base64,(?<data>.+)$/);
794
- preResolved.push(match
795
- ? { base64: match.groups.data, mimeType: match.groups.mime }
796
- : { base64: null, mimeType: 'image/png' });
820
+ if (i >= limit) {
821
+ yield { base64: null, mimeType, omitted: 'appendix-limit' };
797
822
  continue;
798
823
  }
799
- if (!effectiveSrc.startsWith('http')) {
800
- preResolved.push({ base64: null, mimeType: guessMimeType(effectiveSrc) });
824
+ if (usedBytes >= MAX_IMAGE_REQUEST_BYTES) {
825
+ yield { base64: null, mimeType, omitted: 'request-byte-limit' };
801
826
  continue;
802
827
  }
803
- // 只有 src 非空(浏览器实际请求过的)才走 CDP 缓存
804
- if (img.src) {
805
- cdpUrlSet.add(img.src);
828
+ let base64;
829
+ let resolvedMime = mimeType;
830
+ if (src.startsWith('data:')) {
831
+ const match = /^data:(?<mimeType>[^;]+);base64,/.exec(src);
832
+ if (match) {
833
+ resolvedMime = match[1];
834
+ base64 = src.slice(match[0].length);
835
+ }
806
836
  }
807
- preResolved.push(null); // 需要进一步获取
808
- }
809
- // 第二趟:批量 CDP 获取
810
- const cdpResults = await unifiedSession.getResourceContentBatch([...cdpUrlSet]);
811
- // 第三趟:组装结果,CDP 未命中的返回 null
812
- const results = [];
813
- for (let i = 0; i < images.length; i++) {
814
- if (preResolved[i] !== null) {
815
- results.push(preResolved[i]);
837
+ else if (img.src && /^https?:/.test(src)) {
838
+ const resource = (await unifiedSession.getResourceContentBatch([img.src], 1)).get(img.src);
839
+ unifiedSession.assertRequestActive();
840
+ if (resource) {
841
+ if (!resource.base64Encoded && Buffer.byteLength(resource.content) > MAX_IMAGE_BYTES) {
842
+ yield { base64: null, mimeType, omitted: 'image-byte-limit' };
843
+ continue;
844
+ }
845
+ base64 = resource.base64Encoded ? resource.content : Buffer.from(resource.content).toString('base64');
846
+ }
847
+ }
848
+ if (base64 === undefined) {
849
+ yield { base64: null, mimeType: resolvedMime, omitted: 'unavailable' };
816
850
  continue;
817
851
  }
818
- const img = images[i];
819
- const effectiveSrc = img.src || img.dataSrc;
820
- const mimeType = guessMimeType(effectiveSrc);
821
- // 尝试 CDP 缓存
822
- if (img.src && cdpResults.has(img.src)) {
823
- const resource = cdpResults.get(img.src);
824
- if (resource.base64Encoded) {
825
- results.push({ base64: resource.content, mimeType });
826
- }
827
- else {
828
- results.push({ base64: Buffer.from(resource.content).toString('base64'), mimeType });
829
- }
852
+ const bytes = Buffer.byteLength(base64, 'base64');
853
+ const omitted = bytes > MAX_IMAGE_BYTES
854
+ ? 'image-byte-limit'
855
+ : usedBytes + bytes > MAX_IMAGE_REQUEST_BYTES
856
+ ? 'request-byte-limit'
857
+ : undefined;
858
+ if (omitted) {
859
+ yield { base64: null, mimeType: resolvedMime, omitted };
830
860
  continue;
831
861
  }
832
- // CDP 缓存未命中,不使用 Node.js fetch(避免绕过浏览器同源策略)
833
- results.push({ base64: null, mimeType });
862
+ usedBytes += bytes;
863
+ if (skipDuplicates) {
864
+ sources.add(src);
865
+ }
866
+ yield { base64, mimeType: resolvedMime };
834
867
  }
835
- return results;
836
868
  }
837
869
  /**
838
870
  * 写入图片目录
@@ -845,18 +877,20 @@ async function fetchImageData(unifiedSession, images, limit) {
845
877
  * 1-icon.png
846
878
  * index.json
847
879
  */
848
- async function writeImageDirectory(outputDir, html, images, imageDataList) {
880
+ async function writeImageDirectory(outputDir, html, images, imageDataList, assertActive) {
849
881
  const imagesDir = join(outputDir, 'images');
850
882
  // 写入 HTML
851
- await writePrivateFile(join(outputDir, 'content.html'), html, 'utf-8');
883
+ await writePrivateFile(join(outputDir, 'content.html'), html, 'utf-8', assertActive);
852
884
  // 写入图片文件 + 构建索引(相同 src 去重)
853
885
  const indexEntries = [];
854
886
  const writtenFiles = new Map(); // src → file path
855
- for (let i = 0; i < images.length; i++) {
887
+ let i = 0;
888
+ let omittedImages = 0;
889
+ for await (const data of imageDataList) {
890
+ assertActive?.();
856
891
  const img = images[i];
857
- const data = imageDataList[i];
858
892
  const src = img.src || img.dataSrc;
859
- let file = null;
893
+ let file = writtenFiles.get(src) ?? null;
860
894
  if (data.base64) {
861
895
  // 相同 src 复用已写入的文件
862
896
  const existing = writtenFiles.get(src);
@@ -868,7 +902,7 @@ async function writeImageDirectory(outputDir, html, images, imageDataList) {
868
902
  const safeName = sanitizeFilename(src);
869
903
  const filename = `${i}-${safeName}${ext}`;
870
904
  file = `images/${filename}`;
871
- await writePrivateFile(join(imagesDir, filename), Buffer.from(data.base64, 'base64'));
905
+ await writePrivateFile(join(imagesDir, filename), Buffer.from(data.base64, 'base64'), undefined, assertActive);
872
906
  writtenFiles.set(src, file);
873
907
  }
874
908
  }
@@ -879,13 +913,19 @@ async function writeImageDirectory(outputDir, html, images, imageDataList) {
879
913
  width: img.width,
880
914
  height: img.height,
881
915
  file,
916
+ ...(data.omitted ? { omitted: data.omitted } : {}),
882
917
  });
918
+ if (data.omitted) {
919
+ ++omittedImages;
920
+ }
921
+ ++i;
883
922
  }
884
923
  // 写入索引
885
924
  await writePrivateFile(join(outputDir, 'index.json'), JSON.stringify({
886
925
  html: 'content.html',
887
926
  images: indexEntries,
888
- }, null, 2), 'utf-8');
927
+ }, null, 2), 'utf-8', assertActive);
928
+ return omittedImages;
889
929
  }
890
930
  /**
891
931
  * 构造附录式 MCP 响应
@@ -907,6 +947,9 @@ function buildImageAppendixResponse(html, images, imageDataList) {
907
947
  type: 'html',
908
948
  content: html,
909
949
  imageCount: images.length,
950
+ imageByteLimit: MAX_IMAGE_BYTES,
951
+ imageRequestByteLimit: MAX_IMAGE_REQUEST_BYTES,
952
+ omittedImages: imageDataList.filter((image) => image.omitted).length,
910
953
  }),
911
954
  });
912
955
  if (images.length === 0) {
@@ -923,7 +966,11 @@ function buildImageAppendixResponse(html, images, imageDataList) {
923
966
  // 图片标注
924
967
  const sizeStr = img.naturalWidth ? `${img.naturalWidth}×${img.naturalHeight}` : `${img.width}×${img.height}`;
925
968
  const altStr = img.alt ? ` alt="${img.alt}"` : '';
926
- content.push({ type: 'text', text: `\n[${img.index}] ${effectiveSrc}${altStr} ${sizeStr}` });
969
+ content.push({
970
+ type: 'text',
971
+ text: `\n[${img.index}] ${effectiveSrc}${altStr} ${sizeStr}` +
972
+ (data.omitted ? ` omitted=${data.omitted}` : ''),
973
+ });
927
974
  // 在限制内且有数据时附带图片(SVG 等不支持的格式跳过 image block)
928
975
  if (i < limit && data.base64 && SUPPORTED_IMAGE_MIMES.has(data.mimeType)) {
929
976
  content.push({ type: 'image', data: data.base64, mimeType: data.mimeType });
@@ -932,7 +979,7 @@ function buildImageAppendixResponse(html, images, imageDataList) {
932
979
  if (images.length > MAX_APPENDIX_IMAGES) {
933
980
  content.push({
934
981
  type: 'text',
935
- text: `\n(共 ${images.length} 张图片,仅前 ${MAX_APPENDIX_IMAGES} 张附带数据,使用 output 参数导出全部图片)`,
982
+ text: `\n(共 ${images.length} 张图片,仅前 ${MAX_APPENDIX_IMAGES} 张附带数据,使用 output 参数导出图片,字节预算仍适用)`,
936
983
  });
937
984
  }
938
985
  return { content };
@@ -1038,10 +1085,10 @@ async function extractAttribute(session, target, attribute, timeout) {
1038
1085
  }`);
1039
1086
  }
1040
1087
  async function findTargetRefExtension(unifiedSession, target, timeout) {
1041
- const { selector, text, xpath, nth } = targetToFindParams(target);
1088
+ const { selector, text, xpath, nth, semantic } = targetToFindParams(target);
1042
1089
  const matches = 'x' in target && 'y' in target
1043
1090
  ? await unifiedSession.findAtPoint(target.x, target.y, nth ?? 0, timeout)
1044
- : await unifiedSession.find(selector, text, xpath, timeout, nth ?? 0);
1091
+ : await unifiedSession.find(selector, text, xpath, timeout, semantic, nth ?? 0);
1045
1092
  return matches[0]?.refId;
1046
1093
  }
1047
1094
  /**
@@ -1089,12 +1136,13 @@ async function waitForTargetExtension(unifiedSession, target, timeout, frame) {
1089
1136
  if ('x' in target && 'y' in target) {
1090
1137
  return;
1091
1138
  }
1139
+ unifiedSession.preserveTargetAfterLookup();
1092
1140
  const startTime = Date.now();
1093
1141
  const retryDelay = 100;
1094
- const { selector, text, xpath, nth: nthParam } = targetToFindParams(target);
1142
+ const { selector, text, xpath, nth: nthParam, semantic } = targetToFindParams(target);
1095
1143
  const nth = nthParam ?? 0;
1096
1144
  let lastError = null;
1097
- let matchCount = 0;
1145
+ let matchCount = null;
1098
1146
  let candidates = [];
1099
1147
  while (true) {
1100
1148
  const elapsed = Date.now() - startTime;
@@ -1102,6 +1150,7 @@ async function waitForTargetExtension(unifiedSession, target, timeout, frame) {
1102
1150
  throw new TargetTimeoutError(await buildTargetDiagnostics(unifiedSession, target, {
1103
1151
  nth,
1104
1152
  timeout,
1153
+ deadline: startTime + timeout,
1105
1154
  frame,
1106
1155
  matchCount,
1107
1156
  lastState: 'attached',
@@ -1116,16 +1165,21 @@ async function waitForTargetExtension(unifiedSession, target, timeout, frame) {
1116
1165
  continue;
1117
1166
  }
1118
1167
  try {
1119
- const indexed = nth >= 50;
1120
- const elements = await unifiedSession.find(selector, text, xpath, remaining, indexed ? nth : undefined);
1121
- matchCount = elements.length;
1168
+ const elements = await unifiedSession.find(selector, text, xpath, remaining, semantic);
1169
+ matchCount = elements.length < 50 ? elements.length : null;
1122
1170
  candidates = elements;
1123
- if (indexed ? elements.length > 0 : elements.length > nth) {
1171
+ const selected = nth < 50
1172
+ ? elements[nth]
1173
+ : (await unifiedSession.find(selector, text, xpath, Math.max(1, timeout - (Date.now() - startTime)), semantic, nth))[0];
1174
+ if (selected) {
1124
1175
  return;
1125
1176
  }
1126
1177
  }
1127
1178
  catch (err) {
1128
- // 暂时性错误(RPC 超时、发送失败、连接断开)可重试,其他确定性错误立即抛出
1179
+ if (err instanceof StructuredToolError && err.context.actionStatus === 'unknown') {
1180
+ throw err;
1181
+ }
1182
+ // 仅重试尚未派发成功的暂时性错误
1129
1183
  if (err instanceof Error &&
1130
1184
  /Request timeout|Failed to send|disconnect|未连接|stopped|replaced/i.test(err.message)) {
1131
1185
  lastError = err;
@@ -1150,6 +1204,6 @@ export function registerExtractTool(server) {
1150
1204
  server.registerTool('extract', {
1151
1205
  description: `提取页面内容:文本、HTML(可附带图片)、iframe HTML、属性、截图、状态、页面元信息`,
1152
1206
  inputSchema: extractSchema,
1153
- }, (args) => handleExtract(args));
1207
+ }, (args, extra) => handleExtract(args, extra?.signal));
1154
1208
  }
1155
1209
  //# sourceMappingURL=extract.js.map