@pyrokine/mcp-chrome 3.0.0 → 3.0.1

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 (65) hide show
  1. package/README.md +119 -38
  2. package/README_zh.md +165 -110
  3. package/dist/core/browser-driver.d.ts +5 -4
  4. package/dist/core/browser-driver.d.ts.map +1 -1
  5. package/dist/core/browser-driver.js.map +1 -1
  6. package/dist/core/errors.d.ts +6 -4
  7. package/dist/core/errors.d.ts.map +1 -1
  8. package/dist/core/errors.js +14 -8
  9. package/dist/core/errors.js.map +1 -1
  10. package/dist/core/locator.d.ts +7 -0
  11. package/dist/core/locator.d.ts.map +1 -1
  12. package/dist/core/locator.js +48 -25
  13. package/dist/core/locator.js.map +1 -1
  14. package/dist/core/session.d.ts +6 -4
  15. package/dist/core/session.d.ts.map +1 -1
  16. package/dist/core/session.js +58 -23
  17. package/dist/core/session.js.map +1 -1
  18. package/dist/core/unified-session.d.ts +11 -8
  19. package/dist/core/unified-session.d.ts.map +1 -1
  20. package/dist/core/unified-session.js +71 -27
  21. package/dist/core/unified-session.js.map +1 -1
  22. package/dist/extension/bridge.d.ts +3 -3
  23. package/dist/extension/bridge.d.ts.map +1 -1
  24. package/dist/extension/bridge.js +50 -20
  25. package/dist/extension/bridge.js.map +1 -1
  26. package/dist/extension/http-server.d.ts.map +1 -1
  27. package/dist/extension/http-server.js +9 -0
  28. package/dist/extension/http-server.js.map +1 -1
  29. package/dist/tools/browse.d.ts.map +1 -1
  30. package/dist/tools/browse.js +10 -4
  31. package/dist/tools/browse.js.map +1 -1
  32. package/dist/tools/challenge.d.ts.map +1 -1
  33. package/dist/tools/challenge.js +12 -15
  34. package/dist/tools/challenge.js.map +1 -1
  35. package/dist/tools/evaluate.d.ts.map +1 -1
  36. package/dist/tools/evaluate.js +10 -0
  37. package/dist/tools/evaluate.js.map +1 -1
  38. package/dist/tools/extract.d.ts.map +1 -1
  39. package/dist/tools/extract.js +30 -22
  40. package/dist/tools/extract.js.map +1 -1
  41. package/dist/tools/input.d.ts.map +1 -1
  42. package/dist/tools/input.js +83 -57
  43. package/dist/tools/input.js.map +1 -1
  44. package/dist/tools/manage.d.ts.map +1 -1
  45. package/dist/tools/manage.js +16 -30
  46. package/dist/tools/manage.js.map +1 -1
  47. package/dist/tools/post-condition.d.ts.map +1 -1
  48. package/dist/tools/post-condition.js +23 -9
  49. package/dist/tools/post-condition.js.map +1 -1
  50. package/dist/tools/target-diagnostics.d.ts +9 -1
  51. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  52. package/dist/tools/target-diagnostics.js +60 -17
  53. package/dist/tools/target-diagnostics.js.map +1 -1
  54. package/dist/tools/wait.d.ts.map +1 -1
  55. package/dist/tools/wait.js +19 -7
  56. package/dist/tools/wait.js.map +1 -1
  57. package/extension/dist/assets/{content.ts-loader-CnJuCGhl.js → content.ts-loader-DUWbDHRS.js} +1 -1
  58. package/extension/dist/assets/{content.ts-C4imZ6A9.js → content.ts-qe6IB5DK.js} +1 -1
  59. package/extension/dist/assets/{index.ts-GeHNZBml.js → index.ts-D7_LCUoV.js} +559 -212
  60. package/extension/dist/assets/{page-scripts-CMIY1zhd.js → page-scripts-D508WLkW.js} +50 -51
  61. package/extension/dist/assets/{popup.html-CgtWL6Py.js → popup.html-B-eVq48O.js} +6 -4
  62. package/extension/dist/manifest.json +4 -4
  63. package/extension/dist/service-worker-loader.js +1 -1
  64. package/extension/dist/src/popup/popup.html +1 -1
  65. package/package.json +12 -6
@@ -1,4 +1,4 @@
1
- import { C as simulateMouseClick, S as simulateKeyboardType, _ as performClick, a as extractHtml, b as performType, c as extractText, d as getComputedStyleFromElement, f as injectStealthScripts, g as performActionableClick, h as installFrameProbeListener, i as extractAttribute, l as findElements, m as installActionabilityHelpers, n as dispatchInputToElement, o as extractHtmlWithImages, p as inspectChallengePage, r as executeCode, s as extractMetadata, t as checkActionability, u as generateAccessibilityTree, v as performDragAndDrop, w as simulateMouseEvent, x as simulateKeyEvent, y as performScroll } from "./page-scripts-CMIY1zhd.js";
1
+ import { C as simulateMouseClick, S as simulateKeyboardType, _ as performClick, a as extractHtml, b as performType, c as extractText, d as getComputedStyleFromElement, f as injectStealthScripts, g as performActionableClick, h as installFrameProbeListener, i as extractAttribute, l as findElements, m as installActionabilityHelpers, n as dispatchInputToElement, o as extractHtmlWithImages, p as inspectChallengePage, r as executeCode, s as extractMetadata, t as checkActionability, u as generateAccessibilityTree, v as performDragAndDrop, w as simulateMouseEvent, x as simulateKeyEvent, y as performScroll } from "./page-scripts-D508WLkW.js";
2
2
  //#region src/types/expected-errors.ts
3
3
  /**
4
4
  * 预期的操作错误(tab 关闭、超时、元素/frame 未找到、受限 URL、路径越界等)
@@ -17,6 +17,68 @@ var ExpectedOperationError = class extends Error {
17
17
  function isExpectedOperationError(err) {
18
18
  return err instanceof ExpectedOperationError;
19
19
  }
20
+ var EXPECTED_DEBUGGER_PATTERNS = [
21
+ /Cannot access a chrome:\/\//i,
22
+ /Cannot access a chrome-extension:\/\//i,
23
+ /Cannot attach to .* tab/i,
24
+ /Inspected target navigated or closed/i,
25
+ /^No tab with (?:given )?id\b/i,
26
+ /Detached while handling command/i,
27
+ /Cannot find context with specified id/i,
28
+ /Execution context was destroyed/i
29
+ ];
30
+ function wrapDebuggerError(error, context) {
31
+ if (error instanceof ExpectedOperationError) return error;
32
+ const raw = error instanceof Error ? error.message : String(error);
33
+ let message = raw;
34
+ let nativeCode;
35
+ try {
36
+ const parsed = JSON.parse(raw);
37
+ if (typeof parsed?.message === "string" && typeof parsed.code === "number") {
38
+ message = parsed.message;
39
+ nativeCode = parsed.code;
40
+ }
41
+ } catch {}
42
+ let reason;
43
+ let suggestion;
44
+ if (/^Debugger agent is not enabled\.?$/i.test(message)) {
45
+ reason = "domain_not_enabled";
46
+ suggestion = "在当前调试会话显式启用 Debugger 域后,再请求该方法";
47
+ } else if (/^No script for id:/i.test(message)) {
48
+ reason = "resource_not_found";
49
+ suggestion = "从当前页面及调试会话重新读取 scriptId,再请求脚本内容";
50
+ } else if (/^Cannot(?: not)? access browser-level commands\.?$/i.test(message)) {
51
+ reason = "browser_command_unavailable";
52
+ suggestion = "该命令需要浏览器级 CDP 会话,请显式连接支持该命令的调试目标";
53
+ } else if (context.phase === "command" && message === "Not allowed") {
54
+ reason = "command_not_allowed";
55
+ suggestion = "当前调试会话拒绝此方法,请检查命令所需的权限和调试目标";
56
+ } else if (/^(?:Object couldn't be returned by value|Object reference chain is too long)\.?$/i.test(message)) {
57
+ reason = "result_not_serializable";
58
+ suggestion = "先检查动作产生的状态;再次调用时返回可序列化值,原脚本不会自动重放";
59
+ } else if (nativeCode === -32601 || /^'[^']+' wasn't found\.?$/i.test(message)) {
60
+ reason = "method_not_found";
61
+ suggestion = "检查当前调试协议支持的方法名,方法缺失不表示整个域不可用";
62
+ } else if (EXPECTED_DEBUGGER_PATTERNS.some((pattern) => pattern.test(message))) {
63
+ reason = "target_unavailable";
64
+ suggestion = "重新读取目标页面和调试上下文,再提交操作";
65
+ } else return error instanceof Error ? error : new Error(raw);
66
+ return new ExpectedOperationError(JSON.stringify({ error: {
67
+ code: "CDP_ERROR",
68
+ message: `${context.method ?? `chrome.debugger.${context.phase}`}: ${message}`,
69
+ suggestion,
70
+ context: {
71
+ nativeSource: "chrome.debugger",
72
+ targetId: String(context.tabId),
73
+ method: context.method,
74
+ phase: context.phase,
75
+ nativeMessage: message,
76
+ ...nativeCode !== void 0 ? { nativeCode } : {},
77
+ reason,
78
+ ...context.frameContext ? { frameContext: context.frameContext } : {}
79
+ }
80
+ } }));
81
+ }
20
82
  //#endregion
21
83
  //#region src/background/page-revision.ts
22
84
  var epoch = crypto.randomUUID();
@@ -30,8 +92,17 @@ function advancePageRevision(tabId) {
30
92
  function forgetPageRevision(tabId) {
31
93
  revisions.delete(tabId);
32
94
  }
95
+ async function getExistingTab(tabId) {
96
+ try {
97
+ return await chrome.tabs.get(tabId);
98
+ } catch (error) {
99
+ const message = error instanceof Error ? error.message : String(error);
100
+ if (message === `No tab with id: ${tabId}.` || message === `No tab with id: ${tabId}`) throw new ExpectedOperationError(message);
101
+ throw error;
102
+ }
103
+ }
33
104
  async function pageSnapshot(tabId) {
34
- const tab = await chrome.tabs.get(tabId);
105
+ const tab = await getExistingTab(tabId);
35
106
  return {
36
107
  targetId: String(tabId),
37
108
  url: tab.url ?? "",
@@ -73,7 +144,7 @@ async function update(instanceId, action) {
73
144
  }
74
145
  async function readGrantDocumentId(instanceId, tabId) {
75
146
  if (!instanceId || revokedInstances.has(instanceId)) return null;
76
- const tab = await chrome.tabs.get(tabId);
147
+ const tab = await getExistingTab(tabId);
77
148
  const frame = await chrome.webNavigation.getFrame({
78
149
  tabId,
79
150
  frameId: 0
@@ -87,7 +158,7 @@ async function readGrantDocumentId(instanceId, tabId) {
87
158
  let documentId = null;
88
159
  await update(instanceId, async () => {
89
160
  if (revokedInstances.has(instanceId)) return;
90
- const currentTab = await chrome.tabs.get(tabId);
161
+ const currentTab = await getExistingTab(tabId);
91
162
  const currentFrame = await chrome.webNavigation.getFrame({
92
163
  tabId,
93
164
  frameId: 0
@@ -109,14 +180,14 @@ async function setReadGrant(instanceId, tabId, allow, expected) {
109
180
  await update(instanceId, async () => {
110
181
  const grants = (revokedInstances.has(instanceId) ? [] : await getGrants(instanceId)).filter((grant) => grant.tabId !== tabId);
111
182
  if (allow) {
112
- const tab = await chrome.tabs.get(tabId);
183
+ const tab = await getExistingTab(tabId);
113
184
  const frame = await chrome.webNavigation.getFrame({
114
185
  tabId,
115
186
  frameId: 0
116
187
  });
117
188
  if (!frame?.documentId) throw new Error("无法确认当前页面身份,未授予只读权限");
118
189
  const revision = pageRevision(tabId);
119
- const currentTab = await chrome.tabs.get(tabId);
190
+ const currentTab = await getExistingTab(tabId);
120
191
  const currentFrame = await chrome.webNavigation.getFrame({
121
192
  tabId,
122
193
  frameId: 0
@@ -146,11 +217,15 @@ async function revokeTabReadGrants(tabId) {
146
217
  /**
147
218
  * Managed tab/window 状态与 storage 恢复
148
219
  */
