dsh-chrome-bridge 2.0.3 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +8 -1
  4. package/core/hosts.js +3 -4
  5. package/core/receipt.js +228 -31
  6. package/core/session.js +11 -14
  7. package/core/tooldef.js +10 -1
  8. package/core/transport.js +67 -17
  9. package/drag.js +10 -10
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +34 -7
  12. package/i18n/ru.js +34 -7
  13. package/i18n/zh.js +34 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +309 -73
  17. package/tools/batch.js +311 -0
  18. package/tools/click.js +37 -11
  19. package/tools/dialog.js +19 -2
  20. package/tools/drag.js +31 -5
  21. package/tools/fill.js +71 -22
  22. package/tools/index.js +3 -1
  23. package/tools/input.js +97 -36
  24. package/tools/nav.js +46 -23
  25. package/tools/read.js +2 -0
  26. package/tools/tabs.js +16 -2
  27. package/tools/wait.js +14 -6
  28. package/vendor/extension/in-page-cursor.js +1 -1
  29. package/vendor/extension/manifest.json +1 -1
  30. package/vendor/extension/popup.css +1 -0
  31. package/vendor/extension/popup.html +6 -3
  32. package/vendor/extension/popup.js +19 -13
  33. package/vendor/extension/sw/actions.js +573 -0
  34. package/vendor/extension/sw/boot.js +2 -1
  35. package/vendor/extension/sw/cdp.js +139 -11
  36. package/vendor/extension/sw/conditions.js +176 -0
  37. package/vendor/extension/sw/confirm.js +39 -7
  38. package/vendor/extension/sw/cursor.js +176 -14
  39. package/vendor/extension/sw/dispatch.js +6 -1
  40. package/vendor/extension/sw/frames.js +543 -47
  41. package/vendor/extension/sw/lifecycle.js +82 -0
  42. package/vendor/extension/sw/ops.js +801 -139
  43. package/vendor/extension/sw/page-access.js +292 -0
  44. package/vendor/extension/sw/popup-api.js +28 -7
  45. package/vendor/extension/sw/snapshot.js +251 -0
  46. package/vendor/extension/sw/state.js +16 -5
  47. package/vendor/extension/sw/tabui.js +9 -2
  48. package/vendor/in-page-cursor.js +1 -1
  49. package/vendor/skill/SKILL.md +8 -7
package/README.en.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Lets DSH work in the Chrome you already use: real clicks and typing, a cursor you can see on the page, and your own logins.
4
4
 
5
- - Ships 15 native `browser_*` tools: read pages (cross-site iframes included), click (left / right / middle, double-click), type, batch form fill, downloads (including files that only exist after a click), network-idle waits, console / network inspection, network mocks and redacted HAR export, `browser_handoff` when a login, captcha, 2FA or payment step needs you, and `browser_record` to save the session as an animated GIF.
5
+ - Ships 16 native `browser_*` tools: read pages (cross-site iframes & `mode="page"`), single-hop fast click/input/drag, multi-step `browser_batch`, default `observe="diff"` auto-diffs, batch form fill, downloads (including files that only exist after a click), in-page & network waits, console / network inspection, network mocks and redacted HAR export, `browser_handoff` when a login, captcha, 2FA or payment step needs you, and `browser_record` to save the session as an animated GIF.
6
6
  - Screenshots can number the clickable elements in view (`marks`), and actions work inside cross-site iframes; several browsers and profiles can be connected at once.
7
7
  - It won't touch a page you mark as protected without asking: the list starts empty, and once you add a domain in the popup, a confirmation window (deny by default, 15-minute grants) appears before it reads or acts there.
8
8
  - Pages it opens go into a separate window, so your own window gets no new tabs and keeps focus.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  让 DSH 直接操作你正在用的 Chrome:真点击、真输入,页面里看得到它的光标,你的登录状态都在。
4
4
 
5
- - 自带 15 个 `browser_*` 原生工具:读页面(含跨站 iframe)、点击(左右中键 / 双击)、输入、批量填表、下载(含点了才生成的文件)、等网络空闲、看 console 和网络请求、网络 Mock 与脱敏 HAR,以及需要你本人过登录 / 验证码时把页面交还给你的 `browser_handoff`、把操作过程录成 GIF 动图的 `browser_record`。
5
+ - 自带 16 个 `browser_*` 原生工具:读页面(含跨站 iframe 与 `mode="page"`)、单跳极速点击/输入/拖拽、批量连贯执行 `browser_batch`、默认 `observe="diff"` 自动回看变化、批量填表、下载(含点了才生成的文件)、页内等待、看 console 和网络请求、网络 Mock 与脱敏 HAR,以及需要你本人过登录 / 验证码时把页面交还给你的 `browser_handoff`、把操作过程录成 GIF 动图的 `browser_record`。
6
6
  - 截图可以给可点元素标编号(`marks`),也能在跨站 iframe 里操作;同时连多个浏览器 / Profile 也认得。
7
7
  - 它不会擅自碰你标为受保护的页面:清单默认是空的,只有你在扩展弹窗里加了域名,读或操作它之前才会先弹确认小窗(默认拒绝,放行 15 分钟)。
