@pyrokine/mcp-chrome 2.4.0 → 2.4.4

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 (116) hide show
  1. package/README.md +220 -149
  2. package/README_zh.md +245 -179
  3. package/dist/anti-detection/behavior.js +1 -1
  4. package/dist/anti-detection/behavior.js.map +1 -1
  5. package/dist/anti-detection/injection.d.ts.map +1 -1
  6. package/dist/anti-detection/injection.js +2 -1
  7. package/dist/anti-detection/injection.js.map +1 -1
  8. package/dist/cdp/client.d.ts +2 -2
  9. package/dist/cdp/client.d.ts.map +1 -1
  10. package/dist/cdp/client.js +7 -4
  11. package/dist/cdp/client.js.map +1 -1
  12. package/dist/core/browser-driver.d.ts +9 -3
  13. package/dist/core/browser-driver.d.ts.map +1 -1
  14. package/dist/core/browser-driver.js +1 -0
  15. package/dist/core/browser-driver.js.map +1 -1
  16. package/dist/core/errors.d.ts +9 -0
  17. package/dist/core/errors.d.ts.map +1 -1
  18. package/dist/core/errors.js +16 -1
  19. package/dist/core/errors.js.map +1 -1
  20. package/dist/core/os-mouse.d.ts +65 -0
  21. package/dist/core/os-mouse.d.ts.map +1 -0
  22. package/dist/core/os-mouse.js +334 -0
  23. package/dist/core/os-mouse.js.map +1 -0
  24. package/dist/core/session.d.ts +16 -6
  25. package/dist/core/session.d.ts.map +1 -1
  26. package/dist/core/session.js +160 -55
  27. package/dist/core/session.js.map +1 -1
  28. package/dist/core/types.d.ts +10 -0
  29. package/dist/core/types.d.ts.map +1 -1
  30. package/dist/core/types.js +2 -0
  31. package/dist/core/types.js.map +1 -1
  32. package/dist/core/unified-session.d.ts +34 -5
  33. package/dist/core/unified-session.d.ts.map +1 -1
  34. package/dist/core/unified-session.js +172 -30
  35. package/dist/core/unified-session.js.map +1 -1
  36. package/dist/extension/bridge.d.ts +24 -2
  37. package/dist/extension/bridge.d.ts.map +1 -1
  38. package/dist/extension/bridge.js +32 -1
  39. package/dist/extension/bridge.js.map +1 -1
  40. package/dist/extension/http-server.d.ts +17 -0
  41. package/dist/extension/http-server.d.ts.map +1 -1
  42. package/dist/extension/http-server.js +69 -9
  43. package/dist/extension/http-server.js.map +1 -1
  44. package/dist/extension/index.d.ts +1 -0
  45. package/dist/extension/index.d.ts.map +1 -1
  46. package/dist/extension/index.js.map +1 -1
  47. package/dist/tools/browse.d.ts +1 -1
  48. package/dist/tools/browse.d.ts.map +1 -1
  49. package/dist/tools/browse.js +73 -26
  50. package/dist/tools/browse.js.map +1 -1
  51. package/dist/tools/challenge.d.ts +153 -0
  52. package/dist/tools/challenge.d.ts.map +1 -0
  53. package/dist/tools/challenge.js +573 -0
  54. package/dist/tools/challenge.js.map +1 -0
  55. package/dist/tools/cookies.d.ts.map +1 -1
  56. package/dist/tools/cookies.js +8 -4
  57. package/dist/tools/cookies.js.map +1 -1
  58. package/dist/tools/diagnostics.d.ts +2 -2
  59. package/dist/tools/diagnostics.d.ts.map +1 -1
  60. package/dist/tools/diagnostics.js +28 -9
  61. package/dist/tools/diagnostics.js.map +1 -1
  62. package/dist/tools/evaluate.d.ts +8 -0
  63. package/dist/tools/evaluate.d.ts.map +1 -1
  64. package/dist/tools/evaluate.js +92 -14
  65. package/dist/tools/evaluate.js.map +1 -1
  66. package/dist/tools/extract.d.ts.map +1 -1
  67. package/dist/tools/extract.js +119 -59
  68. package/dist/tools/extract.js.map +1 -1
  69. package/dist/tools/input.d.ts +4 -0
  70. package/dist/tools/input.d.ts.map +1 -1
  71. package/dist/tools/input.js +248 -94
  72. package/dist/tools/input.js.map +1 -1
  73. package/dist/tools/logs.d.ts +7 -4
  74. package/dist/tools/logs.d.ts.map +1 -1
  75. package/dist/tools/logs.js +11 -8
  76. package/dist/tools/logs.js.map +1 -1
  77. package/dist/tools/manage.d.ts.map +1 -1
  78. package/dist/tools/manage.js +20 -7
  79. package/dist/tools/manage.js.map +1 -1
  80. package/dist/tools/network-sanitizer.d.ts +15 -0
  81. package/dist/tools/network-sanitizer.d.ts.map +1 -0
  82. package/dist/tools/network-sanitizer.js +62 -0
  83. package/dist/tools/network-sanitizer.js.map +1 -0
  84. package/dist/tools/png.js +5 -3
  85. package/dist/tools/png.js.map +1 -1
  86. package/dist/tools/post-condition.d.ts.map +1 -1
  87. package/dist/tools/post-condition.js +17 -4
  88. package/dist/tools/post-condition.js.map +1 -1
  89. package/dist/tools/target-diagnostics.d.ts +7 -0
  90. package/dist/tools/target-diagnostics.d.ts.map +1 -1
  91. package/dist/tools/target-diagnostics.js +25 -2
  92. package/dist/tools/target-diagnostics.js.map +1 -1
  93. package/dist/tools/wait.d.ts.map +1 -1
  94. package/dist/tools/wait.js +42 -40
  95. package/dist/tools/wait.js.map +1 -1
  96. package/extension/dist/assets/content.ts-Cj_iiU2s.js +25 -0
  97. package/extension/dist/assets/{index.ts-BMmrcSQ6.js → index.ts-Bqcu2qiN.js} +620 -290
  98. package/extension/dist/manifest.json +3 -3
  99. package/extension/dist/service-worker-loader.js +1 -1
  100. package/extension/dist/src/popup/popup.html +44 -44
  101. package/package.json +8 -7
  102. package/dist/extension/native-host-installer.d.ts +0 -21
  103. package/dist/extension/native-host-installer.d.ts.map +0 -1
  104. package/dist/extension/native-host-installer.js +0 -147
  105. package/dist/extension/native-host-installer.js.map +0 -1
  106. package/dist/extension/socket-server.d.ts +0 -32
  107. package/dist/extension/socket-server.d.ts.map +0 -1
  108. package/dist/extension/socket-server.js +0 -177
  109. package/dist/extension/socket-server.js.map +0 -1
  110. package/dist/extension/ws-server.d.ts +0 -40
  111. package/dist/extension/ws-server.d.ts.map +0 -1
  112. package/dist/extension/ws-server.js +0 -246
  113. package/dist/extension/ws-server.js.map +0 -1
  114. package/dist/native-host/index.js +0 -280
  115. package/dist/native-host/mcp-chrome-host +0 -2
  116. package/extension/dist/assets/content.ts-pEASbjEL.js +0 -6
@@ -15,6 +15,272 @@ function isExpectedOperationError(err) {
15
15
  return err instanceof ExpectedOperationError;
16
16
  }
17
17
  //#endregion