149
- var STORAGE_KEY = "mcp_managed_tab_ids";
220
+ var LEGACY_STORAGE_KEY = "mcp_managed_tab_ids";
221
+ var STORAGE_KEY = "mcp_managed_tabs_v1";
222
+ var GENERATION_KEY = "mcp_managed_tabs_generation_v1";
150
223
  var mcpTabGroupId = null;
151
224
  var mcpWindowId = null;
152
225
  var storageUpdate = Promise.resolve();
153
- var managedTabIds = /* @__PURE__ */ new Set();
226
+ var initialization = null;
227
+ var generation = "";
228
+ var managedTabs = /* @__PURE__ */ new Map();
154
229
  function getMcpTabGroupId() {
155
230
  return mcpTabGroupId;
156
231
  }
@@ -163,40 +238,98 @@ function setMcpTabGroupId(groupId) {
163
238
  function setMcpWindowId(windowId) {
164
239
  mcpWindowId = windowId;
165
240
  }
241
+ async function documentIdForTab(tabId) {
242
+ try {
243
+ const frame = await chrome.webNavigation.getFrame({
244
+ tabId,
245
+ frameId: 0
246
+ });
247
+ if (frame?.documentId) return frame.documentId;
248
+ } catch (error) {
249
+ console.warn(`[MCP] Managed page ${tabId} has no document identity; automatic recovery after Extension reload is unavailable:`, error);
250
+ return null;
251
+ }
252
+ console.warn(`[MCP] Managed page ${tabId} has no document identity; automatic recovery after Extension reload is unavailable`);
253
+ return null;
254
+ }
255
+ async function commitManagedTabs(tabs, sessionGeneration) {
256
+ const snapshot = {
257
+ version: 1,
258
+ generation: sessionGeneration,
259
+ tabs: [...tabs].map(([tabId, documentId]) => ({
260
+ tabId,
261
+ documentId
262
+ }))
263
+ };
264
+ await chrome.storage.local.set({ [STORAGE_KEY]: snapshot });
265
+ managedTabs = tabs;
266
+ generation = sessionGeneration;
267
+ }
166
268
  async function updateManagedTabs(update) {
167
269
  const operation = storageUpdate.catch(() => {}).then(async () => {
168
- const next = new Set(managedTabIds);
169
- await update(next);
170
- await chrome.storage.session.set({ [STORAGE_KEY]: [...next] });
171
- managedTabIds.clear();
172
- for (const id of next) managedTabIds.add(id);
270
+ await restoreManagedTabs();
271
+ const next = new Map(managedTabs);
272
+ if (await update(next)) await commitManagedTabs(next, generation);
173
273
  });
174
274
  storageUpdate = operation;
175
275
  await operation;
176
276
  }
177
277
  async function markManagedTab(tabId) {
178
- await updateManagedTabs((ids) => {
179
- ids.add(tabId);
278
+ await updateManagedTabs(async (tabs) => {
279
+ tabs.set(tabId, await documentIdForTab(tabId));
280
+ return true;
180
281
  });
181
282
  }
182
283
  async function unmarkManagedTab(tabId) {
183
- await updateManagedTabs((ids) => {
184
- ids.delete(tabId);
284
+ await updateManagedTabs((tabs) => tabs.delete(tabId));
285
+ }
286
+ async function updateManagedTabDocument(tabId) {
287
+ await updateManagedTabs(async (tabs) => {
288
+ if (!tabs.has(tabId)) return false;
289
+ tabs.set(tabId, await documentIdForTab(tabId));
290
+ return true;
185
291
  });
186
292
  }
187
293
  function isManagedTab(tab) {
188
- return tab.id !== void 0 && managedTabIds.has(tab.id);
189
- }
190
- /** Extension 启动时调用,只恢复当前浏览器会话中仍存在的受控 tab */
191
- async function restoreManagedTabs() {
192
- await updateManagedTabs(async (ids) => {
193
- const result = await chrome.storage.session.get(STORAGE_KEY);
194
- const stored = Array.isArray(result[STORAGE_KEY]) ? result[STORAGE_KEY] : [];
195
- const tabs = await chrome.tabs.query({});
196
- const existingIds = new Set(tabs.map((tab) => tab.id));
197
- ids.clear();
198
- for (const id of stored) if (typeof id === "number" && Number.isSafeInteger(id) && id >= 0 && existingIds.has(id)) ids.add(id);
199
- });
294
+ return tab.id !== void 0 && managedTabs.has(tab.id);
295
+ }
296
+ /** 同代际恢复现有 tab,跨代际只恢复原生 documentId 匹配的页面 */
297
+ function restoreManagedTabs() {
298
+ if (initialization === null) {
299
+ initialization = (async () => {
300
+ const session = await chrome.storage.session.get([GENERATION_KEY, LEGACY_STORAGE_KEY]);
301
+ const stored = (await chrome.storage.local.get(STORAGE_KEY))[STORAGE_KEY];
302
+ if (stored !== void 0 && (stored === null || stored.version !== 1 || typeof stored.generation !== "string" || !stored.generation || !Array.isArray(stored.tabs))) throw new Error("Invalid managed page storage snapshot");
303
+ const sessionGeneration = typeof session[GENERATION_KEY] === "string" && session[GENERATION_KEY] ? session[GENERATION_KEY] : crypto.randomUUID();
304
+ if (session[GENERATION_KEY] !== sessionGeneration) await chrome.storage.session.set({ [GENERATION_KEY]: sessionGeneration });
305
+ const existingIds = new Set((await chrome.tabs.query({})).map((tab) => tab.id));
306
+ const legacy = Array.isArray(session[LEGACY_STORAGE_KEY]) ? session[LEGACY_STORAGE_KEY] : [];
307
+ const records = stored?.tabs ?? legacy.filter((id) => typeof id === "number").map((tabId) => ({
308
+ tabId,
309
+ documentId: null
310
+ }));
311
+ const next = /* @__PURE__ */ new Map();
312
+ for (const record of records) {
313
+ if (!record || !Number.isSafeInteger(record.tabId) || record.tabId < 0 || !existingIds.has(record.tabId)) continue;
314
+ const documentId = await documentIdForTab(record.tabId);
315
+ if (stored && stored.generation !== sessionGeneration && (typeof record.documentId !== "string" || !record.documentId || record.documentId !== documentId)) {
316
+ console.warn(`[MCP] Managed page ${record.tabId} was not restored: native document identity does not match`);
317
+ continue;
318
+ }
319
+ next.set(record.tabId, documentId);
320
+ }
321
+ await commitManagedTabs(next, sessionGeneration);
322
+ if (session[LEGACY_STORAGE_KEY] !== void 0) try {
323
+ await chrome.storage.session.remove(LEGACY_STORAGE_KEY);
324
+ } catch (error) {
325
+ console.warn("[MCP] Failed to remove migrated managed page IDs:", error);
326
+ }
327
+ })();
328
+ initialization.catch(() => {
329
+ initialization = null;
330
+ });
331
+ }
332
+ return initialization;
200
333
  }
201
334
  //#endregion
202
335
  //#region src/background/action-utils.ts
@@ -205,16 +338,12 @@ function isRestrictedUrl(url) {
205
338
  return url === "about:blank" || url.startsWith("about:") || url.startsWith("chrome://") || url.startsWith("chrome-extension://");
206
339
  }
207
340
  async function assertScriptable(tabId) {
208
- const tab = await chrome.tabs.get(tabId);
341
+ const tab = await getExistingTab(tabId);
209
342
  if (isRestrictedUrl(tab.url)) throw new ExpectedOperationError(`Cannot execute on restricted URL "${tab.url}". Navigate to an http/https page first.`);
210
343
  }
211
344
  async function getTargetTabId(tabId) {
212
345
  if (tabId !== void 0 && tabId !== null) {
213
- try {
214
- await chrome.tabs.get(tabId);
215
- } catch {
216
- throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
217
- }
346
+ await getExistingTab(tabId);
218
347
  return tabId;
219
348
  }
220
349
  const [activeTab] = await chrome.tabs.query({
@@ -255,12 +384,7 @@ function tabToInfo(tab) {
255
384
  };
256
385
  }
257
386
  async function assertManagedTab(tabId, context, operation) {
258
- let tab;
259
- try {
260
- tab = await chrome.tabs.get(tabId);
261
- } catch {
262
- throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
263
- }
387
+ const tab = await getExistingTab(tabId);
264
388
  if (!isManagedTab(tab)) throw new ExpectedOperationError(`${operation} 拒绝操作非托管 tab, ${JSON.stringify({
265
389
  tabId,
266
390
  managed: false,
@@ -272,7 +396,7 @@ async function assertManagedTab(tabId, context, operation) {
272
396
  return tab;
273
397
  }
274
398
  async function assertReadableTab(tabId, context, operation) {
275
- const tab = await chrome.tabs.get(tabId);
399
+ const tab = await getExistingTab(tabId);
276
400
  if (isManagedTab(tab)) return { tab };
277
401
  const documentId = await readGrantDocumentId(context.serverInstanceId, tabId);
278
402
  if (documentId) return {
@@ -285,7 +409,7 @@ var FRAME_PROBE_TIMEOUT_MS = 500;
285
409
  var pendingDomFrameProbes = /* @__PURE__ */ new Map();
286
410
  function recordDomFrameProbe(message, sender) {
287
411
  const pending = pendingDomFrameProbes.get(message.token);
288
- if (!pending || sender.tab?.id !== pending.tabId || sender.frameId === void 0 || sender.frameId === 0 || !Number.isInteger(message.index) || message.index < 0) return { accepted: false };
412
+ if (!pending || sender.tab?.id !== pending.tabId || sender.frameId === void 0 || sender.frameId === 0 || pending.documentId !== void 0 && sender.documentId !== pending.documentId || !Number.isInteger(message.index) || message.index < 0) return { accepted: false };
289
413
  const frameIds = pending.frameIdsByIndex.get(message.index) ?? [];
290
414
  if (!frameIds.includes(sender.frameId)) {
291
415
  frameIds.push(sender.frameId);
@@ -293,6 +417,52 @@ function recordDomFrameProbe(message, sender) {
293
417
  }
294
418
  return { accepted: true };
295
419
  }
420
+ /** 向 CDP 返回的实际 owner 节点探测,避免异步等待后按旧 DOM index 选择其他 iframe */
421
+ async function probeCdpFrameOwner(tabId, documentId, cdpFrameId) {
422
+ await chrome.scripting.executeScript({
423
+ target: {
424
+ tabId,
425
+ documentIds: [documentId]
426
+ },
427
+ func: installFrameProbeListener
428
+ });
429
+ const owner = await chrome.debugger.sendCommand({ tabId }, "DOM.getFrameOwner", { frameId: cdpFrameId });
430
+ const objectId = (await chrome.debugger.sendCommand({ tabId }, "DOM.resolveNode", { backendNodeId: owner.backendNodeId })).object.objectId;
431
+ if (!objectId) return null;
432
+ const token = crypto.randomUUID();
433
+ const pending = {
434
+ tabId,
435
+ documentId,
436
+ frameIdsByIndex: /* @__PURE__ */ new Map()
437
+ };
438
+ pendingDomFrameProbes.set(token, pending);
439
+ try {
440
+ const result = await chrome.debugger.sendCommand({ tabId }, "Runtime.callFunctionOn", {
441
+ objectId,
442
+ functionDeclaration: `function(token, timeout) {
443
+ const child = this.contentWindow;
444
+ if (!this.isConnected || !child) return false;
445
+ return new Promise(resolve => {
446
+ const finish = value => { clearTimeout(timer); window.removeEventListener('message', onMessage); resolve(value); };
447
+ const onMessage = event => { if (event.source === child && event.data?.type === 'mcp-frame-probe-ack-v2' && event.data.token === token && event.data.index === 0) finish(true); };
448
+ const timer = setTimeout(() => finish(false), timeout);
449
+ window.addEventListener('message', onMessage);
450
+ child.postMessage({type:'mcp-frame-probe-v2', token, index:0}, '*');
451
+ });
452
+ }`,
453
+ arguments: [{ value: token }, { value: FRAME_PROBE_TIMEOUT_MS }],
454
+ awaitPromise: true,
455
+ returnByValue: true
456
+ });
457
+ const ids = pending.frameIdsByIndex.get(0) ?? [];
458
+ return !result.exceptionDetails && result.result?.value === true && ids.length === 1 ? ids[0] : null;
459
+ } finally {
460
+ pendingDomFrameProbes.delete(token);
461
+ await chrome.debugger.sendCommand({ tabId }, "Runtime.releaseObject", { objectId }).catch((error) => {
462
+ console.debug("[MCP] Frame owner probe cleanup failed", error);
463
+ });
464
+ }
465
+ }
296
466
  /**
297
467
  * 将父文档里的 DOM iframe 与 Chrome frameId 建立可验证映射
298
468
  *
@@ -304,17 +474,29 @@ async function getDomFrameSnapshot(tabId, parentFrameId, selection, documentId,
304
474
  const parentFrame = chromeFrames?.find((frame) => frame.frameId === parentFrameId);
305
475
  if (documentId && (parentFrame?.documentId !== documentId || expectedUrl !== void 0 && parentFrame.url !== expectedUrl)) throw new ExpectedOperationError(`parent frame ${parentFrameId} 页面已变化,未读取`);
306
476
  if (!chromeFrames || !parentFrame?.documentId) throw new ExpectedOperationError(`无法读取 parent frame ${parentFrameId} 的 documentId`);
307
- const childDocumentIds = chromeFrames.filter((frame) => frame.parentFrameId === parentFrameId && frame.parentDocumentId === parentFrame.documentId && !frame.errorOccurred && (!isRestrictedUrl(frame.url) || /^about:(?:blank|srcdoc)(?:[?#]|$)/.test(frame.url))).map((frame) => {
308
- if (!frame.documentId) throw new ExpectedOperationError(`无法读取 iframe ${frame.frameId} 的 documentId`);
309
- return frame.documentId;
310
- });
311
- if (childDocumentIds.length > 0) await chrome.scripting.executeScript({
312
- target: {
313
- tabId,
314
- documentIds: childDocumentIds
315
- },
316
- func: installFrameProbeListener
317
- });
477
+ const unavailableFrames = [];
478
+ const verifiedFrameIds = /* @__PURE__ */ new Set();
479
+ const childFrames = chromeFrames.filter((frame) => frame.parentFrameId === parentFrameId && frame.parentDocumentId === parentFrame.documentId && !frame.errorOccurred && (!isRestrictedUrl(frame.url) || /^about:(?:blank|srcdoc)(?:[?#]|$)/.test(frame.url)));
480
+ await Promise.all(childFrames.map(async (frame) => {
481
+ try {
482
+ if (!frame.documentId) throw new ExpectedOperationError(`无法读取 iframe ${frame.frameId} 的 documentId`);
483
+ await chrome.scripting.executeScript({
484
+ target: {
485
+ tabId,
486
+ documentIds: [frame.documentId]
487
+ },
488
+ func: installFrameProbeListener
489
+ });
490
+ verifiedFrameIds.add(frame.frameId);
491
+ } catch (error) {
492
+ unavailableFrames.push({
493
+ frameId: frame.frameId,
494
+ documentId: frame.documentId,
495
+ url: frame.url,
496
+ error: error instanceof Error ? error.message : String(error)
497
+ });
498
+ }
499
+ }));
318
500
  const token = crypto.randomUUID();
319
501
  const pendingProbe = {
320
502
  tabId,
@@ -369,12 +551,12 @@ async function getDomFrameSnapshot(tabId, parentFrameId, selection, documentId,
369
551
  };
370
552
  const onMessage = (event) => {
371
553
  const data = event.data;
372
- if (event.source === child && data?.type === "mcp-frame-probe-ack" && data.token === probeToken && data.index === index) finish(true);
554
+ if (event.source === child && data?.type === "mcp-frame-probe-ack-v2" && data.token === probeToken && data.index === index) finish(true);
373
555
  };
374
556
  const timer = window.setTimeout(() => finish(false), timeoutMs);
375
557
  window.addEventListener("message", onMessage);
376
558
  child.postMessage({
377
- type: "mcp-frame-probe",
559
+ type: "mcp-frame-probe-v2",
378
560
  token: probeToken,
379
561
  index
380
562
  }, "*");
@@ -434,10 +616,11 @@ async function getDomFrameSnapshot(tabId, parentFrameId, selection, documentId,
434
616
  const candidateFrameIds = acknowledged ? pendingProbe.frameIdsByIndex.get(frame.index) ?? [] : [];
435
617
  return {
436
618
  ...frame,
437
- frameId: candidateFrameIds.length === 1 ? candidateFrameIds[0] : null,
619
+ frameId: candidateFrameIds.length === 1 && verifiedFrameIds.has(candidateFrameIds[0]) ? candidateFrameIds[0] : null,
438
620
  candidateFrameIds: candidateFrameIds.slice(0, 10)
439
621
  };
440
622
  }),
623
+ ...unavailableFrames.length ? { unavailableFrames: unavailableFrames.sort((a, b) => a.frameId - b.frameId) } : {},
441
624
  selectedIndex: parentResult.selectedIndex,
442
625
  selectionStatus: parentResult.selectionStatus,
443
626
  ...parentResult.selectionError ? { selectionError: parentResult.selectionError } : {}
@@ -454,7 +637,7 @@ async function getDomFrameSnapshot(tabId, parentFrameId, selection, documentId,
454
637
  async function getFrameOffset(tabId, frameId) {
455
638
  const targetFrame = (await chrome.webNavigation.getAllFrames({ tabId }))?.find((frame) => frame.frameId === frameId);
456
639
  if (!targetFrame || targetFrame.parentFrameId === -1) return null;
457
- if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return null;
640
+ if (isRestrictedUrl((await getExistingTab(tabId)).url)) return null;
458
641
  let parentOffset = {
459
642
  x: 0,
460
643
  y: 0
@@ -4974,6 +5157,7 @@ var DebuggerSendSchema = object({
4974
5157
  });
4975
5158
  var InputKeySchema = object({
4976
5159
  tabId: tabIdOpt,
5160
+ deadline: number().finite().nonnegative().optional(),
4977
5161
  type: _enum([
4978
5162
  "keyDown",
4979
5163
  "keyUp",
@@ -5085,6 +5269,7 @@ var StealthTypeSchema = object({
5085
5269
  });
5086
5270
  var StealthKeySchema = object({
5087
5271
  tabId: tabIdOpt,
5272
+ deadline: number().finite().nonnegative().optional(),
5088
5273
  frameId: frameIdOpt,
5089
5274
  key: string().min(1),
5090
5275
  type: _enum([
@@ -5297,8 +5482,10 @@ function remainingNavigationTimeout(deadline, actionExecuted = false) {
5297
5482
  }
5298
5483
  var NavigationHandler = class {
5299
5484
  logManager;
5300
- constructor(logManager) {
5485
+ enableNetworkObservation;
5486
+ constructor(logManager, enableNetworkObservation) {
5301
5487
  this.logManager = logManager;
5488
+ this.enableNetworkObservation = enableNetworkObservation;
5302
5489
  }
5303
5490
  async navigate(params, context) {
5304
5491
  const p = NavigateSchema.parse(params);
@@ -5312,7 +5499,7 @@ var NavigationHandler = class {
5312
5499
  await chrome.tabs.update(tabId, { url: p.url });
5313
5500
  }
5314
5501
  remainingNavigationTimeout(deadline, true);
5315
- return tabToInfo(await chrome.tabs.get(tabId));
5502
+ return tabToInfo(await getExistingTab(tabId));
5316
5503
  }
5317
5504
  async goBack(params, context) {
5318
5505
  const p = GoBackSchema.parse(params) ?? {};
@@ -5320,12 +5507,13 @@ var NavigationHandler = class {
5320
5507
  remainingNavigationTimeout(deadline);
5321
5508
  const tabId = await getTargetTabId(p.tabId);
5322
5509
  await assertManagedTab(tabId, context, "go_back");
5323
- const beforeUrl = (await chrome.tabs.get(tabId)).url;
5510
+ await this.prepareNetworkIdle(tabId, p.waitUntil);
5511
+ const beforeUrl = (await getExistingTab(tabId)).url;
5324
5512
  const signalTimeout = Math.min(p.timeout ?? 2e3, 5e3, remainingNavigationTimeout(deadline));
5325
5513
  const navigated = await this.navigateHistory(tabId, beforeUrl, signalTimeout, "back", deadline);
5326
5514
  if (navigated && p.waitUntil) await this.waitForNavigation(tabId, p.waitUntil, remainingNavigationTimeout(deadline, true));
5327
5515
  remainingNavigationTimeout(deadline, true);
5328
- const tab = await chrome.tabs.get(tabId);
5516
+ const tab = await getExistingTab(tabId);
5329
5517
  return {
5330
5518
  url: tab.url || "",
5331
5519
  title: tab.title || "",
@@ -5339,12 +5527,13 @@ var NavigationHandler = class {
5339
5527
  remainingNavigationTimeout(deadline);
5340
5528
  const tabId = await getTargetTabId(p.tabId);
5341
5529
  await assertManagedTab(tabId, context, "go_forward");
5342
- const beforeUrl = (await chrome.tabs.get(tabId)).url;
5530
+ await this.prepareNetworkIdle(tabId, p.waitUntil);
5531
+ const beforeUrl = (await getExistingTab(tabId)).url;
5343
5532
  const signalTimeout = Math.min(p.timeout ?? 2e3, 5e3, remainingNavigationTimeout(deadline));
5344
5533
  const navigated = await this.navigateHistory(tabId, beforeUrl, signalTimeout, "forward", deadline);
5345
5534
  if (navigated && p.waitUntil) await this.waitForNavigation(tabId, p.waitUntil, remainingNavigationTimeout(deadline, true));
5346
5535
  remainingNavigationTimeout(deadline, true);
5347
- const tab = await chrome.tabs.get(tabId);
5536
+ const tab = await getExistingTab(tabId);
5348
5537
  return {
5349
5538
  url: tab.url || "",
5350
5539
  title: tab.title || "",
@@ -5364,7 +5553,7 @@ var NavigationHandler = class {
5364
5553
  await chrome.tabs.reload(tabId, { bypassCache: p.ignoreCache ?? false });
5365
5554
  }
5366
5555
  remainingNavigationTimeout(deadline, true);
5367
- const tab = await chrome.tabs.get(tabId);
5556
+ const tab = await getExistingTab(tabId);
5368
5557
  return {
5369
5558
  url: tab.url || "",
5370
5559
  title: tab.title || "",
@@ -5373,6 +5562,10 @@ var NavigationHandler = class {
5373
5562
  }
5374
5563
  async waitForNavigation(tabId, waitUntil, timeout = 3e4) {
5375
5564
  const startedAt = Date.now();
5565
+ await this.prepareNetworkIdle(tabId, waitUntil);
5566
+ timeout -= Date.now() - startedAt;
5567
+ if (timeout <= 0) throw navigationTimeout(true);
5568
+ const observationStartedAt = Date.now();
5376
5569
  let currentDocumentId = null;
5377
5570
  await new Promise((resolve, reject) => {
5378
5571
  let settled = false;
@@ -5399,12 +5592,16 @@ var NavigationHandler = class {
5399
5592
  };
5400
5593
  const checkIdle = () => {
5401
5594
  if (settled) return;
5402
- const remaining = timeout - (Date.now() - startedAt);
5595
+ const remaining = timeout - (Date.now() - observationStartedAt);
5403
5596
  if (remaining <= 0) {
5404
5597
  fail(navigationTimeout(true));
5405
5598
  return;
5406
5599
  }
5407
5600
  const pending = this.logManager.getPending(tabId);
5601
+ if (!this.logManager.isNetworkObserved(tabId)) {
5602
+ fail(new ExpectedOperationError("Network 观测已中断,无法判断 networkidle"));
5603
+ return;
5604
+ }
5408
5605
  const hasPending = pending !== void 0 && pending.size > 0;
5409
5606
  const uncertain = this.logManager.isPendingUncertain(tabId);
5410
5607
  if (hasPending || uncertain) idleSince = null;
@@ -5440,7 +5637,7 @@ var NavigationHandler = class {
5440
5637
  });
5441
5638
  if (currentDocumentId === null && typeof frame?.documentId === "string") currentDocumentId = frame.documentId;
5442
5639
  }
5443
- if ((await chrome.tabs.get(tabId)).status === "complete") if (waitUntil === "networkidle") checkIdle();
5640
+ if ((await getExistingTab(tabId)).status === "complete") if (waitUntil === "networkidle") checkIdle();
5444
5641
  else done();
5445
5642
  } catch (error) {
5446
5643
  fail(error instanceof Error ? error : new Error(String(error)));
@@ -5448,8 +5645,15 @@ var NavigationHandler = class {
5448
5645
  })();
5449
5646
  });
5450
5647
  }
5648
+ async prepareNetworkIdle(tabId, waitUntil) {
5649
+ if (waitUntil === "networkidle") {
5650
+ await this.enableNetworkObservation?.(tabId);
5651
+ if (!this.logManager.isNetworkObserved(tabId)) throw new ExpectedOperationError("Network 观测未建立,无法判断 networkidle");
5652
+ }
5653
+ }
5451
5654
  async runNavigationAction(tabId, waitUntil, deadline, action, expectedSameDocumentUrl) {
5452
5655
  remainingNavigationTimeout(deadline);
5656
+ await this.prepareNetworkIdle(tabId, waitUntil);
5453
5657
  const normalizedSameDocumentUrl = normalizeNavigationUrl(expectedSameDocumentUrl);
5454
5658
  let baselineDocumentId = null;
5455
5659
  if (expectedSameDocumentUrl && typeof chrome.webNavigation.getFrame === "function") try {
@@ -5497,6 +5701,10 @@ var NavigationHandler = class {
5497
5701
  return;
5498
5702
  }
5499
5703
  const pending = this.logManager.getPending(tabId);
5704
+ if (!this.logManager.isNetworkObserved(tabId)) {
5705
+ fail(new ExpectedOperationError("Network 观测已中断,无法判断 networkidle"));
5706
+ return;
5707
+ }
5500
5708
  const hasPending = pending !== void 0 && pending.size > 0;
5501
5709
  const uncertain = this.logManager.isPendingUncertain(tabId);
5502
5710
  if (hasPending || uncertain) idleSince = null;
@@ -5561,7 +5769,7 @@ var NavigationHandler = class {
5561
5769
  } catch (error) {
5562
5770
  const msg = error instanceof Error ? error.message : String(error);
5563
5771
  if (!/Cannot find a (?:next|previous) page in history/i.test(msg)) throw error;
5564
- if (!isRestrictedUrl((await chrome.tabs.get(tabId)).url)) {
5772
+ if (!isRestrictedUrl((await getExistingTab(tabId)).url)) {
5565
5773
  const frame = await chrome.webNavigation.getFrame({
5566
5774
  tabId,
5567
5775
  frameId: 0
@@ -5905,7 +6113,7 @@ var ContentHandler = class {
5905
6113
  const p = FindSchema.parse(params) ?? {};
5906
6114
  const frameId = p.frameId ?? 0;
5907
6115
  const { tabId, documentId, expectedUrl } = await this.getReadableTabId(p.tabId, context, "find", frameId);
5908
- if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return [];
6116
+ if (isRestrictedUrl((await getExistingTab(tabId)).url)) return [];
5909
6117
  let elements = await this.injectScript(tabId, frameId, findElements, [
5910
6118
  p.selector ?? null,
5911
6119
  p.text ?? null,
@@ -6063,7 +6271,7 @@ var ContentHandler = class {
6063
6271
  }
6064
6272
  /** debugger 被占用时通过 captureVisibleTab 截图(仅可视区域) */
6065
6273
  async screenshotFallback(tabId, p) {
6066
- const tab = await chrome.tabs.get(tabId);
6274
+ const tab = await getExistingTab(tabId);
6067
6275
  if (!tab.active) throw structuredOperationError$1("DEBUGGER_BLOCKED_SCREENSHOT_UNAVAILABLE", "debugger 被占用,且当前 tab 不是窗口内 active tab,无法通过 captureVisibleTab 截图", "请关闭占用 debugger 的扩展,或只在 managed 测试页上显式 activatePage 后重试;不要激活用户工作 tab", {
6068
6276
  tabId,
6069
6277
  fallback: "captureVisibleTab",
@@ -6173,21 +6381,6 @@ var CookieHandler = class {
6173
6381
  };
6174
6382
  //#endregion
6175
6383
  //#region src/background/debugger-handler.ts
6176
- var EXPECTED_DEBUGGER_PATTERNS = [
6177
- /Cannot access a chrome:\/\//i,
6178
- /Cannot access a chrome-extension:\/\//i,
6179
- /Cannot attach to .* tab/i,
6180
- /Inspected target navigated or closed/i,
6181
- /No tab with given id/i,
6182
- /Detached while handling command/i,
6183
- /Cannot find context with specified id/i,
6184
- /Execution context was destroyed/i
6185
- ];
6186
- function wrapDebuggerError(err) {
6187
- const msg = err instanceof Error ? err.message : String(err);
6188
- if (EXPECTED_DEBUGGER_PATTERNS.some((p) => p.test(msg))) return new ExpectedOperationError(msg);
6189
- return err instanceof Error ? err : new Error(msg);
6190
- }
6191
6384
  var DebuggerHandler = class {
6192
6385
  debuggerManager;
6193
6386
  logManager;
@@ -6197,11 +6390,14 @@ var DebuggerHandler = class {
6197
6390
  }
6198
6391
  async debuggerAttach(params, context) {
6199
6392
  const p = DebuggerAttachSchema.parse(params) ?? {};
6200
- const tabId = await this.getManagedScriptableTabId(p.tabId, context, "debugger_attach");
6393
+ const tabId = await this.getManagedDebuggableTabId(p.tabId, context, "debugger_attach");
6201
6394
  try {
6202
6395
  await this.debuggerManager.ensureAttached(tabId);
6203
- } catch (e) {
6204
- throw wrapDebuggerError(e);
6396
+ } catch (error) {
6397
+ throw wrapDebuggerError(error, {
6398
+ tabId,
6399
+ phase: "attach"
6400
+ });
6205
6401
  }
6206
6402
  return {
6207
6403
  success: true,
@@ -6216,8 +6412,11 @@ var DebuggerHandler = class {
6216
6412
  if (!this.debuggerManager.isAttached(tabId)) return { success: true };
6217
6413
  try {
6218
6414
  await chrome.debugger.detach({ tabId });
6219
- } catch (e) {
6220
- throw wrapDebuggerError(e);
6415
+ } catch (error) {
6416
+ throw wrapDebuggerError(error, {
6417
+ tabId,
6418
+ phase: "detach"
6419
+ });
6221
6420
  }
6222
6421
  this.debuggerManager.cleanupTab(tabId);
6223
6422
  this.logManager.handleDebuggerDetach(tabId);
@@ -6225,19 +6424,33 @@ var DebuggerHandler = class {
6225
6424
  }
6226
6425
  async debuggerSend(params, context) {
6227
6426
  const p = DebuggerSendSchema.parse(params);
6228
- const tabId = await this.getManagedScriptableTabId(p.tabId, context, "debugger_send");
6427
+ const tabId = await this.getManagedDebuggableTabId(p.tabId, context, "debugger_send");
6229
6428
  try {
6230
6429
  await this.debuggerManager.ensureAttached(tabId);
6231
- if (p.method === "Emulation.setDeviceMetricsOverride") await chrome.tabs.setZoom(tabId, 1);
6232
- return await chrome.debugger.sendCommand({ tabId }, p.method, p.params);
6233
- } catch (e) {
6234
- throw wrapDebuggerError(e);
6430
+ } catch (error) {
6431
+ throw wrapDebuggerError(error, {
6432
+ tabId,
6433
+ phase: "attach"
6434
+ });
6235
6435
  }
6436
+ if (p.method === "Emulation.setDeviceMetricsOverride") await chrome.tabs.setZoom(tabId, 1);
6437
+ let result;
6438
+ try {
6439
+ result = await chrome.debugger.sendCommand({ tabId }, p.method, p.params);
6440
+ } catch (error) {
6441
+ throw wrapDebuggerError(error, {
6442
+ tabId,
6443
+ method: p.method,
6444
+ phase: "command"
6445
+ });
6446
+ }
6447
+ if (p.method === "Network.disable") this.logManager.handleDebuggerDetach(tabId);
6448
+ return result;
6236
6449
  }
6237
- async getManagedScriptableTabId(tabId, context, operation) {
6450
+ async getManagedDebuggableTabId(tabId, context, operation) {
6238
6451
  const resolvedTabId = await getTargetTabId(tabId);
6239
- await assertManagedTab(resolvedTabId, context, operation);
6240
- await assertScriptable(resolvedTabId);
6452
+ const tab = await assertManagedTab(resolvedTabId, context, operation);
6453
+ if (!/^about:blank(?:[?#]|$)/.test(tab.url ?? "")) await assertScriptable(resolvedTabId);
6241
6454
  return resolvedTabId;
6242
6455
  }
6243
6456
  };
@@ -6276,7 +6489,8 @@ var FrameResolver = class {
6276
6489
  selection: p.frame,
6277
6490
  domIndex: snapshot.selectedIndex,
6278
6491
  candidateFrameIds: selected?.candidateFrameIds ?? [],
6279
- domFrameCount: snapshot.frames.length
6492
+ domFrameCount: snapshot.frames.length,
6493
+ ...snapshot.unavailableFrames ? { unavailableFrames: snapshot.unavailableFrames } : {}
6280
6494
  }
6281
6495
  } }));
6282
6496
  const identity = await this.getExtensionFrameIdentity(tabId, selected.frameId);
@@ -6286,7 +6500,8 @@ var FrameResolver = class {
6286
6500
  frameContext: {
6287
6501
  tabId,
6288
6502
  ...this.frameIdentitySummary(identity),
6289
- domIndex: selected.index
6503
+ domIndex: selected.index,
6504
+ ...snapshot.unavailableFrames ? { unavailableFrames: snapshot.unavailableFrames } : {}
6290
6505
  }
6291
6506
  };
6292
6507
  }
@@ -6299,20 +6514,25 @@ var FrameResolver = class {
6299
6514
  const snapshot = await getDomFrameSnapshot(tabId, 0, void 0, readable.documentId, readable.tab.url);
6300
6515
  if (readable.documentId && await readGrantDocumentId(context.serverInstanceId, tabId) !== readable.documentId) throw new ExpectedOperationError("get_all_frames 页面已变化,未读取");
6301
6516
  const domFramesByFrameId = new Map(snapshot.frames.filter((frame) => frame.frameId !== null).map((frame) => [frame.frameId, frame]));
6302
- return { frames: frames.map((frame, index) => {
6303
- const isMainFrame = frame.frameId === 0;
6304
- const dom = isMainFrame ? void 0 : domFramesByFrameId.get(frame.frameId);
6305
- return {
6306
- index,
6307
- frameId: frame.frameId,
6308
- parentFrameId: isMainFrame ? null : frame.parentFrameId,
6309
- url: frame.url,
6310
- title: isMainFrame ? snapshot.parent.title : dom?.title ?? null,
6311
- name: isMainFrame ? null : dom?.name ?? null,
6312
- selector: isMainFrame ? null : dom?.selector ?? null,
6313
- rect: isMainFrame ? snapshot.parent.rect : dom?.rect ?? null
6314
- };
6315
- }) };
6517
+ const unavailableFrames = new Map(snapshot.unavailableFrames?.map((frame) => [frame.frameId, frame.error]));
6518
+ return {
6519
+ ...snapshot.unavailableFrames ? { unavailableFrames: snapshot.unavailableFrames } : {},
6520
+ frames: frames.map((frame, index) => {
6521
+ const isMainFrame = frame.frameId === 0;
6522
+ const dom = isMainFrame ? void 0 : domFramesByFrameId.get(frame.frameId);
6523
+ return {
6524
+ index,
6525
+ frameId: frame.frameId,
6526
+ parentFrameId: isMainFrame ? null : frame.parentFrameId,
6527
+ url: frame.url,
6528
+ title: isMainFrame ? snapshot.parent.title : dom?.title ?? null,
6529
+ name: isMainFrame ? null : dom?.name ?? null,
6530
+ selector: isMainFrame ? null : dom?.selector ?? null,
6531
+ rect: isMainFrame ? snapshot.parent.rect : dom?.rect ?? null,
6532
+ ...unavailableFrames.has(frame.frameId) ? { unavailableReason: unavailableFrames.get(frame.frameId) } : {}
6533
+ };
6534
+ })
6535
+ };
6316
6536
  }
6317
6537
  /**
6318
6538
  * 在指定 iframe 中以 precise 模式执行 JS
@@ -6339,15 +6559,41 @@ var FrameResolver = class {
6339
6559
  retryAttempted,
6340
6560
  retryReason
6341
6561
  });
6342
- const identity = await this.getExtensionFrameIdentity(tabId, p.frameId);
6343
- if (identity.parentFrameId !== originalFrame.parentFrameId || identity.frameId !== originalFrame.frameId) throw this.frameEvaluationError("FRAME_IDENTITY_CHANGED", "Frame identity changed before stale-context retry; refusing to guess target", {
6344
- tabId,
6345
- retryAttempted,
6346
- retryReason,
6347
- originalFrame: this.frameIdentitySummary(originalFrame),
6348
- currentFrame: this.frameIdentitySummary(identity)
6349
- });
6350
- const resolved = await this.resolveCdpFrame(tabId, identity);
6562
+ let identity = originalFrame;
6563
+ let resolved;
6564
+ try {
6565
+ identity = await this.getExtensionFrameIdentity(tabId, p.frameId);
6566
+ const resolutionDeadline = startedAt + (p.timeout ?? 2e3);
6567
+ for (;;) {
6568
+ if (identity.parentFrameId !== originalFrame.parentFrameId || identity.frameId !== originalFrame.frameId) throw this.frameEvaluationError("FRAME_IDENTITY_CHANGED", "Frame identity changed before stale-context retry; refusing to guess target", {
6569
+ tabId,
6570
+ retryAttempted,
6571
+ retryReason,
6572
+ originalFrame: this.frameIdentitySummary(originalFrame),
6573
+ currentFrame: this.frameIdentitySummary(identity)
6574
+ });
6575
+ try {
6576
+ resolved = await this.resolveCdpFrame(tabId, identity);
6577
+ break;
6578
+ } catch (error) {
6579
+ const message = error instanceof Error ? error.message : String(error);
6580
+ if (!retryAttempted || message !== `No document with id ${identity.documentId} in tab with id ${tabId}`) throw error;
6581
+ const remainingResolution = resolutionDeadline - Date.now();
6582
+ if (remainingResolution <= 0) throw new Error("Frame document resolution timed out after stale execution context", { cause: error });
6583
+ await new Promise((resolve) => setTimeout(resolve, Math.min(25, remainingResolution)));
6584
+ identity = await this.getExtensionFrameIdentity(tabId, p.frameId);
6585
+ }
6586
+ }
6587
+ } catch (error) {
6588
+ if (!retryAttempted) throw error;
6589
+ throw this.frameEvaluationError("FRAME_EVALUATION_FAILED", (error instanceof Error ? error.message : String(error)).slice(0, 500), {
6590
+ tabId,
6591
+ ...this.frameIdentitySummary(identity),
6592
+ phase: "retry_resolution",
6593
+ retryAttempted,
6594
+ retryReason
6595
+ });
6596
+ }
6351
6597
  let contexts = this.debuggerManager.getExecutionContexts(tabId);
6352
6598
  if (contexts.length === 0 || attempt > 0) await chrome.debugger.sendCommand({ tabId }, "Runtime.enable");
6353
6599
  let targetCtx = contexts.find((item) => item.frameId === resolved.cdpFrameId && item.isDefault);
@@ -6398,8 +6644,20 @@ var FrameResolver = class {
6398
6644
  }
6399
6645
  };
6400
6646
  } catch (error) {
6647
+ const nativeError = wrapDebuggerError(error, {
6648
+ tabId,
6649
+ method: "Runtime.evaluate",
6650
+ phase: "command",
6651
+ frameContext: {
6652
+ tabId,
6653
+ ...this.frameIdentitySummary(identity),
6654
+ cdpFrameId: resolved.cdpFrameId,
6655
+ executionContextId: targetCtx.id
6656
+ }
6657
+ });
6401
6658
  const message = error instanceof Error ? error.message : String(error);
6402
6659
  const staleContext = /context.*(?:destroyed|not found|invalid)|Cannot find context|Execution context/i.test(message);
6660
+ if (!staleContext && nativeError !== error) throw nativeError;
6403
6661
  if (attempt > 0) throw this.frameEvaluationError("FRAME_EVALUATION_FAILED", message.slice(0, 500), {
6404
6662
  tabId,
6405
6663
  ...this.frameIdentitySummary(identity),
@@ -6486,24 +6744,15 @@ var FrameResolver = class {
6486
6744
  candidateCount: 0
6487
6745
  });
6488
6746
  if (candidates.length > 1) {
6489
- if (frame.parentFrameId === 0) {
6490
- const parent = await this.getExtensionFrameIdentity(tabId, 0);
6491
- const snapshot = await getDomFrameSnapshot(tabId, 0, void 0, parent.documentId, parent.url);
6492
- const selected = snapshot.frames.filter((item) => item.frameId === frame.frameId);
6493
- if (selected.length === 1) {
6494
- const document = await chrome.debugger.sendCommand({ tabId }, "DOM.getDocument", { depth: 1 });
6495
- const elements = await chrome.debugger.sendCommand({ tabId }, "DOM.querySelectorAll", {
6496
- nodeId: document.root.nodeId,
6497
- selector: "iframe, frame"
6747
+ if (frame.documentId) {
6748
+ for (const candidate of candidates) if (await probeCdpFrameOwner(tabId, frame.documentId, candidate) === frame.frameId) {
6749
+ const current = await this.getExtensionFrameIdentity(tabId, frame.frameId);
6750
+ if (current.documentId !== frame.documentId || current.parentFrameId !== frame.parentFrameId) throw this.frameEvaluationError("FRAME_IDENTITY_CHANGED", "Frame document changed during owner probe", {
6751
+ tabId,
6752
+ originalFrame: this.frameIdentitySummary(frame),
6753
+ currentFrame: this.frameIdentitySummary(current)
6498
6754
  });
6499
- const nodeId = elements.nodeIds[selected[0].index];
6500
- if (nodeId && elements.nodeIds.length === snapshot.frames.length) {
6501
- const owner = await chrome.debugger.sendCommand({ tabId }, "DOM.describeNode", {
6502
- nodeId,
6503
- depth: 1
6504
- });
6505
- if (owner.node.frameId && candidates.includes(owner.node.frameId)) return { cdpFrameId: owner.node.frameId };
6506
- }
6755
+ return { cdpFrameId: candidate };
6507
6756
  }
6508
6757
  }
6509
6758
  throw this.frameEvaluationError("FRAME_AMBIGUOUS", "Multiple CDP frames match the same URL; refusing to guess target", {
@@ -6548,6 +6797,7 @@ var InputEventHandler = class {
6548
6797
  const p = InputKeySchema.parse(params);
6549
6798
  const tabId = await this.getManagedTabId(p.tabId, context, "input_key");
6550
6799
  await this.debuggerManager.ensureAttached(tabId);
6800
+ if (p.deadline !== void 0) remainingNavigationTimeout(p.deadline);
6551
6801
  const cdpParams = { type: p.type };
6552
6802
  if (p.key) cdpParams.key = p.key;
6553
6803
  if (p.code) cdpParams.code = p.code;
@@ -6561,6 +6811,7 @@ var InputEventHandler = class {
6561
6811
  if (p.modifiers !== void 0) cdpParams.modifiers = p.modifiers;
6562
6812
  if (p.commands && p.commands.length > 0) cdpParams.commands = p.commands;
6563
6813
  await chrome.debugger.sendCommand({ tabId }, "Input.dispatchKeyEvent", cdpParams);
6814
+ if (p.deadline !== void 0) remainingNavigationTimeout(p.deadline, true);
6564
6815
  return { success: true };
6565
6816
  }
6566
6817
  async inputMouse(params, context) {
@@ -6825,17 +7076,22 @@ var LogEventHandler = class {
6825
7076
  const p = NetworkEnableSchema.parse(params) ?? {};
6826
7077
  const tabId = await this.getManagedTabId(p.tabId, context, "network_enable");
6827
7078
  try {
6828
- await this.debuggerManager.ensureAttached(tabId);
6829
- await chrome.debugger.sendCommand({ tabId }, "Page.enable", {});
6830
- const frameTree = await chrome.debugger.sendCommand({ tabId }, "Page.getFrameTree", {});
6831
- this.logManager.setMainFrameId(tabId, frameTree.frameTree.frame.id);
6832
- await chrome.debugger.sendCommand({ tabId }, "Network.enable", {});
7079
+ await this.enableNetworkObservation(tabId);
6833
7080
  } catch (err) {
6834
7081
  if (!(err instanceof DebuggerBlockedError)) throw err;
6835
7082
  }
6836
7083
  if (!this.logManager.hasNetwork(tabId)) this.logManager.setNetwork(tabId, []);
6837
7084
  return { success: true };
6838
7085
  }
7086
+ async enableNetworkObservation(tabId) {
7087
+ await this.debuggerManager.ensureAttached(tabId);
7088
+ await chrome.debugger.sendCommand({ tabId }, "Page.enable", {});
7089
+ const frameTree = await chrome.debugger.sendCommand({ tabId }, "Page.getFrameTree", {});
7090
+ this.logManager.setMainFrameId(tabId, frameTree.frameTree.frame.id);
7091
+ await chrome.debugger.sendCommand({ tabId }, "Network.enable", {});
7092
+ if (!this.debuggerManager.isAttached(tabId)) throw new ExpectedOperationError("Network 观测已中断,无法判断 networkidle");
7093
+ this.logManager.markNetworkObserved(tabId);
7094
+ }
6839
7095
  async networkGet(params, context) {
6840
7096
  const p = NetworkGetSchema.parse(params) ?? {};
6841
7097
  const tabId = await this.getManagedTabId(p.tabId, context, "network_get");
@@ -6862,7 +7118,7 @@ var LogEventHandler = class {
6862
7118
  }
6863
7119
  requests = [...requests.filter((item) => item.source !== "performance"), ...latest].slice(-1e3);
6864
7120
  this.logManager.setNetwork(tabId, requests);
6865
- } else if (p.clear && !isRestrictedUrl((await chrome.tabs.get(tabId)).url)) await this.readPerformanceNetwork(tabId, true);
7121
+ } else if (p.clear && !isRestrictedUrl((await getExistingTab(tabId)).url)) await this.readPerformanceNetwork(tabId, true);
6866
7122
  if (p.urlPattern) requests = requests.filter((r) => matchesUrlPattern(String(r.url ?? ""), p.urlPattern));
6867
7123
  if (p.clear) this.logManager.setNetwork(tabId, []);
6868
7124
  return { requests };
@@ -6870,7 +7126,7 @@ var LogEventHandler = class {
6870
7126
  async networkClear(params, context) {
6871
7127
  const p = NetworkClearSchema.parse(params) ?? {};
6872
7128
  const tabId = await this.getManagedTabId(p.tabId, context, "network_clear");
6873
- if (!isRestrictedUrl((await chrome.tabs.get(tabId)).url)) await this.readPerformanceNetwork(tabId, true);
7129
+ if (!isRestrictedUrl((await getExistingTab(tabId)).url)) await this.readPerformanceNetwork(tabId, true);
6874
7130
  this.logManager.setNetwork(tabId, []);
6875
7131
  return { success: true };
6876
7132
  }
@@ -6882,7 +7138,7 @@ var LogEventHandler = class {
6882
7138
  /** 卸载 fallback console hook,把残留日志合并到 logManager,并报告清理结果 */
6883
7139
  async flushAndUninstallConsoleHook(tabId) {
6884
7140
  try {
6885
- if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return true;
7141
+ if (isRestrictedUrl((await getExistingTab(tabId)).url)) return true;
6886
7142
  const results = await chrome.scripting.executeScript({
6887
7143
  target: {
6888
7144
  tabId,
@@ -7013,7 +7269,7 @@ var LogEventHandler = class {
7013
7269
  async readConsole(tabId, params) {
7014
7270
  let messages = this.logManager.getConsole(tabId);
7015
7271
  try {
7016
- if (!isRestrictedUrl((await chrome.tabs.get(tabId)).url)) {
7272
+ if (!isRestrictedUrl((await getExistingTab(tabId)).url)) {
7017
7273
  const injected = (await chrome.scripting.executeScript({
7018
7274
  target: {
7019
7275
  tabId,
@@ -7085,7 +7341,7 @@ var LogEventHandler = class {
7085
7341
  }
7086
7342
  async clearFallbackConsole(tabId) {
7087
7343
  try {
7088
- if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return;
7344
+ if (isRestrictedUrl((await getExistingTab(tabId)).url)) return;
7089
7345
  await chrome.scripting.executeScript({
7090
7346
  target: {
7091
7347
  tabId,
@@ -7120,6 +7376,7 @@ var LogManager = class {
7120
7376
  mainFrameIds = /* @__PURE__ */ new Map();
7121
7377
  pendingRequests = /* @__PURE__ */ new Map();
7122
7378
  pendingUncertain = /* @__PURE__ */ new Set();
7379
+ networkObserved = /* @__PURE__ */ new Set();
7123
7380
  sweepTimer = null;
7124
7381
  constructor() {
7125
7382
  this.startSweep();
@@ -7164,8 +7421,15 @@ var LogManager = class {
7164
7421
  isPendingUncertain(tabId) {
7165
7422
  return this.pendingUncertain.has(tabId);
7166
7423
  }
7424
+ isNetworkObserved(tabId) {
7425
+ return this.networkObserved.has(tabId);
7426
+ }
7427
+ markNetworkObserved(tabId) {
7428
+ this.networkObserved.add(tabId);
7429
+ }
7167
7430
  /** debugger 断开后请求结束事件不可恢复,保持不确定状态直到新主文档或 tab cleanup */
7168
7431
  handleDebuggerDetach(tabId) {
7432
+ this.networkObserved.delete(tabId);
7169
7433
  this.pendingRequests.delete(tabId);
7170
7434
  this.pendingUncertain.add(tabId);
7171
7435
  this.mainFrameIds.delete(tabId);
@@ -7205,6 +7469,7 @@ var LogManager = class {
7205
7469
  this.consoleMessages.set(tabId, messages);
7206
7470
  }
7207
7471
  if (method === "Network.requestWillBeSent") {
7472
+ this.networkObserved.add(tabId);
7208
7473
  const p = params;
7209
7474
  let tabPending = this.pendingRequests.get(tabId);
7210
7475
  if (p.type.toLowerCase() === "document" && p.frameId !== void 0 && p.frameId === this.mainFrameIds.get(tabId) && !tabPending?.has(p.requestId)) {
@@ -7270,6 +7535,7 @@ var LogManager = class {
7270
7535
  this.mainFrameIds.delete(tabId);
7271
7536
  this.pendingRequests.delete(tabId);
7272
7537
  this.pendingUncertain.delete(tabId);
7538
+ this.networkObserved.delete(tabId);
7273
7539
  }
7274
7540
  finalizeRequest(tabId, requestId, timestamp, errorText) {
7275
7541
  const tabPending = this.pendingRequests.get(tabId);
@@ -7367,19 +7633,27 @@ var StealthHandler = class {
7367
7633
  async stealthKey(params, context) {
7368
7634
  const p = StealthKeySchema.parse(params);
7369
7635
  const tabId = await this.getManagedScriptableTabId(p.tabId, context, "stealth_key");
7370
- return (await chrome.scripting.executeScript({
7636
+ if (p.deadline !== void 0) remainingNavigationTimeout(p.deadline);
7637
+ const results = await chrome.scripting.executeScript({
7371
7638
  target: {
7372
7639
  tabId,
7373
7640
  frameIds: [p.frameId ?? 0]
7374
7641
  },
7375
7642
  world: "MAIN",
7376
7643
  func: simulateKeyEvent,
7377
- args: [
7644
+ args: p.deadline === void 0 ? [
7378
7645
  p.key,
7379
7646
  p.type || "press",
7380
7647
  p.modifiers || []
7648
+ ] : [
7649
+ p.key,
7650
+ p.type || "press",
7651
+ p.modifiers || [],
7652
+ p.deadline
7381
7653
  ]
7382
- }))[0].result;
7654
+ });
7655
+ if (p.deadline !== void 0) remainingNavigationTimeout(p.deadline, true);
7656
+ return results[0].result;
7383
7657
  }
7384
7658
  async stealthMouse(params, context) {
7385
7659
  const p = StealthMouseSchema.parse(params);
@@ -7542,17 +7816,6 @@ async function waitForWindowGeometry(windowId, state, deadline) {
7542
7816
  failureStage: "observation"
7543
7817
  });
7544
7818
  }
7545
- async function assertManagedWindow(windowId, action) {
7546
- const info = await getWindowInfo(windowId);
7547
- const unmanagedTabs = info.tabs.filter((tab) => !tab.managed);
7548
- if (info.tabs.length > 0 && unmanagedTabs.length === 0) return info;
7549
- throw structuredOperationError("UNMANAGED_WINDOW", `${action} 拒绝操作非 MCP 管理的浏览器窗口`, "请先用 manage(action=\"newWindow\") 创建受控窗口,或只传入全部 tab 都是 managed=true 的窗口", {
7550
- action,
7551
- windowId,
7552
- tabCount: info.tabCount,
7553
- unmanagedTabIds: unmanagedTabs.map((tab) => tab.id)
7554
- });
7555
- }
7556
7819
  var TabHandler = class {
7557
7820
  navigationHandler;
7558
7821
  constructor(navigationHandler) {
@@ -7586,7 +7849,7 @@ var TabHandler = class {
7586
7849
  if (p.groupId !== void 0 && p.groupId < -1) throw new ExpectedOperationError("groupId 必须是 -1 或现有分组 ID,未创建页面");
7587
7850
  if (p.pinned === true && p.groupId !== void 0 && p.groupId >= 0) throw new ExpectedOperationError("pinned=true 与标签分组不兼容,未创建页面");
7588
7851
  const explicitGroup = p.groupId !== void 0 && p.groupId >= 0 ? await chrome.tabGroups.get(p.groupId) : null;
7589
- const opener = p.openerTabId !== void 0 ? await chrome.tabs.get(p.openerTabId) : null;
7852
+ const opener = p.openerTabId !== void 0 ? await getExistingTab(p.openerTabId) : null;
7590
7853
  const windowId = p.windowId ?? explicitGroup?.windowId ?? opener?.windowId;
7591
7854
  if (explicitGroup && explicitGroup.windowId !== windowId || opener && opener.windowId !== windowId) throw new ExpectedOperationError("windowId、groupId 或 openerTabId 不属于同一窗口,未创建页面");
7592
7855
  return {
@@ -7610,9 +7873,10 @@ var TabHandler = class {
7610
7873
  let targetWindowId = context.mcpWindowId;
7611
7874
  if (targetWindowId !== null) try {
7612
7875
  await chrome.windows.get(targetWindowId);
7613
- if ((await chrome.tabs.query({ windowId: targetWindowId })).some((tab) => !isManagedTab(tab))) targetWindowId = null;
7614
7876
  } catch (error) {
7615
- console.warn("[MCP] 原受控窗口不可用,将创建新窗口:", error);
7877
+ const message = error instanceof Error ? error.message : String(error);
7878
+ if (!/^No window with id: -?\d+\.?$/.test(message)) throw error;
7879
+ console.warn("[MCP] 原受控窗口已关闭,将创建新窗口:", error);
7616
7880
  targetWindowId = null;
7617
7881
  }
7618
7882
  if (targetWindowId === null) {
@@ -7691,7 +7955,7 @@ var TabHandler = class {
7691
7955
  if (p.waitUntil) await this.navigationHandler.waitForNavigation(tab.id, p.waitUntil, p.timeout);
7692
7956
  failureStage = "snapshot";
7693
7957
  return {
7694
- ...tabToInfo(await chrome.tabs.get(tab.id)),
7958
+ ...tabToInfo(await getExistingTab(tab.id)),
7695
7959
  ...warnings.length ? { warnings } : {}
7696
7960
  };
7697
7961
  } catch (error) {
@@ -7714,7 +7978,7 @@ var TabHandler = class {
7714
7978
  if (properties.active === false) throw new ExpectedOperationError("updatePage 不支持 active=false;激活其他页面请使用 activatePage,未执行");
7715
7979
  const tab = await assertManagedTab(tabId, context, "tabs_update");
7716
7980
  if (properties.openerTabId !== void 0) {
7717
- const opener = await chrome.tabs.get(properties.openerTabId);
7981
+ const opener = await getExistingTab(properties.openerTabId);
7718
7982
  if (opener.windowId !== tab.windowId || opener.id === tabId) throw new ExpectedOperationError("openerTabId 必须是同一窗口内的其他页面,未执行");
7719
7983
  }
7720
7984
  return {
@@ -7725,7 +7989,7 @@ var TabHandler = class {
7725
7989
  });
7726
7990
  const before = tabToInfo(tab);
7727
7991
  await chrome.tabs.update(tabId, properties);
7728
- const after = tabToInfo(await chrome.tabs.get(tabId));
7992
+ const after = tabToInfo(await getExistingTab(tabId));
7729
7993
  return {
7730
7994
  success: true,
7731
7995
  targetId: String(tabId),
@@ -7753,7 +8017,7 @@ var TabHandler = class {
7753
8017
  const tab = await chrome.tabs.update(p.tabId, { active: true });
7754
8018
  if (!tab) throw new ExpectedOperationError("激活 tab 失败,Chrome 未返回 tab");
7755
8019
  if (tab.windowId !== void 0) await chrome.windows.update(tab.windowId, { focused: true });
7756
- return tabToInfo(await chrome.tabs.get(p.tabId));
8020
+ return tabToInfo(await getExistingTab(p.tabId));
7757
8021
  }
7758
8022
  async tabsActivateManaged(params, context) {
7759
8023
  const p = TabsActivateSchema.parse(params);
@@ -7761,7 +8025,7 @@ var TabHandler = class {
7761
8025
  const updatedTab = await chrome.tabs.update(p.tabId, { active: true });
7762
8026
  if (!updatedTab) throw new ExpectedOperationError("激活 tab 失败,Chrome 未返回 tab");
7763
8027
  if (updatedTab.windowId !== void 0) await chrome.windows.update(updatedTab.windowId, { focused: true });
7764
- const after = tabToInfo(await chrome.tabs.get(p.tabId));
8028
+ const after = tabToInfo(await getExistingTab(p.tabId));
7765
8029
  return {
7766
8030
  success: true,
7767
8031
  targetId: String(p.tabId),
@@ -7772,20 +8036,20 @@ var TabHandler = class {
7772
8036
  }
7773
8037
  async tabsAdopt(params) {
7774
8038
  const p = TabsAdoptSchema.parse(params);
7775
- const managedBefore = isManagedTab(await chrome.tabs.get(p.tabId));
8039
+ const managedBefore = isManagedTab(await getExistingTab(p.tabId));
7776
8040
  await markManagedTab(p.tabId);
7777
8041
  return {
7778
8042
  success: true,
7779
- tab: tabToInfo(await chrome.tabs.get(p.tabId)),
8043
+ tab: tabToInfo(await getExistingTab(p.tabId)),
7780
8044
  managedBefore,
7781
8045
  managedAfter: true
7782
8046
  };
7783
8047
  }
7784
8048
  async tabsRelease(params) {
7785
8049
  const p = TabsReleaseSchema.parse(params);
7786
- const managedBefore = isManagedTab(await chrome.tabs.get(p.tabId));
8050
+ const managedBefore = isManagedTab(await getExistingTab(p.tabId));
7787
8051
  await unmarkManagedTab(p.tabId);
7788
- const updatedTab = await chrome.tabs.get(p.tabId);
8052
+ const updatedTab = await getExistingTab(p.tabId);
7789
8053
  return {
7790
8054
  success: true,
7791
8055
  tab: tabToInfo(updatedTab),
@@ -7801,7 +8065,7 @@ var TabHandler = class {
7801
8065
  ...p.windowId !== void 0 ? { windowId: p.windowId } : {}
7802
8066
  });
7803
8067
  if (p.active !== void 0) await chrome.tabs.update(p.tabId, { active: p.active });
7804
- const after = tabToInfo(await chrome.tabs.get(p.tabId));
8068
+ const after = tabToInfo(await getExistingTab(p.tabId));
7805
8069
  return {
7806
8070
  success: true,
7807
8071
  targetId: String(p.tabId),
@@ -7814,7 +8078,7 @@ var TabHandler = class {
7814
8078
  const p = TabsReorderSchema.parse(params);
7815
8079
  const before = tabToInfo(await assertManagedTab(p.tabId, context, "tabs_reorder"));
7816
8080
  await chrome.tabs.move(p.tabId, { index: p.index });
7817
- const after = tabToInfo(await chrome.tabs.get(p.tabId));
8081
+ const after = tabToInfo(await getExistingTab(p.tabId));
7818
8082
  return {
7819
8083
  success: true,
7820
8084
  targetId: String(p.tabId),
@@ -7827,7 +8091,7 @@ var TabHandler = class {
7827
8091
  const p = TabsPinSchema.parse(params);
7828
8092
  const before = tabToInfo(await assertManagedTab(p.tabId, context, "tabs_pin"));
7829
8093
  await chrome.tabs.update(p.tabId, { pinned: p.pinned });
7830
- const after = tabToInfo(await chrome.tabs.get(p.tabId));
8094
+ const after = tabToInfo(await getExistingTab(p.tabId));
7831
8095
  return {
7832
8096
  success: true,
7833
8097
  targetId: String(p.tabId),
@@ -7838,10 +8102,10 @@ var TabHandler = class {
7838
8102
  }
7839
8103
  async windowFocus(params) {
7840
8104
  const p = WindowFocusSchema.parse(params);
7841
- const before = await assertManagedWindow(p.windowId, "window_focus");
8105
+ const before = await getWindowInfo(p.windowId);
7842
8106
  await chrome.windows.update(p.windowId, { focused: true });
7843
8107
  const after = await waitForWindowFocus(p.windowId);
7844
- if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请确认目标是 managed 测试窗口,并检查桌面环境是否允许扩展聚焦窗口;需要可见 tab 时可用 manage(action=\"activatePage\") 激活目标测试 tab", {
8108
+ if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请检查桌面环境是否允许 Chrome 聚焦目标窗口,并用 browse list 核对实际焦点状态", {
7845
8109
  windowId: p.windowId,
7846
8110
  beforeFocused: before.focused,
7847
8111
  afterFocused: after.focused,
@@ -7861,7 +8125,7 @@ var TabHandler = class {
7861
8125
  const { windowId, ...properties } = WindowUpdateSchema.parse(params);
7862
8126
  assertWindowOptions(properties);
7863
8127
  if (Object.values(properties).every((value) => value === void 0)) throw new ExpectedOperationError("updateWindow 需要至少一个窗口配置参数,未执行");
7864
- const before = await assertManagedWindow(windowId, "window_update");
8128
+ const before = await getWindowInfo(windowId);
7865
8129
  const deadline = Date.now() + WINDOW_OBSERVE_TIMEOUT_MS;
7866
8130
  const requestedState = properties.state;
7867
8131
  const hasBounds = [
@@ -7873,7 +8137,6 @@ var TabHandler = class {
7873
8137
  if (hasBounds && requestedState === "normal" && before.state !== "normal") {
7874
8138
  await chrome.windows.update(windowId, { state: "normal" });
7875
8139
  await waitForWindowGeometry(windowId, requestedState, deadline);
7876
- await assertManagedWindow(windowId, "window_update");
7877
8140
  delete properties.state;
7878
8141
  }
7879
8142
  await chrome.windows.update(windowId, properties);
@@ -7973,7 +8236,7 @@ var TabHandler = class {
7973
8236
  const p = WindowCloseSchema.parse(params);
7974
8237
  const before = await getWindowInfo(p.windowId);
7975
8238
  const unmanagedTabs = before.tabs.filter((tab) => !tab.managed);
7976
- if (unmanagedTabs.length > 0) throw structuredOperationError("WINDOW_HAS_UNMANAGED_TABS", "closeWindow 拒绝关闭含非托管 tab 的窗口", "请只关闭全 managed tabs 的受控窗口,或先用 manage(action=\"releasePage\") 解除不需要关闭的受控 tab", {
8239
+ if (unmanagedTabs.length > 0) throw structuredOperationError("WINDOW_HAS_UNMANAGED_TABS", "closeWindow 拒绝关闭含非托管 tab 的窗口", "请逐页关闭已获授权的受控页并保留其他页,整窗关闭需要全部成员页面的明确授权", {
7977
8240
  windowId: p.windowId,
7978
8241
  unmanagedTabIds: unmanagedTabs.map((tab) => tab.id),
7979
8242
  managedTabIds: before.tabs.filter((tab) => tab.managed).map((tab) => tab.id)
@@ -7988,6 +8251,37 @@ var TabHandler = class {
7988
8251
  after: null
7989
8252
  };
7990
8253
  }
8254
+ async getGroupLockSnapshot(action, params, context) {
8255
+ let tabIds = [];
8256
+ let groupId;
8257
+ switch (action) {
8258
+ case "tabgroup_create":
8259
+ tabIds = TabGroupCreateSchema.parse(params).tabIds;
8260
+ break;
8261
+ case "tabgroup_add": {
8262
+ const p = TabGroupAddSchema.parse(params);
8263
+ tabIds = p.tabIds ?? (p.tabId === void 0 ? [] : [p.tabId]);
8264
+ groupId = p.groupId ?? context.mcpTabGroupId ?? void 0;
8265
+ break;
8266
+ }
8267
+ case "tabgroup_remove":
8268
+ tabIds = TabGroupRemoveSchema.parse(params).tabIds;
8269
+ break;
8270
+ case "tabgroup_update":
8271
+ groupId = TabGroupUpdateSchema.parse(params).groupId;
8272
+ break;
8273
+ case "tabgroup_move":
8274
+ groupId = TabGroupMoveSchema.parse(params).groupId;
8275
+ break;
8276
+ }
8277
+ const requested = await Promise.all(tabIds.map((id) => getExistingTab(id)));
8278
+ const groups = new Set(requested.map((tab) => tab.groupId).filter((id) => id >= 0));
8279
+ if (groupId !== void 0) groups.add(groupId);
8280
+ const tabs = await chrome.tabs.query({});
8281
+ const all = new Map(requested.map((tab) => [tab.id, tab]));
8282
+ for (const tab of tabs) if (groups.has(tab.groupId)) all.set(tab.id, tab);
8283
+ return [...all.values()].sort((a, b) => a.id - b.id);
8284
+ }
7991
8285
  async tabGroupCreate(params, context) {
7992
8286
  const p = TabGroupCreateSchema.parse(params);
7993
8287
  return this.changeGroups(p.tabIds, context, "tabgroup_create", async (tabs) => {
@@ -8026,15 +8320,22 @@ var TabHandler = class {
8026
8320
  await chrome.tabs.ungroup(p.tabIds);
8027
8321
  });
8028
8322
  }
8029
- async tabGroupUpdate(params, context) {
8323
+ async tabGroupUpdate(params) {
8030
8324
  const { groupId, ...properties } = TabGroupUpdateSchema.parse(params);
8031
8325
  if (Object.values(properties).every((value) => value === void 0)) throw new ExpectedOperationError("updateGroup 需要 title、color 或 collapsed,未执行");
8032
- await chrome.tabGroups.get(groupId);
8033
- const tabs = await chrome.tabs.query({ groupId });
8034
- return this.changeGroups(tabs.map((tab) => tab.id), context, "tabgroup_update", async () => {
8035
- await chrome.tabGroups.update(groupId, properties);
8036
- return groupId;
8037
- }, groupId);
8326
+ const before = await chrome.tabGroups.get(groupId);
8327
+ const tabsBefore = await chrome.tabs.query({ groupId });
8328
+ await chrome.tabGroups.update(groupId, properties);
8329
+ const after = await chrome.tabGroups.get(groupId);
8330
+ const tabsAfter = await chrome.tabs.query({ groupId });
8331
+ return {
8332
+ success: true,
8333
+ groupId,
8334
+ before: [groupToInfo(before, tabsBefore)],
8335
+ after: [groupToInfo(after, tabsAfter)],
8336
+ tabsBefore: tabsBefore.map((tab) => tabToInfo(tab)),
8337
+ tabsAfter: tabsAfter.map((tab) => tabToInfo(tab))
8338
+ };
8038
8339
  }
8039
8340
  async tabGroupMove(params, context) {
8040
8341
  const { groupId, ...properties } = TabGroupMoveSchema.parse(params);
@@ -8053,9 +8354,10 @@ var TabHandler = class {
8053
8354
  if (destinationGroupId !== void 0) groupIds.add(destinationGroupId);
8054
8355
  const before = await this.groupInfos(groupIds);
8055
8356
  const tabsBefore = tabs.map((tab) => tabToInfo(tab));
8357
+ if ((await Promise.all(ids.map((id) => assertManagedTab(id, context, action)))).some((tab, index) => tab.groupId !== tabs[index].groupId || tab.windowId !== tabs[index].windowId)) throw new ExpectedOperationError("分组成员或窗口已变化,未执行分组操作");
8056
8358
  const groupId = await operation(tabs);
8057
8359
  if (groupId !== void 0) groupIds.add(groupId);
8058
- const tabsAfter = await Promise.all(ids.map(async (id) => tabToInfo(await chrome.tabs.get(id))));
8360
+ const tabsAfter = await Promise.all(ids.map(async (id) => tabToInfo(await getExistingTab(id))));
8059
8361
  const after = await this.groupInfos(groupIds);
8060
8362
  return {
8061
8363
  success: true,
@@ -8173,7 +8475,7 @@ var ActionHandler = class {
8173
8475
  actionLocks = /* @__PURE__ */ new Map();
8174
8476
  logManager = new LogManager();
8175
8477
  debuggerManager = new DebuggerManager(this.logManager);
8176
- navigationHandler = new NavigationHandler(this.logManager);
8478
+ navigationHandler = new NavigationHandler(this.logManager, (tabId) => this.logEventHandler.enableNetworkObservation(tabId));
8177
8479
  frameResolver = new FrameResolver(this.debuggerManager);
8178
8480
  tabHandler = new TabHandler(this.navigationHandler);
8179
8481
  contentHandler = new ContentHandler(this.debuggerManager);
@@ -8192,11 +8494,27 @@ var ActionHandler = class {
8192
8494
  code: "UNKNOWN_ACTION",
8193
8495
  message: `Unknown action: ${action}`
8194
8496
  } }));
8497
+ if (action.startsWith("tabgroup_")) {
8498
+ const snapshot = await this.tabHandler.getGroupLockSnapshot(action, params, context);
8499
+ return this.withActionLocks(snapshot.map((tab) => tab.id), async () => {
8500
+ const current = await this.tabHandler.getGroupLockSnapshot(action, params, context);
8501
+ const request = params;
8502
+ const targets = (tabs) => action === "tabgroup_update" ? [] : action === "tabgroup_move" ? tabs : tabs.filter((tab) => (request.tabIds ?? [request.tabId]).includes(tab.id));
8503
+ const identity = (tabs) => targets(tabs).map((tab) => [
8504
+ tab.id,
8505
+ tab.groupId,
8506
+ tab.windowId
8507
+ ]);
8508
+ if (JSON.stringify(identity(snapshot)) !== JSON.stringify(identity(current))) throw new ExpectedOperationError("分组成员或窗口已变化,未执行分组操作");
8509
+ await Promise.all(targets(current).map((tab) => assertManagedTab(tab.id, context, action)));
8510
+ return handler(params, context);
8511
+ });
8512
+ }
8195
8513
  const mutating = PAGE_MUTATIONS.has(action);
8196
8514
  if (mutating || MANAGED_PAGE_ONLY.has(action) || PAGE_READS.has(action)) {
8197
8515
  const request = params;
8198
8516
  const tabId = await getTargetTabId(request?.tabId);
8199
- const operation = (this.actionLocks.get(tabId) ?? Promise.resolve()).catch(() => {}).then(async () => {
8517
+ return this.withActionLocks([tabId], async () => {
8200
8518
  if (request?.deadline !== void 0) {
8201
8519
  const deadline = params?.deadline;
8202
8520
  if (deadline !== void 0 && (typeof deadline !== "number" || !Number.isFinite(deadline))) throw new ExpectedOperationError(JSON.stringify({ error: {
@@ -8243,13 +8561,6 @@ var ActionHandler = class {
8243
8561
  }
8244
8562
  }
8245
8563
  });
8246
- const settled = operation.then(() => {}, () => {});
8247
- this.actionLocks.set(tabId, settled);
8248
- try {
8249
- return await operation;
8250
- } finally {
8251
- if (this.actionLocks.get(tabId) === settled) this.actionLocks.delete(tabId);
8252
- }
8253
8564
  }
8254
8565
  return handler(params, context);
8255
8566
  }
@@ -8261,6 +8572,17 @@ var ActionHandler = class {
8261
8572
  this.debuggerManager.cleanupTab(tabId);
8262
8573
  this.inputEventHandler.cleanupTab(tabId);
8263
8574
  }
8575
+ async withActionLocks(tabIds, action) {
8576
+ const ids = [...new Set(tabIds)].sort((a, b) => a - b);
8577
+ const operation = Promise.all(ids.map((id) => this.actionLocks.get(id))).then(action);
8578
+ const settled = operation.then(() => {}, () => {});
8579
+ for (const id of ids) this.actionLocks.set(id, settled);
8580
+ try {
8581
+ return await operation;
8582
+ } finally {
8583
+ for (const id of ids) if (this.actionLocks.get(id) === settled) this.actionLocks.delete(id);
8584
+ }
8585
+ }
8264
8586
  registerActions() {
8265
8587
  this.actions.set("page_snapshot", async (params) => {
8266
8588
  const tabId = params?.tabId;
@@ -8286,7 +8608,7 @@ var ActionHandler = class {
8286
8608
  success: true,
8287
8609
  targetId: String(tabId),
8288
8610
  allowed,
8289
- managed: isManagedTab(await chrome.tabs.get(tabId)),
8611
+ managed: isManagedTab(await getExistingTab(tabId)),
8290
8612
  scope: "ordinary-read",
8291
8613
  serverInstanceId: context.serverInstanceId,
8292
8614
  url: before.url,
@@ -8431,6 +8753,7 @@ var HttpClient = class {
8431
8753
  pairingTokenLoaded = false;
8432
8754
  allowInsecureNoToken = null;
8433
8755
  lastServerFailureSummary = "";
8756
+ lastDiscoverySummary = null;
8434
8757
  onMessage(handler) {
8435
8758
  this.messageHandler = handler;
8436
8759
  }
@@ -8521,6 +8844,8 @@ var HttpClient = class {
8521
8844
  this.shouldReconnect = false;
8522
8845
  this.generation += 1;
8523
8846
  this.connectingGeneration = null;
8847
+ this.lastDiscoverySummary = null;
8848
+ this.lastServerFailureSummary = "";
8524
8849
  this.stopReconnect();
8525
8850
  for (const controller of this.pendingHealthChecks) controller.abort();
8526
8851
  this.pendingHealthChecks.clear();
@@ -8565,6 +8890,7 @@ var HttpClient = class {
8565
8890
  async getPairingToken() {
8566
8891
  if (this.pairingTokenLoaded) return this.pairingToken ?? "";
8567
8892
  const result = await chrome.storage.local.get(PAIRING_TOKEN_STORAGE_KEY);
8893
+ if (this.pairingTokenLoaded) return this.pairingToken ?? "";
8568
8894
  this.pairingToken = typeof result[PAIRING_TOKEN_STORAGE_KEY] === "string" ? result[PAIRING_TOKEN_STORAGE_KEY] : "";
8569
8895
  this.pairingTokenLoaded = true;
8570
8896
  return this.pairingToken ?? "";
@@ -8572,6 +8898,7 @@ var HttpClient = class {
8572
8898
  async getAllowInsecureNoToken() {
8573
8899
  if (this.allowInsecureNoToken !== null) return this.allowInsecureNoToken;
8574
8900
  const result = await chrome.storage.local.get(ALLOW_INSECURE_NO_TOKEN_STORAGE_KEY);
8901
+ if (this.allowInsecureNoToken !== null) return this.allowInsecureNoToken;
8575
8902
  this.allowInsecureNoToken = result[ALLOW_INSECURE_NO_TOKEN_STORAGE_KEY] !== false;
8576
8903
  return this.allowInsecureNoToken;
8577
8904
  }
@@ -8688,9 +9015,14 @@ var HttpClient = class {
8688
9015
  console.warn(`[HTTP] ${selectedFailures.length} MCP Server candidate(s) rejected after health identification: ` + failureSummary + omittedSuffix);
8689
9016
  }
8690
9017
  this.lastServerFailureSummary = failureSummary;
8691
- if (healthyPorts.length > 0) console.log(`[HTTP] Found ${healthyPorts.length} MCP Server(s) at ports: ${healthyPorts.sort((a, b) => a - b).join(", ")}`);
8692
- else console.debug("[HTTP] No MCP Server found in port range");
8693
- return healthyPorts.sort((a, b) => a - b);
9018
+ healthyPorts.sort((a, b) => a - b);
9019
+ const discoverySummary = healthyPorts.join(",");
9020
+ if (discoverySummary !== this.lastDiscoverySummary) {
9021
+ if (healthyPorts.length > 0) console.log(`[HTTP] Found ${healthyPorts.length} MCP Server(s) at ports: ${healthyPorts.join(", ")}`);
9022
+ else console.debug("[HTTP] No MCP Server found in port range");
9023
+ this.lastDiscoverySummary = discoverySummary;
9024
+ }
9025
+ return healthyPorts;
8694
9026
  }
8695
9027
  async checkPort(port, generation) {
8696
9028
  const controller = new AbortController();
@@ -8815,6 +9147,7 @@ var HttpClient = class {
8815
9147
  //#region src/background/index.ts
8816
9148
  var httpClient = new HttpClient();
8817
9149
  var actionHandler = new ActionHandler();
9150
+ var connectionGeneration = 0;
8818
9151
  httpClient.onConnectionClosed((instanceId) => {
8819
9152
  revokeReadGrants(instanceId).catch((error) => console.error("[MCP] Read grant cleanup failed:", error));
8820
9153
  });
@@ -8831,6 +9164,7 @@ function structuredErrorPayload(error) {
8831
9164
  httpClient.onMessage(async (message, port) => {
8832
9165
  const { id, action, params } = message;
8833
9166
  try {
9167
+ await restoreManagedTabs();
8834
9168
  const result = await actionHandler.execute(action, params, {
8835
9169
  mcpTabGroupId: getMcpTabGroupId(),
8836
9170
  mcpWindowId: getMcpWindowId(),
@@ -8855,17 +9189,21 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
8855
9189
  });
8856
9190
  async function handleInternalMessage(message, sender) {
8857
9191
  switch (message.type) {
8858
- case "CONNECT": return httpClient.connect();
9192
+ case "CONNECT": return connectAfterRestore();
8859
9193
  case "DISCONNECT":
9194
+ ++connectionGeneration;
8860
9195
  httpClient.disconnect();
8861
9196
  return { success: true };
8862
9197
  case "SET_PAIRING_TOKEN":
9198
+ await restoreManagedTabs();
8863
9199
  await httpClient.setPairingToken(message.token);
8864
9200
  return { success: true };
8865
9201
  case "SET_ALLOW_INSECURE_NO_TOKEN":
9202
+ await restoreManagedTabs();
8866
9203
  await httpClient.setAllowInsecureNoToken(message.allow);
8867
9204
  return { success: true };
8868
9205
  case "GET_STATUS": {
9206
+ await restoreManagedTabs();
8869
9207
  const servers = httpClient.getConnectedServers();
8870
9208
  const managed = Number.isSafeInteger(message.tabId) && isManagedTab({ id: message.tabId });
8871
9209
  const readAccess = Number.isSafeInteger(message.tabId) && !managed ? await Promise.all(servers.map(async (server) => ({
@@ -8883,10 +9221,11 @@ async function handleInternalMessage(message, sender) {
8883
9221
  }
8884
9222
  case "SET_READ_ACCESS": {
8885
9223
  if (sender.id !== chrome.runtime.id || sender.url !== chrome.runtime.getURL("src/popup/popup.html")) throw new Error("只读权限只能从 Extension popup 修改");
9224
+ await restoreManagedTabs();
8886
9225
  if (!Number.isSafeInteger(message.tabId) || !Number.isSafeInteger(message.port) || typeof message.allow !== "boolean") throw new Error("tabId、port 或 allow 无效");
8887
9226
  const instanceId = httpClient.getServerInstanceId(message.port);
8888
9227
  if (!instanceId) throw new Error("目标 MCP Server 未连接或未提供连接身份");
8889
- const tab = await chrome.tabs.get(message.tabId);
9228
+ const tab = await getExistingTab(message.tabId);
8890
9229
  const window = await chrome.windows.getLastFocused();
8891
9230
  if (tab.windowId !== window.id || !tab.active) throw new Error("只能从 popup 授权当前窗口的活动页面");
8892
9231
  if (isManagedTab(tab)) throw new Error("受控页面无需普通只读授权");
@@ -8946,6 +9285,7 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
8946
9285
  chrome.webNavigation.onCommitted.addListener((details) => {
8947
9286
  if (details.frameId === 0) {
8948
9287
  advancePageRevision(details.tabId);
9288
+ updateManagedTabDocument(details.tabId).catch((error) => console.warn("[MCP] Managed page document update failed:", error));
8949
9289
  revokeTabReadGrants(details.tabId).catch((error) => console.warn("[MCP] Read grant navigation cleanup failed:", error));
8950
9290
  }
8951
9291
  });
@@ -8964,9 +9304,16 @@ chrome.webNavigation.onReferenceFragmentUpdated.addListener((details) => {
8964
9304
  var KEEPALIVE_ALARM = "mcp-keepalive";
8965
9305
  chrome.alarms.create(KEEPALIVE_ALARM, { periodInMinutes: 1 });
8966
9306
  chrome.alarms.onAlarm.addListener((alarm) => {
8967
- if (alarm.name === KEEPALIVE_ALARM) httpClient.connect();
8968
- });
8969
- setTimeout(() => {
8970
- restoreManagedTabs().catch((error) => console.error("[MCP] Failed to restore managed pages:", error)).then(() => httpClient.connect());
8971
- }, 500);
9307
+ if (alarm.name === KEEPALIVE_ALARM) connectAfterRestore().catch((error) => console.error("[MCP] Auto-connect failed:", error));
9308
+ });
9309
+ async function connectAfterRestore() {
9310
+ const requestedGeneration = connectionGeneration;
9311
+ await restoreManagedTabs();
9312
+ if (requestedGeneration !== connectionGeneration) return {
9313
+ connected: 0,
9314
+ ports: []
9315
+ };
9316
+ return httpClient.connect();
9317
+ }
9318
+ connectAfterRestore().catch((error) => console.error("[MCP] Auto-connect failed:", error));
8972
9319
  //#endregion