dsh-chrome-bridge 1.19.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +37 -16
  14. package/download.js +895 -69
  15. package/drag.js +68 -30
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +312 -16
  22. package/i18n/index.js +17 -0
  23. package/i18n/ru.js +312 -16
  24. package/i18n/zh.js +310 -14
  25. package/image-guard.js +13 -6
  26. package/index.js +21 -1073
  27. package/locale/ru.json +7 -0
  28. package/nav.js +56 -10
  29. package/package.json +8 -1
  30. package/panel.js +14 -4
  31. package/refs.js +293 -240
  32. package/setup.js +248 -74
  33. package/tools/click.js +58 -0
  34. package/tools/devtools.js +61 -0
  35. package/tools/dialog.js +22 -0
  36. package/tools/download.js +50 -0
  37. package/tools/drag.js +61 -0
  38. package/tools/eval.js +22 -0
  39. package/tools/fill.js +77 -0
  40. package/tools/handoff.js +40 -0
  41. package/tools/index.js +38 -0
  42. package/tools/input.js +147 -0
  43. package/tools/nav.js +57 -0
  44. package/tools/read.js +87 -0
  45. package/tools/record.js +120 -0
  46. package/tools/screenshot.js +223 -0
  47. package/tools/tabs.js +131 -0
  48. package/tools/wait.js +56 -0
  49. package/vendor/cb +616 -35
  50. package/vendor/extension/_locales/en/messages.json +3 -0
  51. package/vendor/extension/_locales/ru/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  53. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  54. package/vendor/extension/background.js +2 -1969
  55. package/vendor/extension/confirm.css +148 -0
  56. package/vendor/extension/confirm.html +49 -0
  57. package/vendor/extension/confirm.js +188 -0
  58. package/vendor/extension/in-page-cursor.js +599 -0
  59. package/vendor/extension/manifest.json +11 -2
  60. package/vendor/extension/popup.css +99 -5
  61. package/vendor/extension/popup.html +28 -2
  62. package/vendor/extension/popup.js +430 -45
  63. package/vendor/extension/sw/boot.js +111 -0
  64. package/vendor/extension/sw/cdp.js +411 -0
  65. package/vendor/extension/sw/chooser.js +192 -0
  66. package/vendor/extension/sw/confirm.js +608 -0
  67. package/vendor/extension/sw/cursor.js +241 -0
  68. package/vendor/extension/sw/dispatch.js +129 -0
  69. package/vendor/extension/sw/download.js +279 -0
  70. package/vendor/extension/sw/fetch-hub.js +224 -0
  71. package/vendor/extension/sw/frames.js +651 -0
  72. package/vendor/extension/sw/imaging.js +361 -0
  73. package/vendor/extension/sw/native.js +111 -0
  74. package/vendor/extension/sw/net-tools.js +525 -0
  75. package/vendor/extension/sw/ops.js +829 -0
  76. package/vendor/extension/sw/popup-api.js +303 -0
  77. package/vendor/extension/sw/profile.js +166 -0
  78. package/vendor/extension/sw/record.js +494 -0
  79. package/vendor/extension/sw/state.js +161 -0
  80. package/vendor/extension/sw/tabui.js +219 -0
  81. package/vendor/extension/sw/util.js +166 -0
  82. package/vendor/extension/sw/welcome.js +26 -0
  83. package/vendor/extension/sw/windows.js +94 -0
  84. package/vendor/extension/welcome.css +189 -0
  85. package/vendor/extension/welcome.html +70 -0
  86. package/vendor/extension/welcome.js +157 -0
  87. package/vendor/host/host.js +476 -71
  88. package/vendor/in-page-cursor.js +309 -37
  89. package/vendor/skill/SKILL.md +34 -16