18
+ //#region src/background/tab-state.ts
19
+ /**
20
+ * Managed tab/window 状态与 storage 恢复。
21
+ */
22
+ var STORAGE_KEY = "mcp_managed_tab_ids";
23
+ var mcpTabGroupId = null;
24
+ var mcpWindowId = null;
25
+ var managedTabIds = /* @__PURE__ */ new Set();
26
+ function getMcpTabGroupId() {
27
+ return mcpTabGroupId;
28
+ }
29
+ function getMcpWindowId() {
30
+ return mcpWindowId;
31
+ }
32
+ function setMcpTabGroupId(groupId) {
33
+ mcpTabGroupId = groupId;
34
+ }
35
+ function setMcpWindowId(windowId) {
36
+ mcpWindowId = windowId;
37
+ }
38
+ async function markManagedTab(tabId) {
39
+ managedTabIds.add(tabId);
40
+ await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
41
+ }
42
+ async function unmarkManagedTab(tabId) {
43
+ managedTabIds.delete(tabId);
44
+ await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
45
+ }
46
+ function isManagedTab(tab, context) {
47
+ if (tab.id !== void 0 && managedTabIds.has(tab.id)) return true;
48
+ return context.mcpTabGroupId !== null && tab.groupId === context.mcpTabGroupId;
49
+ }
50
+ /** Extension 启动时调用,从 storage 恢复 managed tab 集合 */
51
+ async function restoreManagedTabs() {
52
+ const result = await chrome.storage.local.get(STORAGE_KEY);
53
+ const stored = Array.isArray(result[STORAGE_KEY]) ? result[STORAGE_KEY] : [];
54
+ for (const id of stored) managedTabIds.add(id);
55
+ const tabs = await chrome.tabs.query({});
56
+ const existingIds = new Set(tabs.map((t) => t.id).filter((id) => id !== void 0));
57
+ for (const id of managedTabIds) if (!existingIds.has(id)) managedTabIds.delete(id);
58
+ await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
59
+ }
60
+ //#endregion
61
+ //#region src/background/action-utils.ts
62
+ function isRestrictedUrl(url) {
63
+ if (!url) return true;
64
+ return url === "about:blank" || url.startsWith("about:") || url.startsWith("chrome://") || url.startsWith("chrome-extension://");
65
+ }
66
+ async function assertScriptable(tabId) {
67
+ const tab = await chrome.tabs.get(tabId);
68
+ if (isRestrictedUrl(tab.url)) throw new ExpectedOperationError(`Cannot execute on restricted URL "${tab.url}". Navigate to an http/https page first.`);
69
+ }
70
+ async function getTargetTabId(tabId) {
71
+ if (tabId !== void 0 && tabId !== null) {
72
+ try {
73
+ await chrome.tabs.get(tabId);
74
+ } catch {
75
+ throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
76
+ }
77
+ return tabId;
78
+ }
79
+ const [activeTab] = await chrome.tabs.query({
80
+ active: true,
81
+ currentWindow: true
82
+ });
83
+ if (!activeTab?.id) throw new ExpectedOperationError("No active tab found");
84
+ return activeTab.id;
85
+ }
86
+ function tabToInfo(tab, context) {
87
+ return {
88
+ id: tab.id,
89
+ url: tab.url || "",
90
+ title: tab.title || "",
91
+ active: tab.active,
92
+ windowId: tab.windowId,
93
+ index: tab.index,
94
+ groupId: tab.groupId,
95
+ pinned: tab.pinned,
96
+ incognito: tab.incognito,
97
+ managed: isManagedTab(tab, context),
98
+ status: tab.status || "unknown"
99
+ };
100
+ }
101
+ async function assertManagedTab(tabId, context, operation) {
102
+ let tab;
103
+ try {
104
+ tab = await chrome.tabs.get(tabId);
105
+ } catch {
106
+ throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
107
+ }
108
+ if (!isManagedTab(tab, context)) throw new ExpectedOperationError(`${operation} 拒绝操作非托管 tab, ${JSON.stringify({
109
+ tabId,
110
+ managed: false,
111
+ groupId: tab.groupId,
112
+ mcpTabGroupId: context.mcpTabGroupId,
113
+ windowId: tab.windowId,
114
+ mcpWindowId: context.mcpWindowId
115
+ })}, 请从 browse(action="list") 选择 managed=true 的 tab,或用 manage(action="newPage") 创建受控页面`);
116
+ return tab;
117
+ }
118
+ var FRAME_PROBE_TIMEOUT_MS = 500;
119
+ var pendingDomFrameProbes = /* @__PURE__ */ new Map();
120
+ function recordDomFrameProbe(message, sender) {
121
+ const pending = pendingDomFrameProbes.get(message.token);
122
+ if (!pending || sender.tab?.id !== pending.tabId || sender.frameId === void 0 || sender.frameId === 0 || !Number.isInteger(message.index) || message.index < 0) return { accepted: false };
123
+ const frameIds = pending.frameIdsByIndex.get(message.index) ?? [];
124
+ if (!frameIds.includes(sender.frameId)) {
125
+ frameIds.push(sender.frameId);
126
+ pending.frameIdsByIndex.set(message.index, frameIds);
127
+ }
128
+ return { accepted: true };
129
+ }
130
+ /**
131
+ * 将父文档里的 DOM iframe 与 Chrome frameId 建立可验证映射
132
+ *
133
+ * webNavigation 可能包含页面 DOM 不可见的其他 Extension frame,因此不能按两个列表的顺序配对
134
+ * 这里向每个 DOM iframe 的 contentWindow 发送一次随机 probe,再从对应 content script 的 sender 读取实际 frameId
135
+ */
136
+ async function getDomFrameSnapshot(tabId, parentFrameId, selection) {
137
+ const token = crypto.randomUUID();
138
+ const pendingProbe = {
139
+ tabId,
140
+ frameIdsByIndex: /* @__PURE__ */ new Map()
141
+ };
142
+ pendingDomFrameProbes.set(token, pendingProbe);
143
+ try {
144
+ const parentResult = (await chrome.scripting.executeScript({
145
+ target: {
146
+ tabId,
147
+ frameIds: [parentFrameId]
148
+ },
149
+ func: async (probeToken, requestedSelection, timeoutMs) => {
150
+ const iframes = Array.from(document.querySelectorAll("iframe, frame"));
151
+ let selectedIndex = null;
152
+ let selectionStatus = "not-requested";
153
+ let selectionError;
154
+ if (typeof requestedSelection === "number") if (requestedSelection < 0 || requestedSelection >= iframes.length) selectionStatus = "out-of-range";
155
+ else {
156
+ selectedIndex = requestedSelection;
157
+ selectionStatus = "found";
158
+ }
159
+ else if (typeof requestedSelection === "string") try {
160
+ const selected = document.querySelector(requestedSelection);
161
+ if (!selected) selectionStatus = "not-found";
162
+ else if (!selected.matches("iframe, frame")) selectionStatus = "not-frame";
163
+ else {
164
+ selectedIndex = iframes.indexOf(selected);
165
+ selectionStatus = selectedIndex >= 0 ? "found" : "not-found";
166
+ }
167
+ } catch (error) {
168
+ selectionStatus = "invalid-selector";
169
+ selectionError = (error instanceof Error ? error.message : String(error)).slice(0, 300);
170
+ }
171
+ const acknowledged = await Promise.all(iframes.map((frame, index) => new Promise((resolve) => {
172
+ const child = frame.contentWindow;
173
+ if (!child) {
174
+ resolve(false);
175
+ return;
176
+ }
177
+ let settled = false;
178
+ const finish = (value) => {
179
+ if (settled) return;
180
+ settled = true;
181
+ window.clearTimeout(timer);
182
+ window.removeEventListener("message", onMessage);
183
+ resolve(value);
184
+ };
185
+ const onMessage = (event) => {
186
+ const data = event.data;
187
+ if (event.source === child && data?.type === "mcp-frame-probe-ack" && data.token === probeToken && data.index === index) finish(true);
188
+ };
189
+ const timer = window.setTimeout(() => finish(false), timeoutMs);
190
+ window.addEventListener("message", onMessage);
191
+ child.postMessage({
192
+ type: "mcp-frame-probe",
193
+ token: probeToken,
194
+ index
195
+ }, "*");
196
+ })));
197
+ return {
198
+ parent: {
199
+ title: document.title || null,
200
+ rect: {
201
+ x: 0,
202
+ y: 0,
203
+ width: window.innerWidth,
204
+ height: window.innerHeight
205
+ }
206
+ },
207
+ frames: iframes.map((frame, index) => {
208
+ const rect = frame.getBoundingClientRect();
209
+ return {
210
+ index,
211
+ acknowledged: acknowledged[index],
212
+ url: frame.src || "",
213
+ title: frame.title || null,
214
+ name: frame.name || null,
215
+ selector: frame.id ? `#${CSS.escape(frame.id)}` : `${frame.tagName.toLowerCase()}:nth-of-type(${index + 1})`,
216
+ rect: {
217
+ x: rect.x,
218
+ y: rect.y,
219
+ width: rect.width,
220
+ height: rect.height
221
+ },
222
+ contentOffset: {
223
+ x: rect.x + frame.clientLeft,
224
+ y: rect.y + frame.clientTop
225
+ }
226
+ };
227
+ }),
228
+ selectedIndex,
229
+ selectionStatus,
230
+ selectionError
231
+ };
232
+ },
233
+ args: [
234
+ token,
235
+ selection ?? null,
236
+ FRAME_PROBE_TIMEOUT_MS
237
+ ]
238
+ }))[0]?.result;
239
+ if (!parentResult) throw new ExpectedOperationError(`无法读取 parent frame ${parentFrameId} 的 iframe DOM`);
240
+ return {
241
+ parent: parentResult.parent,
242
+ frames: parentResult.frames.map(({ acknowledged, ...frame }) => {
243
+ const candidateFrameIds = acknowledged ? pendingProbe.frameIdsByIndex.get(frame.index) ?? [] : [];
244
+ return {
245
+ ...frame,
246
+ frameId: candidateFrameIds.length === 1 ? candidateFrameIds[0] : null,
247
+ candidateFrameIds: candidateFrameIds.slice(0, 10)
248
+ };
249
+ }),
250
+ selectedIndex: parentResult.selectedIndex,
251
+ selectionStatus: parentResult.selectionStatus,
252
+ ...parentResult.selectionError ? { selectionError: parentResult.selectionError } : {}
253
+ };
254
+ } finally {
255
+ pendingDomFrameProbes.delete(token);
256
+ }
257
+ }
258
+ /**
259
+ * 递归计算 iframe 在页面坐标系中的偏移量
260
+ *
261
+ * 对于嵌套 iframe,递归累加各层偏移,clientLeft/clientTop 补偿 iframe border
262
+ */
263
+ async function getFrameOffset(tabId, frameId) {
264
+ const targetFrame = (await chrome.webNavigation.getAllFrames({ tabId }))?.find((frame) => frame.frameId === frameId);
265
+ if (!targetFrame || targetFrame.parentFrameId === -1) return null;
266
+ if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return null;
267
+ let parentOffset = {
268
+ x: 0,
269
+ y: 0
270
+ };
271
+ if (targetFrame.parentFrameId !== 0) {
272
+ const resolvedParentOffset = await getFrameOffset(tabId, targetFrame.parentFrameId);
273
+ if (!resolvedParentOffset) return null;
274
+ parentOffset = resolvedParentOffset;
275
+ }
276
+ const mappedFrame = (await getDomFrameSnapshot(tabId, targetFrame.parentFrameId)).frames.find((frame) => frame.frameId === frameId);
277
+ if (!mappedFrame) return null;
278
+ return {
279
+ x: parentOffset.x + mappedFrame.contentOffset.x,
280
+ y: parentOffset.y + mappedFrame.contentOffset.y
281
+ };
282
+ }
283
+ //#endregion
18
284
  //#region node_modules/zod/v4/core/core.js