8
8
  - 它新开的页放进一个单独的窗口,不往你正在用的窗口里塞,也不抢焦点。
package/core/ext.js CHANGED
@@ -48,7 +48,7 @@ function currentHostKey() {
48
48
  function hostEntry(key = currentHostKey()) {
49
49
  let entry = hostVersions.get(key)
50
50
  if (!entry) {
51
- entry = { version: undefined, probe: undefined, lastProbe: 0 }
51
+ entry = { version: undefined, caps: undefined, probe: undefined, lastProbe: 0 }
52
52
  hostVersions.set(key, entry)
53
53
  if (hostVersions.size > 32) hostVersions.delete(hostVersions.keys().next().value)
54
54
  }
@@ -61,11 +61,17 @@ function checkExtensionVersion() {
61
61
  entry.lastProbe = Date.now()
62
62
  entry.probe = call('version', {}, 1200, true).then((r) => {
63
63
  entry.version = r?.version
64
+ entry.caps = r?.caps
64
65
  return r || {}
65
66
  }).catch(() => ({})).finally(() => { entry.probe = undefined })
66
67
  return entry.probe
67
68
  }
68
69
 
70
+ export async function hasCap(name) {
71
+ await cursorReady()
72
+ return hostVersions.get(currentHostKey())?.caps?.[name] === true
73
+ }
74
+
69
75
  export function getExtVersion() {
70
76
  return hostVersions.get(currentHostKey())?.version
71
77
  }
@@ -113,6 +119,7 @@ export async function refreshExtension() {
113
119
  if (version === want) return
114
120
  await call('reload', {}, 5000)
115
121
  entry.version = undefined
122
+ entry.caps = undefined
116
123
  entry.lastProbe = 0
117
124
  trace(`扩展 ${version} → ${want}:已让它重载`)
118
125
  } catch (e) {
package/core/hosts.js CHANGED
@@ -235,6 +235,9 @@ export function resolveHost({ profile, host, sessionHost, dir } = {}) {
235
235
  return { dir: d, legacy: false, ...explicit }
236
236
  }
237
237
 
238
+ const hasExplicit = explicit !== undefined && explicit !== null && String(explicit).trim() !== ''
239
+ if (!hasExplicit && useEnv && process.env.DSH_BRIDGE_SOCK) return legacyEndpoint(d)
240
+
238
241
  const { hosts } = scanHosts({ dir: d })
239
242
 
240
243
  if (explicit !== undefined && explicit !== null && String(explicit).trim() !== '') {
@@ -243,10 +246,6 @@ export function resolveHost({ profile, host, sessionHost, dir } = {}) {
243
246
  throw new Error(t('err.hostNotFound', { profile: String(explicit).trim() }))
244
247
  }
245
248
 
246
- if (useEnv && process.env.DSH_BRIDGE_SOCK) {
247
- return legacyEndpoint(d)
248
- }
249
-
250
249
  if (sessionHost) {
251
250
  const found = hosts.find((h) => h.id === sessionHost) || matchHost(hosts, sessionHost)
252
251
  if (found) return { ...found, dir: d, legacy: false }
package/core/receipt.js CHANGED
@@ -1,6 +1,41 @@
1
- import { call } from './transport.js'
2
- import { short } from './tooldef.js'
1
+ import { call, callInfo, resolveEndpoint } from './transport.js'
2
+ import { getExtVersion, hasCap, isExtAtLeast } from './ext.js'
3
+ import { hashUrl } from '../vendor/extension/sw/page-access.js'
4
+ import { pageContent, short, WAIT_MAX_MS } from './tooldef.js'
3
5
  import { t } from './locale.js'
6
+ import { observationBaseline, snapshot, staleRefHint } from '../refs.js'
7
+ import { waitForCondition } from '../nav.js'
8
+
9
+ export const observeParam = () => ({
10
+ type: 'string', enum: ['diff', 'viewport', 'page', 'none'], default: 'diff', description: t('param.observe'),
11
+ })
12
+ export const expectParam = () => ({
13
+ type: 'object', description: t('param.expect'), additionalProperties: false,
14
+ properties: {
15
+ selector: { type: 'string', minLength: 1 }, text: { type: 'string', minLength: 1 }, url: { type: 'string', minLength: 1 },
16
+ gone: { type: 'boolean' }, timeoutMs: { type: 'integer', minimum: 1, maximum: WAIT_MAX_MS },
17
+ },
18
+ })
19
+ export const navWaitParam = () => ({
20
+ type: 'string', enum: ['dom', 'load', 'idle', 'none'], default: 'dom', description: t('param.navWait'),
21
+ })
22
+
23
+ export function validateNavWait(wait = 'dom') {
24
+ if (!['dom', 'load', 'idle', 'none'].includes(wait)) throw new Error(t('err.navWait'))
25
+ return wait
26
+ }
27
+
28
+ export function validateExpect(expect) {
29
+ if (expect === undefined) return
30
+ if (!expect || typeof expect !== 'object' || Array.isArray(expect) ||
31
+ !Object.keys(expect).every((key) => Object.hasOwn(expectParam().properties, key)) ||
32
+ ['selector', 'text', 'url'].filter((key) => expect[key]).length !== 1 ||
33
+ ['selector', 'text', 'url'].some((key) => expect[key] !== undefined && (typeof expect[key] !== 'string' || !expect[key].trim())) ||
34
+ (expect.gone !== undefined && typeof expect.gone !== 'boolean') ||
35
+ (expect.timeoutMs !== undefined && (!Number.isInteger(expect.timeoutMs) || expect.timeoutMs < 1 || expect.timeoutMs > WAIT_MAX_MS))) {
36
+ throw new Error(t('err.expect'))
37
+ }
38
+ }
4
39
 
5
40
  const ACTION_STATE_JS = `(() => {
6
41
  const live = [];
@@ -12,45 +47,207 @@ const ACTION_STATE_JS = `(() => {
12
47
  if (text && !live.includes(text)) live.push(text);
13
48
  if (live.length >= 30) break;
14
49
  }
15
- return { url: location.href, title: document.title, live };
50
+ return { url: location.href, urlHash: (${hashUrl})(location.href), title: document.title, documentToken: globalThis.performance?.timeOrigin ?? (window.__dshDocToken ||= Math.random().toString(36).slice(2)), live };
16
51
  })()`
17
52
 
18
- export async function probeState(tabId) {
53
+ export function originOf(url) {
54
+ try {
55
+ const origin = new URL(url).origin
56
+ return origin === 'null' ? '' : origin
57
+ } catch { return '' }
58
+ }
59
+
60
+ export const blocksObservation = (receipt) => !receipt || receipt.protectedSite || receipt.originChanged ||
61
+ receipt.pendingDialog || receipt.unverified
62
+
63
+ export function inBatch() {
64
+ return Boolean(callInfo.getStore()?.batch)
65
+ }
66
+
67
+ const actionTimeout = (expect) => 95_000 + (expect?.timeoutMs ?? (expect ? 15000 : 0))
68
+
69
+ export async function probeState(tabId, { strict = false, quiet = false, noReattach = false, controlEpoch } = {}) {
19
70
  try {
20
- return (await call('eval', { tabId, expression: ACTION_STATE_JS, userGesture: false }, 850, true)).value
21
- } catch {}
71
+ const r = await call('eval', {
72
+ tabId, expression: ACTION_STATE_JS, userGesture: false,
73
+ ...(strict ? { requireControl: true } : {}),
74
+ ...(noReattach ? { noReattach: true } : {}),
75
+ ...(Number.isInteger(controlEpoch) ? { controlEpoch } : {}),
76
+ }, quiet ? 2200 : 65_000, true)
77
+ return r.value ? {
78
+ ...r.value, controlEpoch: r.controlEpoch,
79
+ ...(Number.isInteger(r.navGeneration) ? { navGeneration: r.navGeneration } : {}),
80
+ } : undefined
81
+ } catch (error) {
82
+ if (strict || ['USER_ACTIVE', 'USER_DENIED_SENSITIVE', 'CONFIRM_LATE', 'NO_TAB'].includes(error.code)) throw error
83
+ }
22
84
  }
23
85
 
24
- export async function actionReceipt(tabId, before, result) {
86
+ async function legacyReceipt(tabId, before, result, { opened = false } = {}) {
87
+ const beforeUrl = before?.url
88
+ const beforeTitle = before?.title
89
+ const direct = result?.url
90
+ const state = { beforeUrl, beforeTitle, url: direct, title: result?.title, navigated: result?.navigated,
91
+ protectedSite: result?.protectedSite, pendingDialog: result?.pendingDialog, openedTabs: result?.openedTabs }
92
+ const expected = originOf(beforeUrl)
93
+ if (expected && direct && originOf(direct) !== expected) state.originChanged = true
94
+ if (blocksObservation(state)) return state
95
+
96
+ // Legacy eval/info can raise a confirmation prompt or re-attach on release. Tabs and panel do not read page content.
25
97
  try {
26
- const [after, info] = await Promise.all([
27
- probeState(tabId),
28
- call('info', { tabId }, 850, true).catch(() => null),
98
+ if (!expected) return { ...state, unverified: true }
99
+ const [panel, tabs, modern] = await Promise.all([
100
+ call('panel', {}, 1500, true), call('tabs', {}, 1500, true), hasCap('actV1'),
29
101
  ])
30
- const lines = []
31
- const page = after?.url !== undefined ? after : result?.url !== undefined ? result : info
32
- if (before && page?.url !== undefined && (page.url !== before.url || page.title !== before.title)) {
33
- lines.push(`→ ${[short(page.title, 100), short(page.url, 250)].filter(Boolean).join(' ')}`)
102
+ if (panel?.protectedCount !== 0) return { ...state, unverified: true }
103
+ const tab = tabs.find((entry) => entry.id === tabId)
104
+ if (!tab || !originOf(tab.url)) return { ...state, unverified: true }
105
+ if (originOf(tab.url) !== expected) return { ...state, url: originOf(tab.url), originChanged: true, navigated: !opened }
106
+ const hasEpoch = Number.isInteger(before?.controlEpoch)
107
+ if (!modern && !getExtVersion()) return { ...state, unverified: true }
108
+ if (!modern && isExtAtLeast(2, 0) && !hasEpoch) return { ...state, unverified: true }
109
+ const epochOpt = hasEpoch ? { controlEpoch: before.controlEpoch } : {}
110
+ if (modern || !isExtAtLeast(2, 0)) {
111
+ const info = await call('info', { tabId, ...(modern ? { noReattach: true } : {}), ...epochOpt }, 2200, true)
112
+ if (originOf(info.url) !== expected) return { ...state, url: originOf(info.url), originChanged: true, navigated: !opened }
113
+ if (info.pendingDialog) return { ...state, url: info.url, title: info.title, pendingDialog: info.pendingDialog }
34
114
  }
35
- if (result?.openedTabs?.length) {
36
- const tabs = result.openedTabs.slice(0, 4).map((tb) => `[${tb.tabId ?? tb.id}] ${short(tb.url, 120)}`)
37
- if (result.openedTabs.length > tabs.length) tabs.push(`+${result.openedTabs.length - tabs.length}`)
38
- lines.push(t('res.action.tabs', { tabs: tabs.join(' · ') }))
115
+ const after = await probeState(tabId, { quiet: true, ...(modern ? { noReattach: true } : {}), ...epochOpt })
116
+ if (!after) return { ...state, unverified: true }
117
+ if (originOf(after.url) !== expected) return { ...state, url: originOf(after.url), originChanged: true, navigated: !opened }
118
+ return {
119
+ ...state, url: after.url, urlHash: after.urlHash ?? hashUrl(after.url), title: after.title, documentToken: after.documentToken,
120
+ ...(Number.isInteger(after.controlEpoch) ? { controlEpoch: after.controlEpoch } : epochOpt),
121
+ ...(Number.isInteger(after.navGeneration) ? { navGeneration: after.navGeneration } : {}),
122
+ navigated: state.navigated ?? (!opened && (after.url !== beforeUrl ||
123
+ (before?.documentToken != null && after.documentToken !== before.documentToken))),
124
+ liveUpdate: before?.live && after.live?.find((text) => !before.live.includes(text)),
125
+ legacySafe: true,
39
126
  }
40
- const notes = []
41
- if (result?.occluded) {
42
- const { tag, text } = result.occluded
43
- notes.push(t('res.action.occluded', { target: [short(tag, 30), short(text, 80)].filter(Boolean).join(' ') || '—' }))
127
+ } catch (error) {
128
+ return { ...state, unverified: true, error }
129
+ }
130
+ }
131
+
132
+ export async function actionReceipt(tabId, before, result, options) {
133
+ return result?.receipt ?? legacyReceipt(tabId, before, result, options)
134
+ }
135
+
136
+ export function receiptText(receipt, result) {
137
+ if (!receipt) return ''
138
+ const { beforeUrl, beforeTitle, url, title, navigated, originChanged, protectedSite, pendingDialog, liveUpdate, openedTabs } = receipt
139
+ const lines = []
140
+ if (url && (originChanged || protectedSite || navigated || beforeUrl && (url !== beforeUrl || title !== beforeTitle))) {
141
+ const destination = originChanged || protectedSite ? [originOf(url)] : [short(title, 100), short(url, 250)]
142
+ const label = destination.filter(Boolean).join(' ')
143
+ if (label) lines.push(`→ ${label}`)
144
+ }
145
+ if (!originChanged && !protectedSite && openedTabs?.length) {
146
+ const tabs = openedTabs.slice(0, 4).map((tb) => `[${tb.tabId ?? tb.id}] ${short(tb.url, 120)}`)
147
+ if (openedTabs.length > tabs.length) tabs.push(`+${openedTabs.length - tabs.length}`)
148
+ lines.push(t('res.action.tabs', { tabs: tabs.join(' · ') }))
149
+ }
150
+ const notes = []
151
+ if (!protectedSite && !originChanged && result?.occluded) {
152
+ const { tag, text } = result.occluded
153
+ notes.push(t('res.action.occluded', { target: [short(tag, 30), short(text, 80)].filter(Boolean).join(' ') || '—' }))
154
+ }
155
+ if (pendingDialog) {
156
+ notes.push(t('res.action.dialog', { type: short(pendingDialog.type), message: protectedSite || originChanged ? '' : short(pendingDialog.message, 120) }))
157
+ } else if (!protectedSite && !originChanged && liveUpdate) {
158
+ notes.push(t('res.action.live', { text: short(liveUpdate, 120) }))
159
+ }
160
+ if (notes.length) lines.push(notes.join(' · '))
161
+ return lines.length ? '\n' + lines.join('\n') : ''
162
+ }
163
+
164
+ export async function observeResult(tabId, receipt, observe = 'diff', controlEpoch) {
165
+ if (observe === 'none' || blocksObservation(receipt) || !originOf(receipt.url)) return ''
166
+ try {
167
+ const modern = await hasCap('snapshotV2')
168
+ if (!modern && !receipt.legacySafe) return ''
169
+ const epoch = Number.isInteger(controlEpoch) ? controlEpoch : receipt?.controlEpoch
170
+ const opts = {
171
+ autoObserve: true, expectedOrigin: originOf(receipt.url), details: true,
172
+ ...(Number.isInteger(epoch) ? { controlEpoch: epoch } : {}),
44
173
  }
45
- const dialog = result?.pendingDialog ?? info?.pendingDialog
46
- if (dialog) notes.push(t('res.action.dialog', { type: short(dialog.type), message: short(dialog.message, 120) }))
47
- if (Array.isArray(before?.live) && Array.isArray(after?.live)) {
48
- const update = after.live.find((text) => !before.live.includes(text))
49
- if (update) notes.push(t('res.action.live', { text: short(update, 120) }))
174
+ const base = !receipt.navigated && observe === 'diff' && observationBaseline(tabId, receipt.beforeUrl || receipt.url)
175
+ if (base) {
176
+ const change = await snapshot(call, tabId, { ...opts, scope: base.scope, diff: true, maxChars: 2000 })
177
+ if (change.skipped) return ''
178
+ if (change.unchanged && change.incremental) return '\n' + t('res.action.unchanged')
179
+ if (change.incremental && !change.more && change.rows.length) return '\n' + pageContent(change.rows.join('\n'))
180
+ if (!change.incremental && base.scope === 'viewport' && !change.more) return '\n' + pageContent(change.text)
50
181
  }
51
- if (notes.length) lines.push(notes.join(' · '))
52
- return lines.length ? '\n' + lines.join('\n') : ''
53
- } catch {
54
- return ''
182
+ const view = await snapshot(call, tabId, {
183
+ ...opts, scope: observe === 'page' ? 'all' : 'viewport',
184
+ mode: observe === 'page' ? 'page' : 'interactive', maxChars: 2300,
185
+ })
186
+ return view.skipped || !view.text ? '' : '\n' + pageContent(view.text.slice(0, 2500))
187
+ } catch { return '' }
188
+ }
189
+
190
+ const lastReceipts = new Map()
191
+ const receiptKey = (tabId) => {
192
+ try {
193
+ const endpoint = resolveEndpoint()
194
+ return JSON.stringify([endpoint.id || endpoint.socket, tabId])
195
+ } catch { return null }
196
+ }
197
+ export const lastReceipt = (tabId) => lastReceipts.get(receiptKey(tabId))
198
+
199
+ export async function finishAction(tabId, text, { before, result, observe, expect, opened, error, skipObservation } = {}) {
200
+ const store = callInfo.getStore()
201
+ const receipt = await actionReceipt(tabId, before ?? store?.batch?.current, result, { opened })
202
+ const key = receiptKey(tabId)
203
+ if (key && receipt.url) {
204
+ lastReceipts.delete(key)
205
+ lastReceipts.set(key, receipt)
206
+ if (lastReceipts.size > 256) lastReceipts.delete(lastReceipts.keys().next().value)
207
+ }
208
+ let expectMet = result?.expectMet
209
+ if (expect && expectMet === undefined && !error) {
210
+ if (!blocksObservation(receipt)) {
211
+ try {
212
+ const [modernWait, modernAct] = await Promise.all([hasCap('inPageWait'), hasCap('actV1')])
213
+ if (!modernAct) {
214
+ expectMet = false
215
+ } else {
216
+ const epoch = receipt?.controlEpoch ?? before?.controlEpoch
217
+ await waitForCondition(call, tabId, expect, modernWait, {
218
+ ...(Number.isInteger(epoch) ? { controlEpoch: epoch } : {}),
219
+ noReattach: true,
220
+ })
221
+ expectMet = true
222
+ }
223
+ } catch (e) {
224
+ error ??= e
225
+ expectMet = false
226
+ }
227
+ } else {
228
+ expectMet = false
229
+ }
230
+ }
231
+ if (store?.batch) {
232
+ store.batch.receipt = receipt
233
+ store.batch.error = error ?? receipt.error
234
+ store.batch.skipObservation = Boolean(skipObservation)
235
+ if (expectMet === false && !store.batch.error) store.batch.error = new Error(t('res.action.expectUnmet'))
236
+ }
237
+ const note = expectMet === true ? '\n' + t('res.action.expectMet')
238
+ : expectMet === false ? '\n' + t('res.action.expectUnmet') : ''
239
+ return { text: text + receiptText(receipt, result) + note +
240
+ (store?.batch || error || skipObservation ? '' : await observeResult(tabId, receipt, observe)) }
241
+ }
242
+
243
+ export async function performAct(tabId, args) {
244
+ try {
245
+ return await call('act', { tabId, ...args, receipt: true, timeoutMs: actionTimeout(args.expect) - 65_000 }, actionTimeout(args.expect))
246
+ } catch (error) {
247
+ const match = /\bREF_GONE\s+(\d+)\b/.exec(error.message)
248
+ if (!match) throw error
249
+ const ref = Number(match[1])
250
+ const hint = inBatch() ? '' : await staleRefHint(call, tabId, ref).catch(() => '')
251
+ throw new Error(t('err.refGone', { ref }) + hint, { cause: error })
55
252
  }
56
253
  }
package/core/session.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from 'node:path'
2
- import { call, callInfo, setSessionHostGetter } from './transport.js'
3
- import { parseTabRef, resolveHost } from './hosts.js'
2
+ import { call, callInfo, resolveEndpoint, setClosedTabHandler, setSessionHostGetter } from './transport.js'
3
+ import { parseTabRef } from './hosts.js'
4
4
  import { t } from './locale.js'
5
5
 
6
6
  /**
@@ -52,6 +52,7 @@ export function bindCallHost(hostId) {
52
52
  }
53
53
 
54
54
  setSessionHostGetter(getSessionHost)
55
+ setClosedTabHandler((id, hostId) => forgetTab(id, hostId, true))
55
56
 
56
57
  export function rememberTab(id, hostId = null) {
57
58
  const resolvedHost = hostId || callInfo.getStore()?.host || getSessionHost() || null
@@ -63,10 +64,10 @@ export function rememberTab(id, hostId = null) {
63
64
  }
64
65
 
65
66
  /** 标签页关掉了:谁正在用它,谁就忘掉它 */
66
- export function forgetTab(id, hostId = null) {
67
- const targetHost = hostId || callInfo.getStore()?.host || null
67
+ export function forgetTab(id, hostId = null, exactHost = false) {
68
+ const targetHost = hostId || (!exactHost && callInfo.getStore()?.host) || null
68
69
  for (const [key, entry] of currentTab) {
69
- if (entry.value === Number(id) && (!targetHost || !entry.host || entry.host === targetHost)) {
70
+ if (entry.value === Number(id) && (exactHost ? entry.host === targetHost : !targetHost || !entry.host || entry.host === targetHost)) {
70
71
  currentTab.delete(key)
71
72
  }
72
73
  }
@@ -74,15 +75,15 @@ export function forgetTab(id, hostId = null) {
74
75
  }
75
76
 
76
77
  export async function resolveTab(tab, userTab) {
78
+ const batch = callInfo.getStore()?.batch
79
+ if (batch && tab === undefined) return batch.tabId
77
80
  if (tab !== undefined && tab !== null && tab !== '') {
78
81
  const parsed = parseTabRef(tab)
79
82
  const isActive = String(parsed.tab) === 'active'
80
83
  const id = isActive ? null : Number(parsed.tab)
81
84
  if (!isActive && !Number.isInteger(id)) throw new Error(t('err.badTab', { tab }))
82
85
 
83
- const resolved = parsed.host
84
- ? resolveHost({ profile: parsed.host })
85
- : resolveHost({ sessionHost: getSessionHost() })
86
+ const resolved = resolveEndpoint(parsed.host)
86
87
  const hostId = resolved.id || null
87
88
  if (hostId) {
88
89
  bindCallHost(hostId)
@@ -104,12 +105,8 @@ export async function resolveTab(tab, userTab) {
104
105
  const id = entry.value
105
106
  const hostId = entry.host || getSessionHost() || null
106
107
  if (hostId) bindCallHost(hostId)
107
- const exists = (await call('tabs', {}, 60000, false, hostId ? { host: hostId } : {})).some((tb) => tb.id === id)
108
- if (currentTab.get(key) === entry) {
109
- if (exists) rememberTab(id, hostId)
110
- else currentTab.delete(key)
111
- }
112
- if (exists) return id
108
+ rememberTab(id, hostId)
109
+ return id
113
110
  }
114
111
  throw new Error(t('err.noTab'))
115
112
  }
package/core/tooldef.js CHANGED
@@ -63,6 +63,7 @@ export function hintOf(name, a = {}) {
63
63
  ? t('res.hint.typing', { n: String(a.text ?? a.value ?? '').length }) + (a.ref != null || a.selector ? ` → ${el()}` : '')
64
64
  : a.action === 'key' ? t('res.hint.key', { key: a.key || '' })
65
65
  : `${a.action} ${el()}`.trim()
66
+ case 'browser_batch': return t('res.hint.steps', { n: a.steps?.length || 0 })
66
67
  case 'browser_fill': return t('res.hint.fields', { n: a.fields?.length || 0 })
67
68
  case 'browser_nav': return (a.action && a.action !== 'go') ? a.action : short(a.url, 50)
68
69
  case 'browser_screenshot': return [a.mode === 'element' ? t('res.hint.element', { el: el() }) : a.mode || '', a.marks ? 'marks' : ''].filter(Boolean).join(' ')
@@ -95,8 +96,14 @@ export function hintOf(name, a = {}) {
95
96
  }
96
97
 
97
98
  /** 等价于 dsh-tools 的 defineTool(只用它的产出形状,不依赖它) */
99
+ const toolImplementations = new WeakMap()
100
+
101
+ export function executeInScope(tool, args, exec) {
102
+ return toolImplementations.get(tool)(args, exec)
103
+ }
104
+
98
105
  export function defineTool(options) {
99
- return {
106
+ const tool = {
100
107
  name: options.name,
101
108
  description: options.description,
102
109
  parameters: specToJsonSchema(options.parameters),
@@ -116,6 +123,8 @@ export function defineTool(options) {
116
123
  return callInfo.run(info, () => options.execute(args, exec))
117
124
  },
118
125
  }
126
+ toolImplementations.set(tool, options.execute)
127
+ return tool
119
128
  }
120
129
 
121
130
  export const pageContent = (text) => `${t('res.pageUntrusted')}\n${text}`
package/core/transport.js CHANGED
@@ -4,7 +4,7 @@ import path from 'node:path'
4
4
  import crypto from 'node:crypto'
5
5
  import { AsyncLocalStorage } from 'node:async_hooks'
6
6
  import { installHint, assistInstall } from '../setup.js'
7
- import { bridgeDir, resolveHost, tokenLines } from './hosts.js'
7
+ import { bridgeDir, resolveHost } from './hosts.js'
8
8
  import { t } from './locale.js'
9
9
 
10
10
  // socket / token / 日志都在只有当前用户进得去的 /tmp/dsh-bridge-<uid>/(和宿主、cb 同一个约定):
@@ -15,6 +15,13 @@ const WIN = process.platform === 'win32'
15
15
  const UID = typeof process.getuid === 'function' ? process.getuid() : null
16
16
 
17
17
  let sessionHostGetter = null
18
+ let forgetClosedTab = null
19
+ let cachedEndpoint
20
+ const ENDPOINT_TTL_MS = 1000
21
+
22
+ export function setClosedTabHandler(fn) {
23
+ forgetClosedTab = fn
24
+ }
18
25
  export function setSessionHostGetter(fn) {
19
26
  sessionHostGetter = typeof fn === 'function' ? fn : null
20
27
  }
@@ -22,9 +29,22 @@ export function setSessionHostGetter(fn) {
22
29
  // 统一按 host/profile、当前调用上下文(callInfo.host)、会话绑定宿主、最近聚焦宿主或旧单路径解析目标。
23
30
  export function resolveEndpoint(host) {
24
31
  const store = callInfo.getStore()
25
- const explicit = host !== undefined && host !== null && host !== '' ? host : (store?.host || null)
26
- const sessionHost = !explicit && sessionHostGetter ? sessionHostGetter() : null
27
- return resolveHost({ host: explicit, sessionHost })
32
+ const selectedHost = host || store?.host || null
33
+ const explicit = Boolean(selectedHost)
34
+ const sessionHost = !selectedHost && sessionHostGetter ? sessionHostGetter() : null
35
+ const env = JSON.stringify([bridgeDir(), process.env.DSH_BRIDGE_SOCK, process.env.DSH_BRIDGE_TOKEN])
36
+ const route = selectedHost || sessionHost
37
+ if (cachedEndpoint?.env === env && performance.now() < cachedEndpoint.until &&
38
+ cachedEndpoint.explicit === explicit &&
39
+ (cachedEndpoint.route === route || (route !== null && route === cachedEndpoint.endpoint.id))) {
40
+ return cachedEndpoint.endpoint
41
+ }
42
+ cachedEndpoint = undefined
43
+ const endpoint = resolveHost({ host: selectedHost, sessionHost })
44
+ if (typeof route !== 'object' || route === null) {
45
+ cachedEndpoint = { route, explicit, env, endpoint, until: performance.now() + ENDPOINT_TTL_MS }
46
+ }
47
+ return endpoint
28
48
  }
29
49
 
30
50
  /** 宿主起没起:socket 文件在不在;Windows 看 token 文件或注册表里有没有管道名(宿主退出时会删掉) */
@@ -108,6 +128,21 @@ const HINT = () => installHint() + firstAid()
108
128
  */
109
129
  export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {}) {
110
130
  const hint = () => (quiet ? '' : HINT())
131
+ const store = callInfo.getStore()
132
+ if (store?.batch?.tabId === args.tabId && Number.isInteger(store?.batch?.controlEpoch)) {
133
+ args = { ...args, controlEpoch: store.batch.controlEpoch }
134
+ if (op === 'eval') args.requireControl = true
135
+ if (store.batch.stopOnNav && ['act', 'click', 'dragGesture', 'waitCondition', 'networkIdle'].includes(op) &&
136
+ (store.batch.expectedUrlHash || store.batch.expectedDocToken != null || Number.isInteger(store.batch.expectedNavGen))) {
137
+ if (store.batch.expectedUrlHash && args.expectedUrlHash === undefined) args.expectedUrlHash = store.batch.expectedUrlHash
138
+ if (store.batch.expectedDocToken != null && args.expectedDocToken === undefined) {
139
+ args.expectedDocToken = store.batch.expectedDocToken
140
+ }
141
+ if (Number.isInteger(store.batch.expectedNavGen) && args.expectedNavGen === undefined) {
142
+ args.expectedNavGen = store.batch.expectedNavGen
143
+ }
144
+ }
145
+ }
111
146
  return new Promise((resolve, reject) => {
112
147
  let endpoint
113
148
  try {
@@ -115,12 +150,16 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
115
150
  } catch (e) {
116
151
  return reject(e)
117
152
  }
153
+ const fail = (error) => {
154
+ if (cachedEndpoint?.endpoint === endpoint) cachedEndpoint = undefined
155
+ reject(error)
156
+ }
118
157
  const { socket, tokenFile, dir } = endpoint
119
158
  if (!hostUp(endpoint)) {
120
- return reject(new Error(t('err.bridgeDown', { sock: socket || tokenFile || dir, hint: hint() })))
159
+ return fail(new Error(t('err.bridgeDown', { sock: socket || tokenFile || dir, hint: hint() })))
121
160
  }
122
- try { checkDir(WIN ? dir : path.dirname(socket)) } catch (e) { return reject(e) }
123
- const token = endpoint.token || (tokenFile ? tokenLines(tokenFile)[0] : null) || null
161
+ try { checkDir(WIN ? dir : path.dirname(socket)) } catch (e) { return fail(e) }
162
+ const token = endpoint.token || null
124
163
  const id = crypto.randomUUID()
125
164
  const sock = net.connect(socket)
126
165
  let acc = ''
@@ -134,10 +173,9 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
134
173
  fn(v)
135
174
  }
136
175
  sock.setEncoding('utf8')
137
- const store = callInfo.getStore()
138
176
  let client = BASE_CLIENT
139
177
  if (store) {
140
- const { host: _host, ...rest } = store
178
+ const { host: _host, batch: _batch, ...rest } = store
141
179
  client = rest
142
180
  }
143
181
  // timeoutMs 也带给宿主:它按这个等扩展,不再一律 45 秒(等元素、截图这类慢操作以前必定被它掐掉)
@@ -147,23 +185,35 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
147
185
  const i = acc.indexOf('\n')
148
186
  if (i < 0) return
149
187
  let msg
150
- try { msg = JSON.parse(acc.slice(0, i)) } catch { return finish(reject, new Error(t('err.badJson'))) }
188
+ try { msg = JSON.parse(acc.slice(0, i)) } catch { return finish(fail, new Error(t('err.badJson'))) }
151
189
  if (msg.ok) return finish(resolve, msg.result)
152
190
  const message = String(msg.error || t('err.unknownHostError'))
191
+ const tabId = args.tabId ?? args.openerTabId
192
+ if (tabId != null && /No tab with id|tab (?:has been |was |is )?closed|标签页已经不存在|标签页(?:已被|已|被)关闭|вкладка закрыта/i.test(message)) {
193
+ forgetClosedTab?.(tabId, endpoint.id)
194
+ const error = new Error(t('err.noTab'))
195
+ error.code = 'NO_TAB'
196
+ return finish(fail, error)
197
+ }
153
198
  if (message.startsWith('USER_ACTIVE ')) {
154
199
  const error = new Error(t('err.userActive'))
155
200
  error.code = 'USER_ACTIVE'
156
- return finish(reject, error)
201
+ return finish(fail, error)
157
202
  }
158
203
  if (message.startsWith('USER_DENIED_SENSITIVE')) {
159
204
  const error = new Error(t('err.userDeniedSensitive'))
160
205
  error.code = 'USER_DENIED_SENSITIVE'
161
- return finish(reject, error)
206
+ return finish(fail, error)
162
207
  }
163
208
  if (message.startsWith('CONFIRM_LATE')) {
164
209
  const error = new Error(t('err.confirmLate'))
165
210
  error.code = 'CONFIRM_LATE'
166
- return finish(reject, error)
211
+ return finish(fail, error)
212
+ }
213
+ if (message.startsWith('BATCH_NAVIGATED')) {
214
+ const error = new Error(message)
215
+ error.code = 'BATCH_NAVIGATED'
216
+ return finish(fail, error)
167
217
  }
168
218
  const disconnected = /扩展未连接|扩展.{0,12}(?:没装|未装|被停用)|extension.{0,20}(?:not connected|not installed|disabled)/i
169
219
  const hostTimeout = /扩展 (\d+ms) 没回|CDP .+? (\d+) 秒没回应/i.exec(message)
@@ -172,19 +222,19 @@ export function call(op, args = {}, timeoutMs = 65000, quiet = false, opts = {})
172
222
  : message + (disconnected.test(message) ? hint() : '')
173
223
  const failure = new Error(error)
174
224
  if (hostTimeout) failure.code = 'EXTENSION_TIMEOUT'
175
- finish(reject, failure)
225
+ finish(fail, failure)
176
226
  })
177
227
  sock.on('error', (e) => {
178
228
  const message = e.code === 'ECONNREFUSED' ? t('err.staleSocket')
179
229
  : ['ECONNRESET', 'EPIPE'].includes(e.code) ? t('err.closed')
180
230
  : t('err.connect', { message: e.message, hint: hint() })
181
- finish(reject, new Error(message))
231
+ finish(fail, new Error(message))
182
232
  })
183
- sock.on('close', () => finish(reject, new Error(t('err.closed'))))
233
+ sock.on('close', () => finish(fail, new Error(t('err.closed'))))
184
234
  timer = setTimeout(() => {
185
235
  const err = new Error(t('err.timeout', { ms: `${timeoutMs}ms` }))
186
236
  err.code = 'EXTENSION_TIMEOUT'
187
- finish(reject, err)
237
+ finish(fail, err)
188
238
  }, timeoutMs)
189
239
  })
190
240
  }