@@ -0,0 +1,829 @@
1
+ import {
2
+ checkCdp, clearPending, ensure, evaluate, failLoadWaiter, forgetAttached, onCdpEvent, pointOf,
3
+ send, sendNoReply,
4
+ } from './cdp.js'
5
+ import {
6
+ attrValue, docOf, dropChooser, fileAccess, fileAccessError, hasAttr, inputState, isFolderNode,
7
+ withChooser,
8
+ } from './chooser.js'
9
+ import {
10
+ agentInput, clickPoint, cursorDo, cursorFx, cursorMove, markCursor, mountHandoff, pressKey,
11
+ settle, unmountHandoff,
12
+ } from './cursor.js'
13
+ import { areAllFramesAllowed, ensureUrlAllowed, hasProtectedSites, isUrlAllowed, loadProtectedSites } from './confirm.js'
14
+ import { clickAndDownload } from './download.js'
15
+ import { buildState, diagnostics, releaseAllTabs, setOwnWindow, setPaused, setShowCursor } from './popup-api.js'
16
+ import { CHOOSER_TTL_MS, PAUSED_MSG, S } from './state.js'
17
+ import { labels, unmarkTab } from './tabui.js'
18
+ import { checkPath, isExtUrl, sleep, timeLeft, updateBadge, within } from './util.js'
19
+ import { agentWindowIds, openInAgentWindow } from './windows.js'
20
+
21
+ /**
22
+ * console / network / networkIdle 的受保护网站过滤:
23
+ * 核对每条记录自身的 URL(含重定向链)、事件发生时的页面来源 pageUrl、脚本来源 where,
24
+ * 不给 tabId 时同时核对所属标签页当前网址;清单空着回 null(零开销)。
25
+ */
26
+ function itemAllowed(x) {
27
+ const id = x.tabId
28
+ const candidates = []
29
+ if (typeof x.url === 'string' && x.url) candidates.push(x.url)
30
+ if (Array.isArray(x.urls)) for (const u of x.urls) if (typeof u === 'string' && u) candidates.push(u)
31
+ if (typeof x.pageUrl === 'string' && x.pageUrl) candidates.push(x.pageUrl)
32
+ if (typeof x.where === 'string' && /^https?:|^wss?:/i.test(x.where)) candidates.push(x.where)
33
+ return candidates.every((u) => isUrlAllowed(id, u))
34
+ }
35
+
36
+ async function protectedFilter(items, checkCurrentTab = true) {
37
+ if (!hasProtectedSites()) return null
38
+ await loadProtectedSites()
39
+ if (!hasProtectedSites()) return null
40
+ if (!checkCurrentTab) return itemAllowed
41
+ const tabOk = new Map()
42
+ for (const id of new Set(items.map((x) => x.tabId))) {
43
+ let ok = false
44
+ try {
45
+ const t = await chrome.tabs.get(Number(id))
46
+ ok = [t.url, t.pendingUrl].every((u) => !u || isUrlAllowed(id, u))
47
+ } catch {}
48
+ tabOk.set(id, ok)
49
+ }
50
+ return (x) => tabOk.get(x.tabId) === true && itemAllowed(x)
51
+ }
52
+
53
+ const OPS = {
54
+ async diagnostics() {
55
+ const state = await buildState()
56
+ const { version, connected, paused, pauseReason, disconnectReason, attachedCount, showCursor, ownWindow, sessions } = state
57
+ return { text: await diagnostics(state), id: chrome.runtime.id, version, connected, paused, pauseReason,
58
+ disconnectReason, attachedCount, showCursor, ownWindow, sessions, recentErrors: S.ACTIVITY.filter(a => !a.ok).slice(-10), logs: S.LOG.slice(-30) }
59
+ },
60
+
61
+ async waitNewTab({ openerTabId, urlFilter, since, timeoutMs = 15000 }) {
62
+ const at = Date.now()
63
+ const after = since ?? at - 15000
64
+ let finish
65
+ const result = new Promise(resolve => { finish = resolve })
66
+ const matches = t => t && t.at >= after && t.url && (!urlFilter || t.url.includes(urlFilter)) &&
67
+ (openerTabId == null || t.openerTabId === Number(openerTabId))
68
+ const candidates = new Map()
69
+ const inspect = t => {
70
+ if (matches(t)) finish({ tabId: t.id, title: t.title, url: t.url, waitedMs: Date.now() - at })
71
+ }
72
+ const created = t => {
73
+ if (openerTabId != null && t.openerTabId !== Number(openerTabId)) return
74
+ candidates.set(t.id, t.openerTabId)
75
+ inspect(S.recentTabs.get(t.id))
76
+ }
77
+ const updated = (id, changes, tab) => {
78
+ if (candidates.has(id)) inspect({ ...tab, openerTabId: candidates.get(id), url: tab.pendingUrl || tab.url, at: Date.now() })
79
+ else inspect(S.recentTabs.get(id))
80
+ }
81
+ S.tabCreated.add(created)
82
+ S.tabUpdated.add(updated)
83
+ try {
84
+ // Subscribe before the async liveness checks so a new tab cannot fall in the gap.
85
+ for (const t of [...S.recentTabs.values()].reverse()) {
86
+ if (t.at >= at - 30000 && matches(t))
87
+ chrome.tabs.get(t.id).then(() => inspect(S.recentTabs.get(t.id)), () => {})
88
+ }
89
+ return await within(result, timeoutMs, '等待新标签页超时')
90
+ } finally {
91
+ S.tabCreated.delete(created)
92
+ S.tabUpdated.delete(updated)
93
+ }
94
+ },
95
+
96
+ async networkIdle({ tabId, idleMs = 500, timeoutMs = 15000, urlFilter, since }) {
97
+ const at = Date.now()
98
+ const id = await within(ensure(tabId), timeoutMs, '等待网络超时')
99
+ while (Date.now() - at < timeoutMs) {
100
+ if (S.paused || !S.attached.has(id)) throw new Error('等待网络时浏览器控制中止')
101
+ const waitedMs = Date.now() - at
102
+ if (urlFilter) {
103
+ const hit = S.NET.find(r => r.tabId === id && r.at >= (since ?? at - 30000) && r.url.includes(urlFilter) && (!hasProtectedSites() || itemAllowed(r)))
104
+ if (hit) return { matched: true, url: hit.url, status: hit.status, method: hit.method, waitedMs }
105
+ } else {
106
+ const busy = [...S.netPending.values()].some(r => r.tabId === id && r.type !== 'WebSocket' && r.type !== 'EventSource')
107
+ if (!busy && Date.now() - Math.max(at, S.netChanged.get(id) || 0) >= idleMs) return { idle: true, waitedMs }
108
+ }
109
+ await sleep(Math.min(100, timeoutMs - waitedMs))
110
+ }
111
+ throw new Error('等待网络超时')
112
+ },
113
+
114
+ async handoff({ tabId, reason = '', timeoutMs = 300000, focus = true }) {
115
+ const at = Date.now()
116
+ while (S.activeHandoff) {
117
+ const old = S.activeHandoff
118
+ old.resolve({ done: false, aborted: true })
119
+ await old.cleaned
120
+ }
121
+ if (S.paused) throw new Error(PAUSED_MSG)
122
+ const id = crypto.randomUUID()
123
+ tabId = Number(tabId)
124
+ let resolve, cleanup, timer, settled = false
125
+ const result = new Promise(r => {
126
+ resolve = value => {
127
+ if (settled) return false
128
+ settled = true
129
+ r(value)
130
+ return true
131
+ }
132
+ })
133
+ const cleaned = new Promise(r => { cleanup = r })
134
+ S.activeHandoff = { id, tabId, at, reason, resolve, cleaned, get settled() { return settled } }
135
+ updateBadge()
136
+ timer = setTimeout(() => resolve({ done: false, timedOut: true }), Math.max(0, at + timeoutMs - Date.now()))
137
+ try {
138
+ if (focus !== false) await getOps().activate({ tabId })
139
+ if (!settled) await mountHandoff(S.activeHandoff)
140
+ const outcome = await result
141
+ const t = outcome.done && await chrome.tabs.get(tabId).catch(() => null)
142
+ return { ...outcome, waitedMs: Date.now() - at, ...(outcome.done && { title: t?.title || '', url: t?.url || '' }) }
143
+ } catch (e) {
144
+ if (!settled) throw e
145
+ return { ...(await result), waitedMs: Date.now() - at }
146
+ } finally {
147
+ settled = true
148
+ clearTimeout(timer)
149
+ S.userTakeover.delete(tabId)
150
+ await unmountHandoff(tabId, id)
151
+ S.activeHandoff = null
152
+ updateBadge()
153
+ cleanup()
154
+ }
155
+ },
156
+
157
+ clickAndDownload,
158
+
159
+ async ping() {
160
+ return { pong: true, at: Date.now(), attached: [...S.attached] }
161
+ },
162
+
163
+ async version() {
164
+ return { version: chrome.runtime.getManifest().version, id: chrome.runtime.id }
165
+ },
166
+
167
+ /**
168
+ * DSH 插件设置页用:读状态、暂停、开关光标、全部松手。
169
+ * 只开放「更安全」的方向:这条通道 DSH 里的模型也摸得到(cb / socket),
170
+ * 所以「恢复控制」不给 —— 那一下只能用户在 Chrome 的扩展面板里点。
171
+ */
172
+ async panel({ action = 'state', on } = {}) {
173
+ if (action === 'pause') {
174
+ if (!on) throw new Error('恢复控制只能在 Chrome 工具栏的 DSH Bridge 面板里打开')
175
+ await setPaused(true, 'panel')
176
+ } else if (action === 'cursor') {
177
+ await setShowCursor(!!on, 'DSH 设置页')
178
+ } else if (action === 'window') {
179
+ await setOwnWindow(!!on, 'DSH 设置页')
180
+ } else if (action === 'releaseAll') {
181
+ await releaseAllTabs()
182
+ } else if (action !== 'state') {
183
+ throw new Error(`panel 不认识的 action: ${action}`)
184
+ }
185
+ const st = await buildState()
186
+ return {
187
+ version: st.version, id: chrome.runtime.id, paused: st.paused, showCursor: st.showCursor,
188
+ ownWindow: st.ownWindow, attachedCount: st.attachedCount, pauseReason: st.pauseReason, handoff: st.handoff,
189
+ protectedCount: Array.isArray(st.protectedSites) ? st.protectedSites.length : 0,
190
+ sessions: st.sessions.filter((x) => x.tabs.some((t) => t.attached)).length,
191
+ tabs: [...st.sessions.flatMap((x) => x.tabs), ...st.orphans]
192
+ .filter((t) => t.attached).slice(0, 8).map((t) => ({ title: t.title, url: t.url })),
193
+ }
194
+ },
195
+
196
+ /** 改完扩展代码:拷文件 → cb reload,不用去 chrome://extensions 点刷新 */
197
+ async reload() {
198
+ setTimeout(() => chrome.runtime.reload(), 250)
199
+ return { reloading: true }
200
+ },
201
+
202
+ async logs({ limit = 60 } = {}) {
203
+ return { lines: S.LOG.slice(-limit) }
204
+ },
205
+
206
+ async console({ limit = 40, tabId, clear = false } = {}) {
207
+ // 清单非空时,按每条记录发生时的来源过滤(不给 tabId 时一并核对标签页当前网址),防止切回普通页后偷看或误清受保护页旧日志
208
+ const visible = await protectedFilter(S.CONSOLE, tabId == null)
209
+ if (clear) {
210
+ for (let i = S.CONSOLE.length - 1; i >= 0; i--) {
211
+ const c = S.CONSOLE[i]
212
+ const matchTab = tabId == null || c.tabId === Number(tabId)
213
+ if (matchTab && (!visible || visible(c))) S.CONSOLE.splice(i, 1)
214
+ }
215
+ return { cleared: true }
216
+ }
217
+ let items = tabId != null ? S.CONSOLE.filter(c => c.tabId === Number(tabId)) : S.CONSOLE
218
+ if (visible) items = items.filter(visible)
219
+ return { items: items.slice(-limit) }
220
+ },
221
+
222
+ async tabs() {
223
+ const tabs = await chrome.tabs.query({})
224
+ // 窗口不止一个时每个窗口都有一个 active:focused 标出用户最后在用的那个窗口,agentWindow 标出 DSH 的干活窗口
225
+ let focusedWin = null
226
+ try { focusedWin = (await chrome.windows.getLastFocused()).id } catch {}
227
+ const agentWins = await agentWindowIds()
228
+ // 刚开、服务器还没回第一个字节的页 url 是空的,要去的地址在 pendingUrl:不算上的话,刚开的慢页列不出来,
229
+ // 不传 tab 接着操作它也会报「没指定标签页」
230
+ return tabs
231
+ .map(t => ({ t, url: t.url || t.pendingUrl || '' }))
232
+ .filter(({ t, url }) => url && !isExtUrl(url) && !isExtUrl(t.pendingUrl))
233
+ .map(({ t, url }) => ({
234
+ id: t.id, windowId: t.windowId, active: t.active, pinned: t.pinned,
235
+ focused: t.windowId === focusedWin, agentWindow: agentWins.has(t.windowId),
236
+ title: t.title, url, attached: S.attached.has(t.id),
237
+ // 这个标签页是不是被我们自动分进「🖱 DSH agent」组(面板和自检都用得上)
238
+ grouped: S.groupedTabs.has(t.id), groupId: t.groupId >= 0 ? t.groupId : null,
239
+ }))
240
+ },
241
+
242
+ async attach({ tabId }) {
243
+ await ensure(tabId)
244
+ return { tabId: Number(tabId), attached: true }
245
+ },
246
+
247
+ /** 第二个参数只给扩展内部用(dispatch 只传 args):空闲自动断开传 reason 'idle',受保护网站的放行就不跟着作废 */
248
+ async detach({ tabId }, { reason = 'detached' } = {}) {
249
+ if (S.activeDownload?.tabId === Number(tabId)) {
250
+ S.activeDownload.interrupt()
251
+ await S.activeDownload.cleaned
252
+ }
253
+ S.ensureInflight.delete(Number(tabId))
254
+ clearPending(Number(tabId))
255
+ S.dialogs.delete(Number(tabId))
256
+ failLoadWaiter(Number(tabId), '等页面加载时被松手了') // 自己 detach 不会触发 onDetach,这里补上
257
+ try { await chrome.debugger.detach({ tabId: Number(tabId) }) } catch {}
258
+ forgetAttached(Number(tabId), reason === 'idle' ? 'idle' : 'detached')
259
+ S.lastUsed.delete(Number(tabId))
260
+ await unmarkTab(tabId)
261
+ return { tabId: Number(tabId), attached: false }
262
+ },
263
+
264
+ async activate({ tabId }) {
265
+ const t = await chrome.tabs.get(Number(tabId))
266
+ await chrome.tabs.update(Number(tabId), { active: true })
267
+ await chrome.windows.update(t.windowId, { focused: true })
268
+ return { tabId: Number(tabId), windowId: t.windowId }
269
+ },
270
+
271
+ async open({ url, active = false }) {
272
+ // 相对地址会被 tabs.create 按扩展自己的地址补全(example.com → chrome-extension://…/example.com),只收完整网址
273
+ if (url) { try { new URL(url) } catch { throw new Error(`要给完整网址(带 https://):${url}`) } }
274
+ // 默认开进 DSH 自己的窗口(后台,不抢焦点);用户关了「单独窗口」就在当前窗口后台开页。
275
+ // 两种都不顶掉用户正在看的标签页。active=true(cb open --front)是有意要它跳到眼前,照旧开在当前窗口
276
+ if (S.ownWindow && !active) {
277
+ const t = await openInAgentWindow(url)
278
+ return { tabId: t.id, url: t.pendingUrl || t.url || url || '', window: 'agent' }
279
+ }
280
+ const t = await chrome.tabs.create({ url, active: !!active })
281
+ return { tabId: t.id, url: t.url }
282
+ },
283
+
284
+ async close({ tabId }) {
285
+ await chrome.tabs.remove(Number(tabId))
286
+ return { closed: Number(tabId) }
287
+ },
288
+
289
+ async eval({ tabId, expression, userGesture = false, timeoutMs }) {
290
+ return { value: await evaluate(tabId, expression, userGesture === true, timeoutMs) }
291
+ },
292
+
293
+ async cdp({ tabId, method, params, timeoutMs }) {
294
+ checkCdp(method, params)
295
+ if (method === 'Network.getCookies') {
296
+ const current = new URL((await chrome.tabs.get(Number(tabId))).url)
297
+ if (!['http:', 'https:'].includes(current.protocol) || params.urls.some(url => new URL(url).hostname !== current.hostname))
298
+ throw new Error('Network.getCookies urls 必须与当前页同主机')
299
+ }
300
+ if (method === 'Page.navigateToHistoryEntry') {
301
+ // 后退 / 前进到历史里的扩展页面也算「导航到扩展页面」
302
+ const h = await send(tabId, 'Page.getNavigationHistory', {}, timeoutMs)
303
+ const e = (h.entries || []).find((x) => x.id === (params || {}).entryId)
304
+ if (e && isExtUrl(e.url)) throw new Error('扩展页面(chrome-extension://)不能被自动化操作')
305
+ }
306
+ if (method === 'Network.getResponseBody' && hasProtectedSites()) {
307
+ // 响应体可能是别的标签页 / 别的网站 / 受保护站重定向到 CDN 的接口:核对整条重定向链 + 发起页面来源
308
+ const id = Number(tabId)
309
+ const rid = params?.requestId
310
+ const rec = rid == null ? null
311
+ : S.netPending.get(`${id}/${rid}`) || S.NET.findLast((n) => n.tabId === id && n.id === rid)
312
+ const chain = [...new Set([rec?.url, ...(rec?.urls || []), rec?.pageUrl].filter((u) => typeof u === 'string' && u))]
313
+ if (!rec || !chain.length)
314
+ throw new Error('USER_DENIED_SENSITIVE 找不到这条网络请求的记录:开着受保护网站时,只能读这个标签页里记录在案的请求的响应')
315
+ for (const u of chain) {
316
+ if (!isUrlAllowed(id, u)) await ensureUrlAllowed(id, u, { op: 'cdp' })
317
+ }
318
+ }
319
+ const run = () => send(tabId, method, params || {}, timeoutMs)
320
+ return { result: method.startsWith('Input.') ? await agentInput(tabId, run) : await run() }
321
+ },
322
+
323
+ async nav({ tabId, url, wait = true, timeoutMs = 30000 }) {
324
+ const deadline = Date.now() + timeoutMs
325
+ const id = await within(ensure(tabId), timeoutMs, '等待调试器超时')
326
+ const waitMs = timeLeft(deadline)
327
+ // 加载完 → loaded=true;超时 → loaded=false(照样返回,调用方提示「还没加载完」);
328
+ // 标签页关了 / 调试器断了 → failLoadWaiter 直接让它失败
329
+ let entry
330
+ const loadedEvent = wait && new Promise(resolve => {
331
+ const entries = S.loadWaiters.get(id) || new Set()
332
+ entry = { finish(value) {
333
+ if (!entries.has(entry)) return
334
+ clearTimeout(entry.timer)
335
+ entries.delete(entry)
336
+ if (!entries.size) S.loadWaiters.delete(id)
337
+ resolve(value)
338
+ } }
339
+ entries.add(entry)
340
+ S.loadWaiters.set(id, entries)
341
+ entry.timer = setTimeout(() => entry.finish(false), waitMs)
342
+ })
343
+ let r, loaded = null
344
+ try {
345
+ r = await send(id, 'Page.navigate', { url }, timeLeft(deadline))
346
+ if (r.errorText) throw new Error(r.errorText)
347
+ // 同文档跳转(只改 #hash):Page.navigate 照常回 frameId 但不带 loaderId,也不会再来 loadEventFired —— 别白等到超时
348
+ if (wait) loaded = r.frameId && !r.loaderId ? true : await loadedEvent
349
+ if (loaded instanceof Error) throw loaded
350
+ } finally { if (entry && S.loadWaiters.get(id)?.has(entry)) entry.finish(false) }
351
+ const t = await chrome.tabs.get(id).catch(() => null)
352
+ const finalUrl = (t && t.url) || url
353
+ // 跳转后(多半是被重定向)落到了没放行的受保护网站上:标题、路径都不给,只说到了哪个网站;
354
+ // 接下来读它、动它都会先弹窗问用户
355
+ if (hasProtectedSites() && (await loadProtectedSites(), !isUrlAllowed(id, finalUrl))) {
356
+ let origin = ''
357
+ try { origin = new URL(finalUrl).origin } catch {}
358
+ return { url: origin, title: '', frameId: r.frameId, waited: !!wait, loaded, protectedSite: true,
359
+ note: '跳到了受保护网站,标题和地址已隐藏;接下来在这个页面上读或操作都要用户先在弹窗里放行' }
360
+ }
361
+ return { url: finalUrl, title: t && t.title, frameId: r.frameId, waited: !!wait, loaded }
362
+ },
363
+
364
+ async click({ tabId, x, y, clickCount, button, chooser }) {
365
+ return clickPoint(tabId, x, y, { clickCount, button, chooser, cursor: { label: `${labels[S.UI_LANG].click} (${Math.round(x)}, ${Math.round(y)})` } })
366
+ },
367
+
368
+ async clickEl({ tabId, selector, chooser, clickCount, button }, { deadline, check } = {}) {
369
+ const pt = await pointOf(tabId, `
370
+ const el = document.querySelector(${JSON.stringify(selector)});
371
+ if (!el) return null;
372
+ let target = el;
373
+ const r0 = el.getBoundingClientRect();
374
+ if (r0.width < 1 || r0.height < 1) {
375
+ const inner = [...el.querySelectorAll('*')].find(__dsh_visible);
376
+ if (inner) target = inner;
377
+ }
378
+ if (!__dsh_visible(target) && !target.getBoundingClientRect().width) return null;
379
+ return __dsh_point(target);
380
+ `, deadline)
381
+ const hit = await clickPoint(tabId, pt.x, pt.y, { deadline, check, clickCount, button, chooser, cursor: { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` } })
382
+ return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
383
+ },
384
+
385
+ async clickText({ tabId, text, exact = true, index = 0, chooser, clickCount, button }) {
386
+ const pt = await pointOf(tabId, `
387
+ const want = __dsh_norm(${JSON.stringify(text)});
388
+ const SEL = 'a,button,input,textarea,select,label,summary,[role=button],[role=link],[role=tab],[role=menuitem],[onclick],[contenteditable=true],li,td,th,h1,h2,h3,h4,span,div,p';
389
+ const all = [...document.querySelectorAll(SEL)].filter(__dsh_visible);
390
+ const label = (el) => __dsh_norm(el.innerText || (['button', 'submit', 'reset'].includes(el.type) ? el.value : '') || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '');
391
+ let hit = all.filter((el) => label(el) === want);
392
+ if (!hit.length && ${exact ? 'false' : 'true'}) hit = all.filter((el) => label(el).includes(want));
393
+ if (!hit.length) return null;
394
+ hit.sort((a, b) => { const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return ra.width * ra.height - rb.width * rb.height; });
395
+ const el = hit[Math.min(${Number(index) || 0}, hit.length - 1)];
396
+ // 元素框常常比可见按钮大得多(<a> 里塞满空白),点框中心会落在按钮外面。
397
+ // 所以先找承载这段文字的文本节点,用 Range 拿它的**精确**位置。
398
+ const textRect = (root, needle) => {
399
+ const w = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
400
+ let n;
401
+ while ((n = w.nextNode())) {
402
+ const t = __dsh_norm(n.nodeValue || '');
403
+ if (!t) continue;
404
+ if (t === needle || t.includes(needle)) {
405
+ const rg = document.createRange();
406
+ rg.selectNodeContents(n);
407
+ const rc = rg.getBoundingClientRect();
408
+ if (rc.width > 0 && rc.height > 0) return rc;
409
+ }
410
+ }
411
+ return null;
412
+ };
413
+ const tr = textRect(el, want);
414
+ if (tr) {
415
+ const pr = el.getBoundingClientRect();
416
+ return { ...__dsh_cover(el, Math.round(tr.x + tr.width / 2), Math.round(tr.y + tr.height / 2)), x: Math.round(tr.x + tr.width / 2), y: Math.round(tr.y + tr.height / 2),
417
+ text: (el.innerText || '').trim().slice(0, 60), tag: el.tagName.toLowerCase(),
418
+ rect: [Math.round(pr.x), Math.round(pr.y), Math.round(pr.width), Math.round(pr.height)],
419
+ textRect: [Math.round(tr.x), Math.round(tr.y), Math.round(tr.width), Math.round(tr.height)] };
420
+ }
421
+ return __dsh_point(el);
422
+ `)
423
+ const hit = await clickPoint(tabId, pt.x, pt.y, { clickCount, button, chooser, cursor: { label: `${labels[S.UI_LANG].click} ${pt.text || pt.tag}` } })
424
+ return { ...hit, target: pt, ...(pt.occluded && { occluded: pt.occluded }) }
425
+ },
426
+
427
+ async type({ tabId, text, selector }) {
428
+ if (selector) await getOps().clickEl({ tabId, selector })
429
+ await ensure(tabId)
430
+ // 名牌写上在输什么。只有确认焦点落在普通(非密码)输入框里才亮原文:焦点在 shadow DOM / 同源 iframe 里
431
+ // 就往里找真正的焦点元素;找不到(跨域 iframe、关闭的 shadow root……)或者是密码样式的框,一律打码
432
+ const sensitive = /^\d{4,}$/.test(text) || /(?:\d\s*){6}|(?:bearer\s+|sk[-_]|gh[pousr]_|eyJ|AKIA)[\w./+=-]{6,}/i.test(text) ||
433
+ (text.match(/[\w+/-]{24,}/g) || []).some(word => /[a-z]/i.test(word) && /\d/.test(word))
434
+ const shown = sensitive ? 'null' : JSON.stringify(text.length > 24 ? text.slice(0, 24) + '…' : text)
435
+ await cursorFx(tabId, `(() => {
436
+ let a = document.activeElement;
437
+ for (let i = 0; a && i < 32; i++) {
438
+ if (a.shadowRoot && a.shadowRoot.activeElement) { a = a.shadowRoot.activeElement; continue; }
439
+ if (a.tagName === 'IFRAME' || a.tagName === 'FRAME') { let d = null; try { d = a.contentDocument; } catch {} a = d && d.activeElement; continue; }
440
+ break;
441
+ }
442
+ let plain = false;
443
+ try {
444
+ const sec = (a.ownerDocument.defaultView || window).getComputedStyle(a).webkitTextSecurity || 'none';
445
+ plain = ((a.tagName === 'INPUT' && a.type !== 'password') || a.tagName === 'TEXTAREA' || a.isContentEditable) && sec === 'none' &&
446
+ a.type !== 'tel' && !/one-time-code|current-password|new-password|cc-number|cc-csc/i.test(a.autocomplete || '') &&
447
+ a.inputMode !== 'numeric' && !/code|verif|2fa|mfa|pin|otp|cvv|cvc|card|secret|token|pwd|pass|api[_-]?key/i.test([a.name, a.id].join(' '));
448
+ } catch {}
449
+ window.__dshCursor.label(${JSON.stringify(labels[S.UI_LANG].type + ' ')} + (plain && ${!sensitive} ? ${shown} : '••••••'));
450
+ return 1;
451
+ })()`)
452
+ await agentInput(tabId, () => send(tabId, 'Input.insertText', { text }))
453
+ return { typed: text.length, selector: selector || null }
454
+ },
455
+
456
+ // ── 读取类:让模型能"看"页面 ──────────────────────────────────────────────
457
+
458
+ async text({ tabId, selector, limit = 8000 }) {
459
+ const js = selector
460
+ ? `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? (el.innerText || el.textContent || '') : null })()`
461
+ : `document.body ? (document.body.innerText || '') : ''`
462
+ const t = await evaluate(tabId, js)
463
+ if (t === null) throw new Error(`没找到元素: ${selector}`)
464
+ const s = String(t)
465
+ const cut = s.length > limit
466
+ return { text: cut ? s.slice(0, limit) + `\n…(截断,全文 ${s.length} 字)` : s, length: s.length, truncated: cut }
467
+ },
468
+
469
+ async html({ tabId, selector = 'body', limit = 4000 }) {
470
+ const t = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? el.outerHTML : null })()`)
471
+ if (t === null) throw new Error(`没找到元素: ${selector}`)
472
+ const s = String(t)
473
+ const cut = s.length > limit
474
+ return { html: cut ? s.slice(0, limit) + `…(截断,全文 ${s.length} 字)` : s, length: s.length, truncated: cut }
475
+ },
476
+
477
+ async attr({ tabId, selector, name }) {
478
+ const value = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); return el ? el.getAttribute(${JSON.stringify(name)}) : null })()`)
479
+ return { selector, name, value }
480
+ },
481
+
482
+ async info({ tabId }) {
483
+ const t = await chrome.tabs.get(Number(tabId))
484
+ let viewport = null
485
+ try {
486
+ await ensure(tabId)
487
+ const m = await send(tabId, 'Page.getLayoutMetrics')
488
+ const v = m.cssVisualViewport
489
+ viewport = { w: Math.round(v.clientWidth), h: Math.round(v.clientHeight), scrollY: Math.round(v.pageY) }
490
+ } catch {}
491
+ return {
492
+ tabId: Number(tabId), url: t.url, title: t.title, status: t.status,
493
+ windowId: t.windowId, active: t.active, attached: S.attached.has(Number(tabId)),
494
+ viewport, pendingDialog: S.dialogs.get(Number(tabId)) || null,
495
+ }
496
+ },
497
+
498
+ async waitFor({ tabId, selector, timeoutMs = 15000, visible = true }) {
499
+ const deadline = Date.now() + Number(timeoutMs)
500
+ const js = `(() => {
501
+ const el = document.querySelector(${JSON.stringify(selector)});
502
+ if (!el) return null;
503
+ const r = el.getBoundingClientRect();
504
+ const st = getComputedStyle(el);
505
+ const vis = r.width > 0 && r.height > 0 && st.visibility !== 'hidden' && st.display !== 'none';
506
+ return { found: true, visible: vis, x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 2), text: (el.innerText || '').trim().slice(0, 60) };
507
+ })()`
508
+ let last = null
509
+ while (Date.now() < deadline) {
510
+ last = await evaluate(tabId, js, false, Math.max(1, deadline - Date.now()))
511
+ if (last && (!visible || last.visible)) return { ...last, waitedMs: Number(timeoutMs) - (deadline - Date.now()) }
512
+ await sleep(Math.min(250, Math.max(0, deadline - Date.now())))
513
+ }
514
+ throw new Error(`等了 ${timeoutMs}ms 还没等到 ${selector}${last ? '(元素在,但不可见)' : ''}`)
515
+ },
516
+
517
+ // ── 输入类 ───────────────────────────────────────────────────────────────
518
+
519
+ async hover({ tabId, x, y, selector }) {
520
+ let px = Number(x) || 0, py = Number(y) || 0, target = null
521
+ if (selector) {
522
+ const pt = await pointOf(tabId, `const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return null; return __dsh_point(el);`)
523
+ px = pt.x; py = pt.y; target = pt
524
+ }
525
+ if (S.showCursor) {
526
+ const d = await cursorMove(tabId, px, py, { label: `${labels[S.UI_LANG].hover} ${target ? target.text || target.tag : `(${Math.round(px)}, ${Math.round(py)})`}` })
527
+ if (d !== null) await settle(d)
528
+ }
529
+ await agentInput(tabId, () => send(tabId, 'Input.dispatchMouseEvent', { type: 'mouseMoved', x: Math.round(px), y: Math.round(py), buttons: 0 }))
530
+ return { x: Math.round(px), y: Math.round(py), target }
531
+ },
532
+
533
+ async scroll({ tabId, x = 200, y = 200, deltaY = 600, deltaX = 0 }) {
534
+ const before = await evaluate(tabId, 'Math.round(window.scrollY)')
535
+ await cursorFx(tabId, `(window.__dshCursor.label(${JSON.stringify(deltaY < 0 ? labels[S.UI_LANG].up : labels[S.UI_LANG].down)}, 1400), window.__dshCursor.scroll(${deltaY < 0 ? -1 : 1}), 1)`)
536
+ await sendNoReply(tabId, 'Input.dispatchMouseEvent', {
537
+ type: 'mouseWheel', x: Math.round(x), y: Math.round(y),
538
+ deltaX: Math.round(deltaX), deltaY: Math.round(deltaY),
539
+ })
540
+ let after = await evaluate(tabId, '({ scrollY: Math.round(window.scrollY), pageHeight: Math.round(document.documentElement.scrollHeight) })')
541
+ let via = 'wheel'
542
+ if (after.scrollY === before) {
543
+ // 后台/不可见标签页里 Chrome 不会为滚轮合成帧(实测 mouseWheel 事件发了但页面不动),
544
+ // 退回 JS 滚动 —— 想要的效果是"页面滚下去",不是"必须是合成事件"。
545
+ after = await evaluate(tabId, `(() => { window.scrollBy(0, ${Math.round(deltaY)}); return { scrollY: Math.round(window.scrollY), pageHeight: Math.round(document.documentElement.scrollHeight) } })()`)
546
+ via = 'js'
547
+ }
548
+ return { deltaY, via, ...after }
549
+ },
550
+
551
+ async focus({ tabId, selector }) {
552
+ const ok = await evaluate(tabId, `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return false; el.focus(); return document.activeElement === el })()`)
553
+ if (!ok) throw new Error(`聚焦失败: ${selector}`)
554
+ return { focused: selector }
555
+ },
556
+
557
+ async select({ tabId, selector, value }) {
558
+ const r = await evaluate(tabId, `(() => {
559
+ const el = document.querySelector(${JSON.stringify(selector)});
560
+ if (!el) return { ok: false, why: '找不到元素' };
561
+ if (el.tagName !== 'SELECT') return { ok: false, why: '不是 <select> 元素' };
562
+ const opts = [...el.options];
563
+ const hit = opts.find(o => o.value === ${JSON.stringify(value)}) || opts.find(o => (o.textContent || '').trim() === ${JSON.stringify(value)});
564
+ if (!hit) return { ok: false, why: '没有这个选项', options: opts.map(o => o.value).slice(0, 20) };
565
+ el.value = hit.value;
566
+ el.dispatchEvent(new Event('input', { bubbles: true }));
567
+ el.dispatchEvent(new Event('change', { bubbles: true }));
568
+ return { ok: true, value: hit.value, label: (hit.textContent || '').trim() };
569
+ })()`)
570
+ if (!r.ok) throw new Error(`选择失败:${r.why}${r.options ? '(可选值:' + r.options.join(', ') + ')' : ''}`)
571
+ return r
572
+ },
573
+
574
+ async upload({ tabId, selector, files, chooserId }) {
575
+ const list = Array.isArray(files) ? files : [files]
576
+ // 兜底(插件那边已按 realpath 卡过目录):只收绝对路径,任何一段以 . 开头(隐藏目录 / 文件、..)都不收。
577
+ // 绝对路径:/ 开头(Mac / Linux),或盘符 C:\ 和 \\server\share(Windows;以前只认 /,Windows 上一律被拒)
578
+ for (const path of list) checkPath(path)
579
+ await ensure(tabId)
580
+ if ((await fileAccess()) === false) throw fileAccessError()
581
+ const put = async (params) => {
582
+ try {
583
+ await send(tabId, 'DOM.setFileInputFiles', { files: list, ...params })
584
+ } catch (e) {
585
+ if (/Not allowed/.test(String(e && e.message || e))) throw fileAccessError()
586
+ throw e
587
+ }
588
+ }
589
+ if (!selector) {
590
+ // 没给选择器:塞给刚才拦下的选文件窗口对应的那个框(多半是藏起来的 <input type=file>)。
591
+ // 只认点击回话里给出的那个 id:同一个标签页别的会话后来又点开一个,不能把文件塞到人家的框里
592
+ const id = Number(tabId)
593
+ const c = S.choosers.get(id)
594
+ const none = () => new Error('NO_FILE_CHOOSER 页面现在没在等选文件:先点页面上的上传按钮,或者给出文件输入框的选择器')
595
+ if (c && Date.now() - c.at > CHOOSER_TTL_MS) dropChooser(id, c)
596
+ if (!c || !c.backendNodeId || c.folder || !chooserId || c.id !== String(chooserId) || Date.now() - c.at > CHOOSER_TTL_MS) throw none()
597
+ await c.ready
598
+ // 调试会话断开期间换过页(那时收不到 frameNavigated):文档对不上就当框没了,别往别的节点上塞
599
+ // 只删自己这条:等回包的工夫别的请求可能已经拦下了新框
600
+ const drop = () => dropChooser(id, c)
601
+ if (c.doc && (await docOf(id, c.frameId, send)) !== c.doc) { drop(); throw none() }
602
+ const st = await inputState(id, c.backendNodeId, send, c.key)
603
+ // 拦下时在页面上、现在不在了(弹层关了重开、被页面换掉了):别塞给脱离页面的旧节点。
604
+ // 拦下时就不在页面上的(脚本现造一个 input、不插进页面直接 click,很常见)照常塞
605
+ if (st && !st.on && c.state && c.state.on) { drop(); throw none() }
606
+ // 拦下以后用户自己点开过 / 选过(网页读完文件常把框清空,所以光比文件不够):别拿模型的文件把它盖掉
607
+ if (st && c.state && (st.touched > 0 || st.files !== c.state.files)) { drop(); throw new Error('USER_PICKED 拦下以后有人自己动过这个文件框(多半是用户自己选了文件),没有替换') }
608
+ if (c.mode === 'selectSingle' && list.length > 1) throw new Error(`MULTI_NOT_ALLOWED 这个文件框一次只收一个文件(给了 ${list.length} 个)`)
609
+ try {
610
+ await put({ backendNodeId: c.backendNodeId })
611
+ } catch (e) {
612
+ // 页面换过 / 那个框被删了:节点找不到
613
+ if (/No node|Could not find node|not found/i.test(String(e && e.message || e))) { drop(); throw none() }
614
+ throw e
615
+ }
616
+ drop()
617
+ return { selector: null, chooser: true, files: list }
618
+ }
619
+ const { root } = await send(tabId, 'DOM.getDocument', { depth: -1, pierce: true })
620
+ const { nodeId } = await send(tabId, 'DOM.querySelector', { nodeId: root.nodeId, selector })
621
+ if (!nodeId) throw new Error(`没找到文件输入框: ${selector}`)
622
+ const { node } = await send(tabId, 'DOM.describeNode', { nodeId })
623
+ if (isFolderNode(node)) throw new Error('FOLDER_INPUT 这是选文件夹的框(webkitdirectory),DSH 暂时没法替你选文件夹:请用户自己点它选')
624
+ // 单选的框塞多个,Chrome 只留第一个:别报「都交了」
625
+ // 选中的不是文件框(比如旁边显示文件名的文本框)就不管,让 Chrome 自己报「不是文件框」
626
+ const isFile = node && String(node.nodeName).toUpperCase() === 'INPUT' && String(attrValue(node, 'type') || '').toLowerCase() === 'file'
627
+ if (list.length > 1 && isFile && !hasAttr(node, 'multiple')) {
628
+ throw new Error(`MULTI_NOT_ALLOWED 这个文件框一次只收一个文件(给了 ${list.length} 个)`)
629
+ }
630
+ await put({ nodeId })
631
+ // 塞的正是拦下的那个框才算用掉;别的框(别的会话正等着的)留着
632
+ const c = S.choosers.get(Number(tabId))
633
+ if (c && node && c.backendNodeId === node.backendNodeId) dropChooser(tabId, c)
634
+ return { selector, files: list }
635
+ },
636
+
637
+ /** 被 alert/confirm 挡住时用这个放行,否则页面会一直卡住 */
638
+ async dialog({ tabId, action, text }) {
639
+ const accept = action !== 'dismiss'
640
+ await send(tabId, 'Page.handleJavaScriptDialog', { accept, ...(text !== undefined ? { promptText: String(text) } : {}) })
641
+ S.dialogs.delete(Number(tabId))
642
+ return { action: accept ? 'accept' : 'dismiss' }
643
+ },
644
+
645
+ async key({ tabId, key, times = 1, chooser }) {
646
+ await ensure(tabId)
647
+ // 焦点在「上传」按钮上按回车 / 空格也会弹选文件窗口
648
+ return withChooser(tabId, chooser, async () => {
649
+ const out = []
650
+ for (let i = 0; i < times; i++) out.push(await pressKey(tabId, key))
651
+ return { pressed: key, times, modifiers: out[0] && out[0].modifiers }
652
+ })
653
+ },
654
+
655
+ async shot({ tabId, format = 'png', quality, full = false, selector, timeoutMs }) {
656
+ const deadline = timeoutMs && Date.now() + timeoutMs
657
+ const params = { format, captureBeyondViewport: !!full }
658
+ if (format === 'jpeg' && quality) params.quality = quality
659
+ let clip = null
660
+ if (selector) {
661
+ const rect = await evaluate(tabId, `(() => {
662
+ const el = document.querySelector(${JSON.stringify(selector)});
663
+ if (!el) return null;
664
+ el.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' });
665
+ // 后台标签页会暂停 rAF —— 只等 rAF 会卡满 15 秒,定时器兜底(同 __dsh_point)
666
+ return new Promise((res) => {
667
+ let done = false;
668
+ const finish = () => {
669
+ if (done) return;
670
+ done = true;
671
+ const r = el.getBoundingClientRect();
672
+ res({ ...__dsh_cover(el, r.left + r.width / 2, r.top + r.height / 2), x: r.left, y: r.top, width: r.width, height: r.height });
673
+ };
674
+ requestAnimationFrame(() => requestAnimationFrame(finish));
675
+ setTimeout(finish, 120);
676
+ });
677
+ })()`, false, timeoutMs)
678
+ if (!rect) throw new Error(`没找到元素: ${selector}`)
679
+ clip = { x: rect.x, y: rect.y, width: rect.width, height: rect.height, scale: 1 }
680
+ params.clip = clip
681
+ params.captureBeyondViewport = false
682
+ }
683
+ const r = await send(tabId, 'Page.captureScreenshot', params, deadline && timeLeft(deadline))
684
+ const t = await chrome.tabs.get(Number(tabId)).catch(() => null)
685
+ return { data: r.data, format, url: t && t.url, title: t && t.title, full: !!full, clip }
686
+ },
687
+
688
+ async network({ tabId, limit = 40, filter, clear, reload = false, waitMs = 2500 }) {
689
+ // 清单非空时,按每条记录发生时的来源及请求链过滤(不给 tabId 时一并核对标签页当前网址)
690
+ const visible = await protectedFilter(S.NET, tabId == null)
691
+ const dropTab = (id) => {
692
+ for (let i = S.NET.length - 1; i >= 0; i--) {
693
+ if (S.NET[i].tabId === id && (!visible || visible(S.NET[i]))) S.NET.splice(i, 1)
694
+ }
695
+ }
696
+ if (clear) {
697
+ if (tabId != null) dropTab(Number(tabId))
698
+ else if (!visible) S.NET.length = 0
699
+ else for (let i = S.NET.length - 1; i >= 0; i--) if (visible(S.NET[i])) S.NET.splice(i, 1)
700
+ return { cleared: true }
701
+ }
702
+ // Network 事件只在 attach 之后才有,所以先 attach;要历史就 --reload 刷一次
703
+ if (tabId != null && reload) {
704
+ await ensure(tabId)
705
+ dropTab(Number(tabId))
706
+ await send(tabId, 'Page.reload', {})
707
+ await new Promise(r => setTimeout(r, Number(waitMs)))
708
+ } else if (tabId != null) {
709
+ await ensure(tabId)
710
+ }
711
+ let items = tabId != null ? S.NET.filter(n => n.tabId === Number(tabId)) : S.NET
712
+ if (visible) items = items.filter(visible)
713
+ if (filter) items = items.filter(n => (n.url || '').includes(filter) || (n.method || '').includes(filter))
714
+ return {
715
+ items: items.slice(-limit).map(n => ({
716
+ id: n.id, method: n.method, status: n.status, url: n.url, type: n.type, mime: n.mime, ms: n.ms, failed: n.failed,
717
+ })),
718
+ }
719
+ },
720
+
721
+ /**
722
+ * 录一段屏幕(CDP screencast),用来做演示 GIF。
723
+ * 帧以 base64 JPEG 返回;调用方自己写文件、自己合成。
724
+ */
725
+ async screencast({ tabId, durationMs = 5000, maxWidth = 900, quality = 70, maxFrames = 140 }) {
726
+ await ensure(tabId)
727
+ const id = Number(tabId)
728
+ const frames = []
729
+ let tainted = false
730
+ let frameCheck = null
731
+ const checkUrl = (url) => {
732
+ if (url && hasProtectedSites() && !isUrlAllowed(id, url)) {
733
+ tainted = true
734
+ frames.length = 0
735
+ }
736
+ }
737
+ const triggerFrameCheck = () => {
738
+ if (tainted || frameCheck || !hasProtectedSites()) return
739
+ frameCheck = areAllFramesAllowed(id)
740
+ .then((ok) => { if (!ok) { tainted = true; frames.length = 0 } })
741
+ .catch(() => { tainted = true; frames.length = 0 })
742
+ .finally(() => { frameCheck = null })
743
+ }
744
+ const onEvent = (src, method, params) => {
745
+ if (src.tabId !== id) return
746
+ if (method === 'Page.frameNavigated' && params.frame?.url) {
747
+ checkUrl(params.frame.url)
748
+ return
749
+ }
750
+ if (method !== 'Page.screencastFrame') return
751
+ checkUrl(S.tabUrl.get(id))
752
+ if (!tainted && !(hasProtectedSites() && frameCheck)) {
753
+ frames.push(params.data)
754
+ triggerFrameCheck()
755
+ }
756
+ chrome.debugger
757
+ .sendCommand({ tabId: id }, 'Page.screencastFrameAck', { sessionId: params.sessionId })
758
+ .catch(() => {})
759
+ }
760
+ const onTabUpd = (tid, change, tab) => {
761
+ if (tid === id) checkUrl(tab?.url || tab?.pendingUrl || change?.url)
762
+ }
763
+ const unsubscribe = onCdpEvent(onEvent)
764
+ S.tabUpdated.add(onTabUpd)
765
+ try {
766
+ await send(tabId, 'Page.startScreencast', {
767
+ format: 'jpeg', quality, maxWidth, maxHeight: Math.round(maxWidth * 1.4), everyNthFrame: 1,
768
+ })
769
+ const deadline = Date.now() + Number(durationMs)
770
+ // 帧太多会把一条 native message 撑爆(也拖慢回传),到上限或跳入受保护站就提前收工
771
+ while (!tainted && Date.now() < deadline && frames.length < Number(maxFrames)) {
772
+ triggerFrameCheck()
773
+ await new Promise((r) => setTimeout(r, 100))
774
+ }
775
+ await send(tabId, 'Page.stopScreencast').catch(() => {})
776
+ } finally {
777
+ unsubscribe()
778
+ S.tabUpdated.delete(onTabUpd)
779
+ }
780
+ if (frameCheck) await frameCheck
781
+ if (!tainted && hasProtectedSites()) {
782
+ const t = await chrome.tabs.get(id).catch(() => null)
783
+ for (const u of [t?.url, t?.pendingUrl]) checkUrl(u)
784
+ if (!tainted && !(await areAllFramesAllowed(id))) tainted = true
785
+ }
786
+ if (tainted) {
787
+ frames.length = 0
788
+ throw new Error('USER_DENIED_SENSITIVE 录屏途中进入了未放行的受保护网站,已丢弃画面并中止')
789
+ }
790
+ return { count: frames.length, frames }
791
+ },
792
+
793
+ /** 页内光标只加载包内资源。script 字段仅兼容旧协议。 */
794
+ async cursor({ tabId, action, x, y, duration, straight, text }) {
795
+ const id = Number(tabId)
796
+ if (action === 'hide' || action === 'clear') {
797
+ try { await evaluate(tabId, 'window.__dshCursor && window.__dshCursor.hide()') }
798
+ finally { S.cursorReady.delete(id); S.cursorPos.delete(id); await markCursor(tabId, false) }
799
+ return { action }
800
+ }
801
+ if (!S.showCursor) return { action, skipped: '用户在弹窗里关了页内光标', duration: 0 }
802
+ const missing = () => new Error('页内光标未能加载')
803
+ if (action === 'move' || action === 'click') {
804
+ const d = await cursorMove(tabId, x, y, { duration, straight, label: text })
805
+ if (d === null) throw missing()
806
+ if (action === 'click') {
807
+ await settle(d)
808
+ await cursorDo(tabId, `(window.__dshCursor.click(${Math.round(x)}, ${Math.round(y)}), 1)`)
809
+ }
810
+ return { action, x, y, duration: d }
811
+ }
812
+ const fx = { down: 'down()', up: 'up()', label: `label(${JSON.stringify(String(text || ''))})` }[action]
813
+ if (!fx) throw new Error(`不认识的光标动作: ${action}(move/click/down/up/label/hide/clear)`)
814
+ if ((await cursorDo(tabId, `(window.__dshCursor.${fx}, 1)`)) === undefined) throw missing()
815
+ return { action }
816
+ },
817
+ }
818
+
819
+ function getOps() {
820
+ return S.ops ??= Object.assign(Object.create(null), OPS)
821
+ }
822
+
823
+ function registerOps(extra) {
824
+ Object.assign(getOps(), extra)
825
+ }
826
+
827
+ export {
828
+ OPS, getOps, registerOps,
829
+ }