19
285
  var _a$1;
20
286
  function $constructor(name, initializer, params) {
@@ -4359,6 +4625,22 @@ var EvaluateSchema = object({
4359
4625
  frameId: frameIdOpt,
4360
4626
  code: string().min(1)
4361
4627
  });
4628
+ var ViewportMetricsSchema = object({
4629
+ tabId: tabIdOpt,
4630
+ frameId: frameIdOpt
4631
+ });
4632
+ var ChallengeInspectSchema = object({
4633
+ tabId: tabIdOpt,
4634
+ frameId: frameIdOpt,
4635
+ challengeSelectors: array(string()),
4636
+ deniedSelectors: array(string()),
4637
+ widgetSelectors: array(string()),
4638
+ verifyButtonSelectors: array(string()),
4639
+ frameSelectors: array(string()),
4640
+ titleNeedles: array(string()),
4641
+ textMarkers: array(string()),
4642
+ originResponsePendingTextMarkers: array(string())
4643
+ });
4362
4644
  var FindSchema = object({
4363
4645
  tabId: tabIdOpt,
4364
4646
  frameId: frameIdOpt,
@@ -4421,7 +4703,13 @@ var CookiesClearSchema = object({
4421
4703
  url: string().optional(),
4422
4704
  domain: string().optional(),
4423
4705
  name: string().optional()
4424
- }).partial().optional();
4706
+ }).partial().superRefine((value, ctx) => {
4707
+ if (!value.url && !value.domain) ctx.addIssue({
4708
+ code: "custom",
4709
+ path: ["url"],
4710
+ message: "cookies action=clear 必须带 url 或 domain 过滤参数"
4711
+ });
4712
+ }).optional();
4425
4713
  var DebuggerAttachSchema = object({ tabId: tabIdOpt }).partial().optional();
4426
4714
  var DebuggerDetachSchema = DebuggerAttachSchema;
4427
4715
  var DebuggerSendSchema = object({
@@ -4509,6 +4797,7 @@ var ConsoleEnableSchema = TabIdOnly;
4509
4797
  var ConsoleClearSchema = TabIdOnly;
4510
4798
  var NetworkEnableSchema = TabIdOnly;
4511
4799
  var NetworkClearSchema = TabIdOnly;
4800
+ var NetworkChallengeStateSchema = TabIdOnly;
4512
4801
  var ConsoleGetSchema = object({
4513
4802
  tabId: tabIdOpt,
4514
4803
  level: string().optional(),
@@ -4567,172 +4856,10 @@ var EvaluateInFrameSchema = object({
4567
4856
  tabId: tabIdOpt,
4568
4857
  frameId: number().int().nonnegative(),
4569
4858
  expression: string().min(1),
4570
- timeout: number().nonnegative().optional()
4859
+ timeout: number().nonnegative().optional(),
4860
+ staleContextRetry: _enum(["never", "readOnly"]).default("never")
4571
4861
  });
4572
4862
  //#endregion
4573
- //#region src/background/tab-state.ts
4574
- /**
4575
- * Managed tab/window 状态与 storage 恢复。
4576
- */
4577
- var STORAGE_KEY = "mcp_managed_tab_ids";
4578
- var mcpTabGroupId = null;
4579
- var mcpWindowId = null;
4580
- var managedTabIds = /* @__PURE__ */ new Set();
4581
- function getMcpTabGroupId() {
4582
- return mcpTabGroupId;
4583
- }
4584
- function getMcpWindowId() {
4585
- return mcpWindowId;
4586
- }
4587
- function setMcpTabGroupId(groupId) {
4588
- mcpTabGroupId = groupId;
4589
- }
4590
- function setMcpWindowId(windowId) {
4591
- mcpWindowId = windowId;
4592
- }
4593
- async function markManagedTab(tabId) {
4594
- managedTabIds.add(tabId);
4595
- await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
4596
- }
4597
- async function unmarkManagedTab(tabId) {
4598
- managedTabIds.delete(tabId);
4599
- await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
4600
- }
4601
- function isManagedTab(tab, context) {
4602
- if (tab.id !== void 0 && managedTabIds.has(tab.id)) return true;
4603
- return context.mcpTabGroupId !== null && tab.groupId === context.mcpTabGroupId;
4604
- }
4605
- /** Extension 启动时调用,从 storage 恢复 managed tab 集合 */
4606
- async function restoreManagedTabs() {
4607
- const result = await chrome.storage.local.get(STORAGE_KEY);
4608
- const stored = Array.isArray(result[STORAGE_KEY]) ? result[STORAGE_KEY] : [];
4609
- for (const id of stored) managedTabIds.add(id);
4610
- const tabs = await chrome.tabs.query({});
4611
- const existingIds = new Set(tabs.map((t) => t.id).filter((id) => id !== void 0));
4612
- for (const id of managedTabIds) if (!existingIds.has(id)) managedTabIds.delete(id);
4613
- await chrome.storage.local.set({ [STORAGE_KEY]: [...managedTabIds] });
4614
- }
4615
- //#endregion
4616
- //#region src/background/action-utils.ts
4617
- /**
4618
- * Action 处理器共享工具函数
4619
- *
4620
- * 纯工具函数,不依赖任何实例状态,可被多个 handler 模块直接 import 使用
4621
- */
4622
- function isRestrictedUrl(url) {
4623
- if (!url) return true;
4624
- return url === "about:blank" || url.startsWith("about:") || url.startsWith("chrome://") || url.startsWith("chrome-extension://");
4625
- }
4626
- async function assertScriptable(tabId) {
4627
- const tab = await chrome.tabs.get(tabId);
4628
- if (isRestrictedUrl(tab.url)) throw new ExpectedOperationError(`Cannot execute on restricted URL "${tab.url}". Navigate to an http/https page first.`);
4629
- }
4630
- async function getTargetTabId(tabId) {
4631
- if (tabId !== void 0 && tabId !== null) {
4632
- try {
4633
- await chrome.tabs.get(tabId);
4634
- } catch {
4635
- throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
4636
- }
4637
- return tabId;
4638
- }
4639
- const [activeTab] = await chrome.tabs.query({
4640
- active: true,
4641
- currentWindow: true
4642
- });
4643
- if (!activeTab?.id) throw new ExpectedOperationError("No active tab found");
4644
- return activeTab.id;
4645
- }
4646
- function tabToInfo(tab, context) {
4647
- return {
4648
- id: tab.id,
4649
- url: tab.url || "",
4650
- title: tab.title || "",
4651
- active: tab.active,
4652
- windowId: tab.windowId,
4653
- index: tab.index,
4654
- groupId: tab.groupId,
4655
- pinned: tab.pinned,
4656
- incognito: tab.incognito,
4657
- managed: isManagedTab(tab, context),
4658
- status: tab.status || "unknown"
4659
- };
4660
- }
4661
- async function assertManagedTab(tabId, context, operation) {
4662
- let tab;
4663
- try {
4664
- tab = await chrome.tabs.get(tabId);
4665
- } catch {
4666
- throw new ExpectedOperationError(`Tab ${tabId} 不存在(可能已被关闭)`);
4667
- }
4668
- if (!isManagedTab(tab, context)) throw new ExpectedOperationError(`${operation} 拒绝操作非托管 tab, ${JSON.stringify({
4669
- tabId,
4670
- managed: false,
4671
- groupId: tab.groupId,
4672
- mcpTabGroupId: context.mcpTabGroupId,
4673
- windowId: tab.windowId,
4674
- mcpWindowId: context.mcpWindowId
4675
- })}, 请使用 browse(action="list") 选择 managed=true 的受控 tab, 或用 manage(action="newPage") 创建受控页面`);
4676
- return tab;
4677
- }
4678
- /**
4679
- * 递归计算 iframe 在页面坐标系中的偏移量
4680
- *
4681
- * 对于嵌套 iframe,递归累加各层偏移,
4682
- * 当多个 iframe 共享同一 URL 时,优先按同 URL 的出现顺序匹配,
4683
- * clientLeft/clientTop 补偿 iframe 的 border,确保坐标指向内容区域起点
4684
- */
4685
- async function getFrameOffset(tabId, frameId) {
4686
- const allFrames = await chrome.webNavigation.getAllFrames({ tabId });
4687
- if (!allFrames) return null;
4688
- const targetFrame = allFrames.find((f) => f.frameId === frameId);
4689
- if (!targetFrame || targetFrame.parentFrameId === -1) return null;
4690
- if (isRestrictedUrl((await chrome.tabs.get(tabId)).url)) return null;
4691
- let parentOffset = {
4692
- x: 0,
4693
- y: 0
4694
- };
4695
- if (targetFrame.parentFrameId !== 0) {
4696
- const po = await getFrameOffset(tabId, targetFrame.parentFrameId);
4697
- if (po) parentOffset = po;
4698
- }
4699
- const siblingFrames = allFrames.filter((f) => f.parentFrameId === targetFrame.parentFrameId && f.frameId !== targetFrame.parentFrameId);
4700
- const frameIndex = siblingFrames.findIndex((f) => f.frameId === frameId);
4701
- const sameUrlIndex = siblingFrames.filter((f) => f.url === targetFrame.url).findIndex((f) => f.frameId === frameId);
4702
- const localOffset = (await chrome.scripting.executeScript({
4703
- target: {
4704
- tabId,
4705
- frameIds: [targetFrame.parentFrameId]
4706
- },
4707
- world: "MAIN",
4708
- func: (frameUrl, frameIndex, sameUrlIndex) => {
4709
- const iframes = Array.from(document.querySelectorAll("iframe, frame"));
4710
- const urlMatches = frameUrl ? iframes.filter((iframe) => iframe.src === frameUrl) : [];
4711
- let target;
4712
- if (urlMatches.length === 1) target = urlMatches[0];
4713
- else if (sameUrlIndex >= 0 && sameUrlIndex < urlMatches.length) target = urlMatches[sameUrlIndex];
4714
- else if (frameIndex >= 0 && frameIndex < iframes.length) target = iframes[frameIndex];
4715
- else if (urlMatches.length > 0) target = urlMatches[0];
4716
- if (!target) return null;
4717
- const rect = target.getBoundingClientRect();
4718
- return {
4719
- x: rect.x + target.clientLeft,
4720
- y: rect.y + target.clientTop
4721
- };
4722
- },
4723
- args: [
4724
- targetFrame.url,
4725
- frameIndex,
4726
- sameUrlIndex
4727
- ]
4728
- }))[0]?.result;
4729
- if (!localOffset) return null;
4730
- return {
4731
- x: parentOffset.x + localOffset.x,
4732
- y: parentOffset.y + localOffset.y
4733
- };
4734
- }
4735
- //#endregion
4736
4863
  //#region src/background/debugger-manager.ts
4737
4864
  var DebuggerBlockedError = class extends ExpectedOperationError {
4738
4865
  code = "DEBUGGER_BLOCKED";
@@ -5556,7 +5683,7 @@ async function simulateKeyboardType(text, delay) {
5556
5683
  };
5557
5684
  if (!(activeElement.tagName === "INPUT" || activeElement.tagName === "TEXTAREA" || activeElement.isContentEditable)) return {
5558
5685
  success: false,
5559
- error: `Active element is not inputable: ${activeElement.tagName}`
5686
+ error: `Active element does not accept keyboard input: ${activeElement.tagName}`
5560
5687
  };
5561
5688
  const proto = Object.getPrototypeOf(activeElement);
5562
5689
  const valueSetter = Object.getOwnPropertyDescriptor(proto, "value") ?? Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value") ?? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value");
@@ -6052,6 +6179,154 @@ function getComputedStyleFromElement(refId, prop) {
6052
6179
  }
6053
6180
  return cs.getPropertyValue(prop);
6054
6181
  }
6182
+ function inspectChallengePage(options) {
6183
+ const title = document.title || "";
6184
+ const url = location.href || "";
6185
+ const visibleBodyText = (document.body && document.body.innerText ? document.body.innerText : "").replace(/\s+/g, " ");
6186
+ const isVisible = (el) => {
6187
+ if (!el) return false;
6188
+ const style = window.getComputedStyle(el);
6189
+ if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) return false;
6190
+ const rect = el.getBoundingClientRect();
6191
+ return rect.width > 0 && rect.height > 0;
6192
+ };
6193
+ const bringIntoView = (el) => {
6194
+ if (!el || typeof el.scrollIntoView !== "function") return;
6195
+ el.scrollIntoView({
6196
+ block: "center",
6197
+ inline: "nearest"
6198
+ });
6199
+ };
6200
+ const hits = (selectors) => selectors.filter((selector) => {
6201
+ try {
6202
+ return Array.from(document.querySelectorAll(selector)).some(isVisible);
6203
+ } catch {
6204
+ return false;
6205
+ }
6206
+ });
6207
+ const isCloudflareFrame = (el) => {
6208
+ if (!el) return false;
6209
+ if (el.tagName.toUpperCase() === "IFRAME") {
6210
+ const src = String(el.getAttribute("src") || el.src || "");
6211
+ return src.includes("challenges.cloudflare.com") || src.includes("turnstile");
6212
+ }
6213
+ return Boolean(el.closest(options.frameSelectors.join(",")));
6214
+ };
6215
+ const selectorHits = hits(options.challengeSelectors);
6216
+ const deniedHits = hits(options.deniedSelectors);
6217
+ const widgetHits = hits(options.widgetSelectors);
6218
+ const frameHits = hits(options.frameSelectors);
6219
+ const cloudflareFramePresent = Array.from(document.querySelectorAll("iframe")).some((el) => isCloudflareFrame(el));
6220
+ const normalizedTitle = title.trim().toLowerCase().replace(/…/g, "...");
6221
+ const titlePending = options.titleNeedles.some((needle) => normalizedTitle.includes(String(needle).toLowerCase()));
6222
+ const textHits = options.textMarkers.filter((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
6223
+ const originResponsePending = options.originResponsePendingTextMarkers.some((marker) => visibleBodyText.toLowerCase().includes(String(marker).toLowerCase()));
6224
+ const interstitialPending = selectorHits.length > 0 || titlePending || textHits.length > 0;
6225
+ const findVisibleTurnstileBox = () => {
6226
+ const input = document.querySelector("input[name=\"cf-turnstile-response\"]");
6227
+ if (!input) return null;
6228
+ const candidates = [];
6229
+ let node = input.parentElement;
6230
+ while (node && node !== document.documentElement) {
6231
+ if (isVisible(node)) {
6232
+ const rect = node.getBoundingClientRect();
6233
+ if (rect.width >= 120 && rect.height >= 40) candidates.push(node);
6234
+ }
6235
+ node = node.parentElement;
6236
+ }
6237
+ if (candidates.length === 0) return null;
6238
+ return candidates.find((el) => {
6239
+ const rect = el.getBoundingClientRect();
6240
+ return rect.width >= 250 && rect.width <= 340 && rect.height >= 50 && rect.height <= 85;
6241
+ }) || candidates[0];
6242
+ };
6243
+ const turnstileBox = findVisibleTurnstileBox();
6244
+ const hostVerify = Array.from(document.querySelectorAll(options.verifyButtonSelectors.join(","))).find(isVisible);
6245
+ const useIframeClick = cloudflareFramePresent || !hostVerify && interstitialPending && Boolean(document.querySelector("input[name=\"cf-turnstile-response\"]"));
6246
+ const turnstilePresent = widgetHits.length > 0 || useIframeClick || interstitialPending && frameHits.length > 0 || Boolean(turnstileBox);
6247
+ const pointFromRect = (rect, kind) => {
6248
+ if (!rect || rect.width < 8 || rect.height < 8) return null;
6249
+ const y = Math.round(rect.top + Math.min(rect.height, 65) / 2);
6250
+ if (kind === "verify") return {
6251
+ x: Math.round(rect.left + rect.width / 2),
6252
+ y
6253
+ };
6254
+ const widgetWidth = Math.min(rect.width, 300);
6255
+ return {
6256
+ x: Math.round(rect.left + Math.min(20, Math.max(14, widgetWidth / 15))),
6257
+ y
6258
+ };
6259
+ };
6260
+ let clickPoint = null;
6261
+ let clickTargetKind = null;
6262
+ let clickSource = null;
6263
+ const setClickTarget = (el, kind) => {
6264
+ if (!el) return;
6265
+ bringIntoView(el);
6266
+ const point = pointFromRect(el.getBoundingClientRect(), kind);
6267
+ if (!point) return;
6268
+ clickPoint = point;
6269
+ clickTargetKind = kind;
6270
+ clickSource = isCloudflareFrame(el) || useIframeClick ? "iframe" : "page";
6271
+ };
6272
+ if (hostVerify) setClickTarget(hostVerify, "verify");
6273
+ if (!clickPoint && turnstileBox) {
6274
+ const boxRect = turnstileBox.getBoundingClientRect();
6275
+ if (boxRect.width <= 340 && boxRect.height <= 85) setClickTarget(turnstileBox, "widget");
6276
+ }
6277
+ if (!clickPoint && turnstilePresent) {
6278
+ const frame = Array.from(document.querySelectorAll(options.frameSelectors.join(","))).find(isVisible);
6279
+ if (frame) setClickTarget(frame, "widget");
6280
+ }
6281
+ if (!clickPoint && turnstilePresent) {
6282
+ const widget = Array.from(document.querySelectorAll(options.widgetSelectors.join(","))).find(isVisible);
6283
+ if (widget) setClickTarget(widget, "widget");
6284
+ }
6285
+ if (!clickPoint && turnstilePresent) {
6286
+ const nodes = Array.from(document.querySelectorAll("div"));
6287
+ for (const node of nodes) {
6288
+ if (!isVisible(node)) continue;
6289
+ const rect = node.getBoundingClientRect();
6290
+ if (rect.width >= 280 && rect.width <= 320 && rect.height >= 50 && rect.height <= 80) {
6291
+ setClickTarget(node, "widget");
6292
+ break;
6293
+ }
6294
+ }
6295
+ }
6296
+ if (!clickPoint && turnstileBox) setClickTarget(turnstileBox, "widget");
6297
+ const viewport = {
6298
+ screenX: Number(window.screenX),
6299
+ screenY: Number(window.screenY),
6300
+ innerWidth: Number(window.innerWidth),
6301
+ innerHeight: Number(window.innerHeight),
6302
+ outerWidth: Number(window.outerWidth),
6303
+ outerHeight: Number(window.outerHeight),
6304
+ devicePixelRatio: Number(window.devicePixelRatio || 1)
6305
+ };
6306
+ const horizontal = Math.max(0, viewport.outerWidth - viewport.innerWidth);
6307
+ const vertical = Math.max(0, viewport.outerHeight - viewport.innerHeight);
6308
+ const chromeLeft = Math.round(horizontal / 2);
6309
+ const chromeTop = Math.max(0, vertical - horizontal);
6310
+ const resolvedClickPoint = clickPoint;
6311
+ const screenPoint = resolvedClickPoint === null ? null : {
6312
+ x: Math.round(viewport.screenX + chromeLeft + resolvedClickPoint.x),
6313
+ y: Math.round(viewport.screenY + chromeTop + resolvedClickPoint.y)
6314
+ };
6315
+ return {
6316
+ title,
6317
+ url,
6318
+ selectorHits,
6319
+ deniedHits,
6320
+ textHits,
6321
+ originResponsePending,
6322
+ turnstilePresent,
6323
+ clickPoint: resolvedClickPoint,
6324
+ clickTargetKind,
6325
+ clickSource,
6326
+ screenPoint,
6327
+ viewport
6328
+ };
6329
+ }
6055
6330
  //#endregion
6056
6331
  //#region src/background/content-handler.ts
6057
6332
  var EXPECTED_INJECTION_PATTERNS = [
@@ -6106,7 +6381,7 @@ var ContentHandler = class {
6106
6381
  expression: "document.visibilityState",
6107
6382
  returnByValue: true
6108
6383
  });
6109
- if (visibility?.value === "hidden") throw structuredOperationError$1("HIDDEN_TAB_SCREENSHOT", "screenshot 需要 tab 可见,当前 tab 处于 hidden 状态", "Extension 截图依赖可见 renderer,请显式使用 manage(action=\"activatePage\") 或 manage(action=\"focusWindow\"),也可在 CDP/headless 测试浏览器中截图", {
6384
+ if (visibility?.value === "hidden") throw structuredOperationError$1("HIDDEN_TAB_SCREENSHOT", "screenshot 需要 tab 可见,当前 tab 处于 hidden 状态", "Extension 截图依赖可见 renderer,请用 manage 的 activatePage 或 focusWindow 动作,也可在 CDP/headless 测试浏览器中截图", {
6110
6385
  tabId,
6111
6386
  visibilityState: visibility.value
6112
6387
  });
@@ -6233,6 +6508,58 @@ var ContentHandler = class {
6233
6508
  const tabId = await this.getManagedScriptableTabId(p.tabId, context, "evaluate");
6234
6509
  return this.injectScript(tabId, p.frameId, executeCode, [p.code]);
6235
6510
  }
6511
+ async getViewportMetrics(params, context) {
6512
+ const p = ViewportMetricsSchema.parse(params);
6513
+ const tabId = await this.getManagedScriptableTabId(p.tabId, context, "viewport_metrics");
6514
+ const results = await chrome.scripting.executeScript({
6515
+ target: {
6516
+ tabId,
6517
+ frameIds: [p.frameId ?? 0]
6518
+ },
6519
+ world: "ISOLATED",
6520
+ func: () => ({
6521
+ screenX: Number(window.screenX),
6522
+ screenY: Number(window.screenY),
6523
+ innerWidth: Number(window.innerWidth),
6524
+ innerHeight: Number(window.innerHeight),
6525
+ outerWidth: Number(window.outerWidth),
6526
+ outerHeight: Number(window.outerHeight),
6527
+ devicePixelRatio: Number(window.devicePixelRatio || 1)
6528
+ })
6529
+ });
6530
+ const injectionError = results[0]?.error;
6531
+ if (injectionError) throw wrapInjectionError(injectionError.message || String(injectionError));
6532
+ const metrics = results[0]?.result;
6533
+ if (!metrics) throw new Error("viewport_metrics 未返回视口");
6534
+ return metrics;
6535
+ }
6536
+ async inspectChallenge(params, context) {
6537
+ const p = ChallengeInspectSchema.parse(params);
6538
+ const tabId = await this.getManagedScriptableTabId(p.tabId, context, "challenge_inspect");
6539
+ const results = await chrome.scripting.executeScript({
6540
+ target: {
6541
+ tabId,
6542
+ frameIds: [p.frameId ?? 0]
6543
+ },
6544
+ world: "ISOLATED",
6545
+ func: inspectChallengePage,
6546
+ args: [{
6547
+ challengeSelectors: p.challengeSelectors,
6548
+ deniedSelectors: p.deniedSelectors,
6549
+ widgetSelectors: p.widgetSelectors,
6550
+ verifyButtonSelectors: p.verifyButtonSelectors,
6551
+ frameSelectors: p.frameSelectors,
6552
+ titleNeedles: p.titleNeedles,
6553
+ textMarkers: p.textMarkers,
6554
+ originResponsePendingTextMarkers: p.originResponsePendingTextMarkers
6555
+ }]
6556
+ });
6557
+ const injectionError = results[0]?.error;
6558
+ if (injectionError) throw wrapInjectionError(injectionError.message || String(injectionError));
6559
+ const snapshot = results[0]?.result;
6560
+ if (!snapshot) throw new Error("challenge_inspect 未返回页面状态");
6561
+ return snapshot;
6562
+ }
6236
6563
  async find(params, context) {
6237
6564
  const p = FindSchema.parse(params) ?? {};
6238
6565
  const tabId = await this.getManagedTabId(p.tabId, context, "find");
@@ -6409,7 +6736,7 @@ var CookieHandler = class {
6409
6736
  }
6410
6737
  async cookiesClear(params) {
6411
6738
  const p = CookiesClearSchema.parse(params) ?? {};
6412
- if (!p.url && !p.domain && !p.name) throw new ExpectedOperationError("cookies action=clear 必须带 name/domain/url 至少一个过滤参数(项目规范)");
6739
+ if (!p.url && !p.domain) throw new ExpectedOperationError("cookies action=clear 必须带 url 或 domain 过滤参数,name 只能在该范围内进一步过滤(避免跨站误删同名 cookie)");
6413
6740
  const filter = {};
6414
6741
  if (p.url) filter.url = p.url;
6415
6742
  if (p.domain) filter.domain = p.domain;
@@ -6510,53 +6837,28 @@ var FrameResolver = class {
6510
6837
  async resolveFrame(params, context) {
6511
6838
  const p = ResolveFrameSchema.parse(params);
6512
6839
  const tabId = await this.getManagedScriptableTabId(p.tabId, context, "resolve_frame");
6513
- const allFrames = await chrome.webNavigation.getAllFrames({ tabId });
6514
- if (!allFrames) throw new Error("Failed to get frames");
6515
- const allChildFrames = allFrames.filter((f) => f.frameId !== 0);
6516
- if (allChildFrames.length === 0) throw new Error("No iframes found in page");
6517
- const directChildFrames = allFrames.filter((f) => f.parentFrameId === 0 && f.frameId !== 0);
6518
- const info = (await chrome.scripting.executeScript({
6519
- target: {
6840
+ const snapshot = await getDomFrameSnapshot(tabId, 0, p.frame);
6841
+ if (snapshot.selectionStatus !== "found" || snapshot.selectedIndex === null) {
6842
+ const desc = typeof p.frame === "number" ? `index ${p.frame}` : `selector "${p.frame}"`;
6843
+ const detail = snapshot.selectionError ? `: ${snapshot.selectionError}` : "";
6844
+ throw new ExpectedOperationError(`iframe not found: ${desc} (${snapshot.selectionStatus})${detail}`);
6845
+ }
6846
+ const selected = snapshot.frames.find((frame) => frame.index === snapshot.selectedIndex);
6847
+ if (!selected || selected.frameId === null) throw new ExpectedOperationError(JSON.stringify({ error: {
6848
+ code: "FRAME_IDENTITY_UNAVAILABLE",
6849
+ message: "Cannot map the selected DOM iframe to one Chrome frameId",
6850
+ suggestion: "请等待 iframe 完成加载后重试;工具不会按 webNavigation 列表顺序选择其他 frame",
6851
+ context: {
6520
6852
  tabId,
6521
- frameIds: [0]
6522
- },
6523
- world: "MAIN",
6524
- func: (frame) => {
6525
- const iframes = Array.from(document.querySelectorAll("iframe, frame"));
6526
- let target;
6527
- let index = -1;
6528
- if (typeof frame === "number") {
6529
- if (frame < 0 || frame >= iframes.length) return null;
6530
- target = iframes[frame];
6531
- index = frame;
6532
- } else {
6533
- target = document.querySelector(frame);
6534
- if (target) index = iframes.indexOf(target);
6535
- }
6536
- if (!target) return null;
6537
- let absoluteSrc = target.src || "";
6538
- if (absoluteSrc && !absoluteSrc.startsWith("http") && !absoluteSrc.startsWith("about:")) try {
6539
- absoluteSrc = new URL(absoluteSrc, location.href).href;
6540
- } catch {}
6541
- return {
6542
- src: absoluteSrc,
6543
- index
6544
- };
6545
- },
6546
- args: [p.frame]
6547
- }))[0]?.result;
6548
- if (!info) throw new ExpectedOperationError(`iframe not found: ${typeof p.frame === "number" ? `index ${p.frame}` : `selector "${p.frame}"`}`);
6549
- let matchedFrameId;
6550
- if (info.src) {
6551
- const urlMatches = allChildFrames.filter((f) => f.url === info.src);
6552
- if (urlMatches.length === 1) matchedFrameId = urlMatches[0].frameId;
6553
- }
6554
- if (matchedFrameId === void 0 && info.index >= 0 && info.index < directChildFrames.length) matchedFrameId = directChildFrames[info.index].frameId;
6555
- if (matchedFrameId === void 0) throw new Error(`Cannot resolve iframe to frameId. src: "${info.src}", directChildren: ${directChildFrames.length}, allFrames: ${allChildFrames.length}`);
6556
- const offset = await getFrameOffset(tabId, matchedFrameId);
6853
+ selection: p.frame,
6854
+ domIndex: snapshot.selectedIndex,
6855
+ candidateFrameIds: selected?.candidateFrameIds ?? [],
6856
+ domFrameCount: snapshot.frames.length
6857
+ }
6858
+ } }));
6557
6859
  return {
6558
- frameId: matchedFrameId,
6559
- offset
6860
+ frameId: selected.frameId,
6861
+ offset: selected.contentOffset
6560
6862
  };
6561
6863
  }
6562
6864
  async getAllFrames(params, context) {
@@ -6564,80 +6866,20 @@ var FrameResolver = class {
6564
6866
  const tabId = await this.getManagedScriptableTabId(p.tabId, context, "get_all_frames");
6565
6867
  const frames = await chrome.webNavigation.getAllFrames({ tabId });
6566
6868
  if (!frames) throw new Error("Failed to get frames");
6567
- let mainFrameInfo = {
6568
- title: null,
6569
- rect: {
6570
- x: 0,
6571
- y: 0,
6572
- width: 0,
6573
- height: 0
6574
- }
6575
- };
6576
- let domFrames = [];
6577
- try {
6578
- const pageFrames = (await chrome.scripting.executeScript({
6579
- target: {
6580
- tabId,
6581
- frameIds: [0]
6582
- },
6583
- world: "MAIN",
6584
- func: () => ({
6585
- main: {
6586
- title: document.title || null,
6587
- rect: {
6588
- x: 0,
6589
- y: 0,
6590
- width: window.innerWidth,
6591
- height: window.innerHeight
6592
- }
6593
- },
6594
- frames: Array.from(document.querySelectorAll("iframe, frame")).map((frame, index) => {
6595
- const el = frame;
6596
- const rect = el.getBoundingClientRect();
6597
- const selector = el.id ? `#${CSS.escape(el.id)}` : `${el.tagName.toLowerCase()}:nth-of-type(${index + 1})`;
6598
- return {
6599
- index,
6600
- url: el.src || "",
6601
- title: el.title || null,
6602
- name: el.name || null,
6603
- selector,
6604
- rect: {
6605
- x: rect.x,
6606
- y: rect.y,
6607
- width: rect.width,
6608
- height: rect.height
6609
- }
6610
- };
6611
- })
6612
- })
6613
- }))[0]?.result;
6614
- mainFrameInfo = pageFrames?.main ?? mainFrameInfo;
6615
- domFrames = pageFrames?.frames ?? [];
6616
- } catch {
6617
- domFrames = [];
6618
- }
6619
- const directChildFrames = frames.filter((frame) => frame.parentFrameId === 0 && frame.frameId !== 0);
6620
- const getDomFrame = (frame) => {
6621
- if (frame.parentFrameId !== 0) return;
6622
- const directIndex = directChildFrames.findIndex((candidate) => candidate.frameId === frame.frameId);
6623
- const byIndex = directIndex >= 0 ? domFrames[directIndex] : void 0;
6624
- if (byIndex) return byIndex;
6625
- const navigationMatches = directChildFrames.filter((candidate) => candidate.url === frame.url);
6626
- const domMatches = domFrames.filter((candidate) => candidate.url === frame.url);
6627
- return navigationMatches.length === 1 && domMatches.length === 1 ? domMatches[0] : void 0;
6628
- };
6869
+ const snapshot = await getDomFrameSnapshot(tabId, 0);
6870
+ const domFramesByFrameId = new Map(snapshot.frames.filter((frame) => frame.frameId !== null).map((frame) => [frame.frameId, frame]));
6629
6871
  return { frames: frames.map((frame, index) => {
6630
6872
  const isMainFrame = frame.frameId === 0;
6631
- const dom = isMainFrame ? void 0 : getDomFrame(frame);
6873
+ const dom = isMainFrame ? void 0 : domFramesByFrameId.get(frame.frameId);
6632
6874
  return {
6633
6875
  index,
6634
6876
  frameId: frame.frameId,
6635
6877
  parentFrameId: isMainFrame ? null : frame.parentFrameId,
6636
6878
  url: frame.url,
6637
- title: isMainFrame ? mainFrameInfo.title : dom?.title ?? null,
6879
+ title: isMainFrame ? snapshot.parent.title : dom?.title ?? null,
6638
6880
  name: isMainFrame ? null : dom?.name ?? null,
6639
6881
  selector: isMainFrame ? null : dom?.selector ?? null,
6640
- rect: isMainFrame ? mainFrameInfo.rect : dom?.rect ?? null
6882
+ rect: isMainFrame ? snapshot.parent.rect : dom?.rect ?? null
6641
6883
  };
6642
6884
  }) };
6643
6885
  }
@@ -6656,7 +6898,8 @@ var FrameResolver = class {
6656
6898
  const originalFrame = await this.getExtensionFrameIdentity(tabId, p.frameId);
6657
6899
  let retryAttempted = false;
6658
6900
  let retryReason;
6659
- for (let attempt = 0; attempt < 2; attempt++) {
6901
+ const maxAttempts = p.staleContextRetry === "readOnly" ? 2 : 1;
6902
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
6660
6903
  const remaining = p.timeout === void 0 ? void 0 : p.timeout - (Date.now() - startedAt);
6661
6904
  if (remaining !== void 0 && remaining <= 0) throw this.frameEvaluationError("FRAME_EVALUATION_TIMEOUT", "Frame evaluation timed out before resolution", {
6662
6905
  tabId,
@@ -6713,6 +6956,7 @@ var FrameResolver = class {
6713
6956
  ...await chrome.debugger.sendCommand({ tabId }, "Runtime.evaluate", evalParams),
6714
6957
  retryAttempted,
6715
6958
  retryReason,
6959
+ staleContextRetry: p.staleContextRetry,
6716
6960
  frameContext: {
6717
6961
  tabId,
6718
6962
  extensionFrameId: identity.frameId,
@@ -6736,6 +6980,14 @@ var FrameResolver = class {
6736
6980
  retryReason
6737
6981
  });
6738
6982
  if (!staleContext) throw error;
6983
+ if (p.staleContextRetry !== "readOnly") throw this.frameEvaluationError("FRAME_STALE_CONTEXT", "Execution context became stale; script was not replayed because staleContextRetry is never", {
6984
+ tabId,
6985
+ ...this.frameIdentitySummary(identity),
6986
+ cdpFrameId: resolved.cdpFrameId,
6987
+ executionContextId: targetCtx.id,
6988
+ retryAttempted: false,
6989
+ staleContextRetry: p.staleContextRetry
6990
+ });
6739
6991
  retryAttempted = true;
6740
6992
  retryReason = message.slice(0, 500);
6741
6993
  this.debuggerManager.invalidateExecutionContext(tabId, targetCtx.id);
@@ -7138,6 +7390,8 @@ var LogEventHandler = class {
7138
7390
  } catch (e) {
7139
7391
  console.warn("[logs] console fallback (executeScript) failed:", e);
7140
7392
  }
7393
+ this.logManager.setConsole(tabId, messages);
7394
+ messages = this.logManager.getConsole(tabId);
7141
7395
  if (p.level) {
7142
7396
  const target = p.level;
7143
7397
  messages = messages.filter((m) => m.level === target || target === "warning" && m.level === "warn" || target === "warn" && m.level === "warning");
@@ -7228,6 +7482,11 @@ var LogEventHandler = class {
7228
7482
  this.logManager.setNetwork(tabId, []);
7229
7483
  return { success: true };
7230
7484
  }
7485
+ async networkChallengeState(params, context) {
7486
+ const p = NetworkChallengeStateSchema.parse(params) ?? {};
7487
+ const tabId = await this.getManagedTabId(p.tabId, context, "network_challenge_state");
7488
+ return { challengeRequired: this.logManager.isChallengeRequired(tabId) };
7489
+ }
7231
7490
  async getManagedTabId(tabId, context, operation) {
7232
7491
  const resolvedTabId = await getTargetTabId(tabId);
7233
7492
  await assertManagedTab(resolvedTabId, context, operation);
@@ -7283,9 +7542,16 @@ var LogEventHandler = class {
7283
7542
  var PENDING_TTL_MS = 6e4;
7284
7543
  var PENDING_MAX_PER_TAB = 500;
7285
7544
  var PENDING_SWEEP_INTERVAL_MS = 3e4;
7545
+ function isCloudflareChallenge(headers) {
7546
+ if (!headers) return false;
7547
+ return Object.entries(headers).some(([name, value]) => name.toLowerCase() === "cf-mitigated" && String(value).toLowerCase() === "challenge");
7548
+ }
7286
7549
  var LogManager = class {
7287
7550
  consoleMessages = /* @__PURE__ */ new Map();
7288
7551
  networkRequests = /* @__PURE__ */ new Map();
7552
+ consoleSequences = /* @__PURE__ */ new Map();
7553
+ networkSequences = /* @__PURE__ */ new Map();
7554
+ challengeRequired = /* @__PURE__ */ new Map();
7289
7555
  pendingRequests = /* @__PURE__ */ new Map();
7290
7556
  sweepTimer = null;
7291
7557
  constructor() {
@@ -7301,6 +7567,7 @@ var LogManager = class {
7301
7567
  }
7302
7568
  /** 替换 console 消息列表(清理或覆盖场景) */
7303
7569
  setConsole(tabId, messages) {
7570
+ this.assignConsoleSequences(tabId, messages);
7304
7571
  this.consoleMessages.set(tabId, messages);
7305
7572
  }
7306
7573
  /** 是否已为 tab 初始化 network 缓冲 */
@@ -7311,8 +7578,12 @@ var LogManager = class {
7311
7578
  getNetwork(tabId) {
7312
7579
  return this.networkRequests.get(tabId) ?? [];
7313
7580
  }
7581
+ isChallengeRequired(tabId) {
7582
+ return this.challengeRequired.get(tabId) === true;
7583
+ }
7314
7584
  /** 替换 network 请求列表 */
7315
7585
  setNetwork(tabId, requests) {
7586
+ this.assignNetworkSequences(tabId, requests);
7316
7587
  this.networkRequests.set(tabId, requests);
7317
7588
  }
7318
7589
  /** 取 pending 请求 Map(navigation-handler 用于过滤进行中的请求) */
@@ -7348,6 +7619,7 @@ var LogManager = class {
7348
7619
  lineNumber: p.exceptionDetails.lineNumber
7349
7620
  };
7350
7621
  const messages = this.consoleMessages.get(tabId) || [];
7622
+ this.assignConsoleSequences(tabId, [message]);
7351
7623
  messages.push(message);
7352
7624
  if (messages.length > 1100) messages.splice(0, messages.length - 1e3);
7353
7625
  this.consoleMessages.set(tabId, messages);
@@ -7383,12 +7655,16 @@ var LogManager = class {
7383
7655
  const pending = tabPending?.get(p.requestId);
7384
7656
  if (pending) {
7385
7657
  const { _monotonic, _addedAt: _, ...requestData } = pending;
7658
+ const challenge = isCloudflareChallenge(p.response.headers);
7659
+ if (requestData.type.toLowerCase() === "document") this.challengeRequired.set(tabId, challenge);
7386
7660
  const requests = this.networkRequests.get(tabId) || [];
7387
7661
  requests.push({
7388
7662
  ...requestData,
7389
7663
  status: p.response.status,
7664
+ challenge,
7390
7665
  duration: Math.round((p.timestamp - _monotonic) * 1e3)
7391
7666
  });
7667
+ this.assignNetworkSequences(tabId, requests.slice(-1));
7392
7668
  if (requests.length > 1100) requests.splice(0, requests.length - 1e3);
7393
7669
  this.networkRequests.set(tabId, requests);
7394
7670
  tabPending.delete(p.requestId);
@@ -7406,6 +7682,7 @@ var LogManager = class {
7406
7682
  errorText: p.errorText,
7407
7683
  duration: Math.round((p.timestamp - _monotonic) * 1e3)
7408
7684
  });
7685
+ this.assignNetworkSequences(tabId, requests.slice(-1));
7409
7686
  if (requests.length > 1100) requests.splice(0, requests.length - 1e3);
7410
7687
  this.networkRequests.set(tabId, requests);
7411
7688
  }
@@ -7415,8 +7692,23 @@ var LogManager = class {
7415
7692
  cleanupTab(tabId) {
7416
7693
  this.consoleMessages.delete(tabId);
7417
7694
  this.networkRequests.delete(tabId);
7695
+ this.consoleSequences.delete(tabId);
7696
+ this.networkSequences.delete(tabId);
7697
+ this.challengeRequired.delete(tabId);
7418
7698
  this.pendingRequests.delete(tabId);
7419
7699
  }
7700
+ assignConsoleSequences(tabId, messages) {
7701
+ let sequence = this.consoleSequences.get(tabId) ?? 0;
7702
+ for (const message of messages) if (message.sequence === void 0) message.sequence = ++sequence;
7703
+ else sequence = Math.max(sequence, message.sequence);
7704
+ this.consoleSequences.set(tabId, sequence);
7705
+ }
7706
+ assignNetworkSequences(tabId, requests) {
7707
+ let sequence = this.networkSequences.get(tabId) ?? 0;
7708
+ for (const request of requests) if (request.sequence === void 0) request.sequence = ++sequence;
7709
+ else sequence = Math.max(sequence, request.sequence);
7710
+ this.networkSequences.set(tabId, sequence);
7711
+ }
7420
7712
  startSweep() {
7421
7713
  if (this.sweepTimer) return;
7422
7714
  this.sweepTimer = setInterval(() => this.sweepPending(), PENDING_SWEEP_INTERVAL_MS);
@@ -8029,7 +8321,7 @@ var TabHandler = class {
8029
8321
  const before = await assertManagedWindow(p.windowId, context, "window_focus");
8030
8322
  await chrome.windows.update(p.windowId, { focused: true });
8031
8323
  const after = await waitForWindowFocus(p.windowId, context);
8032
- if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请确认目标窗口属于 managed 测试窗口,并检查当前桌面环境是否允许浏览器扩展主动聚焦窗口;需要可见 tab 时可改用 manage(action=\"activatePage\") 激活目标测试 tab", {
8324
+ if (!after.focused) throw structuredOperationError("WINDOW_FOCUS_NOT_OBSERVED", "focusWindow 已请求聚焦窗口,但 Chrome 未观测到目标窗口获得焦点", "请确认目标是 managed 测试窗口,并检查桌面环境是否允许扩展聚焦窗口;需要可见 tab 时可用 manage(action=\"activatePage\") 激活目标测试 tab", {
8033
8325
  windowId: p.windowId,
8034
8326
  beforeFocused: before.focused,
8035
8327
  afterFocused: after.focused,
@@ -8077,7 +8369,7 @@ var TabHandler = class {
8077
8369
  setMcpWindowId(window.id);
8078
8370
  const tabId = window.tabs?.[0]?.id;
8079
8371
  if (tabId !== void 0) await markManagedTab(tabId);
8080
- const after = await getWindowInfo(window.id, context);
8372
+ const after = p.focused ? await waitForWindowFocus(window.id, context) : await getWindowInfo(window.id, context);
8081
8373
  return {
8082
8374
  success: true,
8083
8375
  windowId: window.id,
@@ -8137,6 +8429,11 @@ var TabHandler = class {
8137
8429
  };
8138
8430
  //#endregion
8139
8431
  //#region src/background/actions.ts
8432
+ /**
8433
+ * Action 处理器
8434
+ *
8435
+ * 处理来自 MCP Server 的所有操作请求
8436
+ */
8140
8437
  var ActionHandler = class {
8141
8438
  actions = /* @__PURE__ */ new Map();
8142
8439
  logManager = new LogManager();
@@ -8156,7 +8453,10 @@ var ActionHandler = class {
8156
8453
  }
8157
8454
  async execute(action, params, context) {
8158
8455
  const handler = this.actions.get(action);
8159
- if (!handler) throw new Error(`Unknown action: ${action}`);
8456
+ if (!handler) throw new ExpectedOperationError(JSON.stringify({ error: {
8457
+ code: "UNKNOWN_ACTION",
8458
+ message: `Unknown action: ${action}`
8459
+ } }));
8160
8460
  return handler(params, context);
8161
8461
  }
8162
8462
  /**
@@ -8198,6 +8498,8 @@ var ActionHandler = class {
8198
8498
  this.actions.set("type", this.contentHandler.type.bind(this.contentHandler));
8199
8499
  this.actions.set("scroll", this.contentHandler.scroll.bind(this.contentHandler));
8200
8500
  this.actions.set("evaluate", this.contentHandler.evaluate.bind(this.contentHandler));
8501
+ this.actions.set("viewport_metrics", this.contentHandler.getViewportMetrics.bind(this.contentHandler));
8502
+ this.actions.set("challenge_inspect", this.contentHandler.inspectChallenge.bind(this.contentHandler));
8201
8503
  this.actions.set("find", this.contentHandler.find.bind(this.contentHandler));
8202
8504
  this.actions.set("get_text", this.contentHandler.getText.bind(this.contentHandler));
8203
8505
  this.actions.set("get_html", this.contentHandler.getHtml.bind(this.contentHandler));
@@ -8223,6 +8525,7 @@ var ActionHandler = class {
8223
8525
  this.actions.set("network_enable", this.logEventHandler.networkEnable.bind(this.logEventHandler));
8224
8526
  this.actions.set("network_get", this.logEventHandler.networkGet.bind(this.logEventHandler));
8225
8527
  this.actions.set("network_clear", this.logEventHandler.networkClear.bind(this.logEventHandler));
8528
+ this.actions.set("network_challenge_state", this.logEventHandler.networkChallengeState.bind(this.logEventHandler));
8226
8529
  this.actions.set("stealth_click", this.stealthHandler.stealthClick.bind(this.stealthHandler));
8227
8530
  this.actions.set("stealth_type", this.stealthHandler.stealthType.bind(this.stealthHandler));
8228
8531
  this.actions.set("stealth_key", this.stealthHandler.stealthKey.bind(this.stealthHandler));
@@ -8260,6 +8563,25 @@ function randomHex(bytes = 16) {
8260
8563
  crypto.getRandomValues(data);
8261
8564
  return bytesToHex(data);
8262
8565
  }
8566
+ var backgroundBundleHashPromise;
8567
+ async function loadBackgroundBundleHash() {
8568
+ try {
8569
+ const response = await fetch(chrome.runtime.getURL("service-worker-loader.js"), { cache: "no-store" });
8570
+ if (!response.ok) {
8571
+ console.warn(`[HTTP] Cannot read Extension service worker loader: HTTP ${response.status}`);
8572
+ return;
8573
+ }
8574
+ const digest = await crypto.subtle.digest("SHA-256", await response.arrayBuffer());
8575
+ return `sha256:${bytesToHex(new Uint8Array(digest))}`;
8576
+ } catch (error) {
8577
+ console.warn("[HTTP] Cannot compute Extension background bundle hash:", error instanceof Error ? error.message : String(error));
8578
+ return;
8579
+ }
8580
+ }
8581
+ function getBackgroundBundleHash() {
8582
+ backgroundBundleHashPromise ??= loadBackgroundBundleHash();
8583
+ return backgroundBundleHashPromise;
8584
+ }
8263
8585
  async function hmacHex(token, payload) {
8264
8586
  const encoder = new TextEncoder();
8265
8587
  const key = await crypto.subtle.importKey("raw", encoder.encode(token), {
@@ -8427,10 +8749,14 @@ var HttpClient = class {
8427
8749
  };
8428
8750
  this.connections.set(port, conn);
8429
8751
  this.resetHeartbeat(port);
8430
- ws.send(JSON.stringify({
8431
- type: "hello",
8432
- version: chrome.runtime.getManifest().version
8433
- }));
8752
+ getBackgroundBundleHash().then((backgroundBundleHash) => {
8753
+ if (ws.readyState !== WebSocket.OPEN) return;
8754
+ ws.send(JSON.stringify({
8755
+ type: "hello",
8756
+ version: chrome.runtime.getManifest().version,
8757
+ ...backgroundBundleHash ? { backgroundBundleHash } : {}
8758
+ }));
8759
+ });
8434
8760
  console.log(`[HTTP] Connected to MCP Server at port ${port} (total: ${this.connections.size})`);
8435
8761
  this.statusHandler?.("connected", this.connections.size);
8436
8762
  resolve(true);
@@ -8490,7 +8816,10 @@ var HttpClient = class {
8490
8816
  const healthyPorts = results.filter(({ result }) => result.healthy).map(({ port }) => port);
8491
8817
  const selectedFailures = results.filter(({ result }) => result.failureKind);
8492
8818
  const failureSummary = selectedFailures.slice(0, 10).map(({ port, result }) => `${port} (${result.failureKind}: ${result.reason})`).join(", ");
8493
- if (failureSummary && failureSummary !== this.lastServerFailureSummary) console.warn(`[HTTP] ${selectedFailures.length} MCP Server candidate(s) rejected after health identification: ${failureSummary}${selectedFailures.length > 10 ? ", ..." : ""}`);
8819
+ if (failureSummary && failureSummary !== this.lastServerFailureSummary) {
8820
+ const omittedSuffix = selectedFailures.length > 10 ? ", ..." : "";
8821
+ console.warn(`[HTTP] ${selectedFailures.length} MCP Server candidate(s) rejected after health identification: ` + failureSummary + omittedSuffix);
8822
+ }
8494
8823
  this.lastServerFailureSummary = failureSummary;
8495
8824
  if (healthyPorts.length > 0) console.log(`[HTTP] Found ${healthyPorts.length} MCP Server(s) at ports: ${healthyPorts.sort((a, b) => a - b).join(", ")}`);
8496
8825
  else console.log("[HTTP] No MCP Server found in port range");
@@ -8635,11 +8964,11 @@ httpClient.onStatusChange((status, count) => {
8635
8964
  updateBadge(status, count);
8636
8965
  broadcastStatus(status, count);
8637
8966
  });
8638
- chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
8639
- handleInternalMessage(message).then(sendResponse);
8967
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
8968
+ handleInternalMessage(message, sender).then(sendResponse);
8640
8969
  return true;
8641
8970
  });
8642
- async function handleInternalMessage(message) {
8971
+ async function handleInternalMessage(message, sender) {
8643
8972
  switch (message.type) {
8644
8973
  case "CONNECT": return httpClient.connect();
8645
8974
  case "DISCONNECT":
@@ -8657,6 +8986,7 @@ async function handleInternalMessage(message) {
8657
8986
  pairingTokenConfigured: await httpClient.hasPairingToken(),
8658
8987
  allowInsecureNoToken: await httpClient.isAllowInsecureNoToken()
8659
8988
  };
8989
+ case "MCP_FRAME_PROBE": return recordDomFrameProbe(message, sender);
8660
8990
  default: return { error: "Unknown message type" };
8661
8991
  }
8662
8992
  }