dsh-chrome-bridge 2.0.2 → 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.
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/core/ext.js +44 -15
- package/core/hosts.js +3 -4
- package/core/receipt.js +228 -31
- package/core/session.js +11 -14
- package/core/tooldef.js +10 -1
- package/core/transport.js +67 -17
- package/drag.js +118 -36
- package/features/frames.js +5 -2
- package/i18n/en.js +37 -7
- package/i18n/ru.js +37 -7
- package/i18n/zh.js +37 -7
- package/nav.js +103 -32
- package/package.json +1 -1
- package/refs.js +317 -77
- package/tools/batch.js +311 -0
- package/tools/click.js +37 -11
- package/tools/dialog.js +19 -2
- package/tools/drag.js +52 -9
- package/tools/fill.js +71 -22
- package/tools/index.js +3 -1
- package/tools/input.js +97 -36
- package/tools/nav.js +46 -23
- package/tools/read.js +2 -0
- package/tools/screenshot.js +10 -1
- package/tools/tabs.js +16 -2
- package/tools/wait.js +14 -6
- package/vendor/cb +3 -2
- package/vendor/extension/in-page-cursor.js +49 -11
- package/vendor/extension/manifest.json +1 -1
- package/vendor/extension/popup.css +1 -0
- package/vendor/extension/popup.html +6 -3
- package/vendor/extension/popup.js +19 -13
- package/vendor/extension/sw/actions.js +573 -0
- package/vendor/extension/sw/boot.js +7 -1
- package/vendor/extension/sw/cdp.js +219 -33
- package/vendor/extension/sw/conditions.js +176 -0
- package/vendor/extension/sw/confirm.js +39 -7
- package/vendor/extension/sw/cursor.js +534 -49
- package/vendor/extension/sw/dispatch.js +43 -8
- package/vendor/extension/sw/frames.js +643 -49
- package/vendor/extension/sw/imaging.js +35 -17
- package/vendor/extension/sw/lifecycle.js +82 -0
- package/vendor/extension/sw/ops.js +1028 -148
- package/vendor/extension/sw/page-access.js +292 -0
- package/vendor/extension/sw/popup-api.js +42 -10
- package/vendor/extension/sw/record.js +22 -5
- package/vendor/extension/sw/snapshot.js +251 -0
- package/vendor/extension/sw/state.js +24 -5
- package/vendor/extension/sw/tabui.js +10 -2
- package/vendor/in-page-cursor.js +49 -11
- 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
|
|
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
|
-
- 自带
|
|
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
|
@@ -3,7 +3,7 @@ import os from 'node:os'
|
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
import { paths, extensionId } from '../setup.js'
|
|
6
|
-
import { call, hostUp, nudgeLegacyHost, trace } from './transport.js'
|
|
6
|
+
import { call, hostUp, nudgeLegacyHost, resolveEndpoint, trace } from './transport.js'
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* 后台标签页(或者 Chrome 窗口被别的窗口挡住)时页面是 hidden,CDP 发的鼠标/键盘事件
|
|
@@ -17,6 +17,8 @@ const FATAL_CODES = new Set(['USER_ACTIVE', 'USER_DENIED_SENSITIVE', 'CONFIRM_LA
|
|
|
17
17
|
const FATAL_TEXT = /超时|timed out|closed|关掉|ECONNREFUSED|ECONNRESET|EPIPE|not connected|未连接|没在跑|not running|连不上|cannot reach|已退出|refused|истекло время|закрыто|не запущен|не удаётся подключиться|отклонил/i
|
|
18
18
|
|
|
19
19
|
export async function emulateFocus(tabId) {
|
|
20
|
+
await cursorReady()
|
|
21
|
+
if (hasBuiltinCursor()) return
|
|
20
22
|
try {
|
|
21
23
|
await call('cdp', { tabId, method: 'Emulation.setFocusEmulationEnabled', params: { enabled: true } })
|
|
22
24
|
} catch (e) {
|
|
@@ -34,21 +36,44 @@ export async function emulateFocus(tabId) {
|
|
|
34
36
|
* 只管解压版(ID 和 ~/dsh-bridge-extension 推导出来的一致)。商店版的代码由商店自己更新,
|
|
35
37
|
* reload 只会白白掐断宿主一下;而商店版本号常常落后本地,不跳过就会每次启动都重载。
|
|
36
38
|
*/
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
39
|
+
const hostVersions = new Map()
|
|
40
|
+
function currentHostKey() {
|
|
41
|
+
try {
|
|
42
|
+
const ep = resolveEndpoint()
|
|
43
|
+
return ep?.socket || ep?.tokenFile || ep?.dir || 'default'
|
|
44
|
+
} catch {
|
|
45
|
+
return 'default'
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function hostEntry(key = currentHostKey()) {
|
|
49
|
+
let entry = hostVersions.get(key)
|
|
50
|
+
if (!entry) {
|
|
51
|
+
entry = { version: undefined, caps: undefined, probe: undefined, lastProbe: 0 }
|
|
52
|
+
hostVersions.set(key, entry)
|
|
53
|
+
if (hostVersions.size > 32) hostVersions.delete(hostVersions.keys().next().value)
|
|
54
|
+
}
|
|
55
|
+
return entry
|
|
56
|
+
}
|
|
40
57
|
function checkExtensionVersion() {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
58
|
+
const key = currentHostKey()
|
|
59
|
+
const entry = hostEntry(key)
|
|
60
|
+
if (entry.probe) return entry.probe
|
|
61
|
+
entry.lastProbe = Date.now()
|
|
62
|
+
entry.probe = call('version', {}, 1200, true).then((r) => {
|
|
63
|
+
entry.version = r?.version
|
|
64
|
+
entry.caps = r?.caps
|
|
45
65
|
return r || {}
|
|
46
|
-
}).catch(() => ({})).finally(() => {
|
|
47
|
-
return
|
|
66
|
+
}).catch(() => ({})).finally(() => { entry.probe = undefined })
|
|
67
|
+
return entry.probe
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function hasCap(name) {
|
|
71
|
+
await cursorReady()
|
|
72
|
+
return hostVersions.get(currentHostKey())?.caps?.[name] === true
|
|
48
73
|
}
|
|
49
74
|
|
|
50
75
|
export function getExtVersion() {
|
|
51
|
-
return
|
|
76
|
+
return hostVersions.get(currentHostKey())?.version
|
|
52
77
|
}
|
|
53
78
|
|
|
54
79
|
export function isExtAtLeast(requiredMajor, requiredMinor, requiredPatch = 0, requiredBuild = 0) {
|
|
@@ -64,8 +89,9 @@ export function isExtAtLeast(requiredMajor, requiredMinor, requiredPatch = 0, re
|
|
|
64
89
|
export const hasBuiltinCursor = () => isExtAtLeast(1, 16)
|
|
65
90
|
|
|
66
91
|
export async function cursorReady() {
|
|
67
|
-
|
|
68
|
-
|
|
92
|
+
const entry = hostEntry()
|
|
93
|
+
if (entry.probe) await entry.probe
|
|
94
|
+
else if (!entry.version && Date.now() - entry.lastProbe > 2000) await checkExtensionVersion()
|
|
69
95
|
}
|
|
70
96
|
|
|
71
97
|
export async function refreshExtension() {
|
|
@@ -73,6 +99,8 @@ export async function refreshExtension() {
|
|
|
73
99
|
if (!process.env.DSH_BRIDGE_SOCK) nudgeLegacyHost()
|
|
74
100
|
return
|
|
75
101
|
}
|
|
102
|
+
const key = currentHostKey()
|
|
103
|
+
const entry = hostEntry(key)
|
|
76
104
|
const { version, id } = await checkExtensionVersion()
|
|
77
105
|
if (!version) return
|
|
78
106
|
let want, localId
|
|
@@ -90,8 +118,9 @@ export async function refreshExtension() {
|
|
|
90
118
|
}
|
|
91
119
|
if (version === want) return
|
|
92
120
|
await call('reload', {}, 5000)
|
|
93
|
-
|
|
94
|
-
|
|
121
|
+
entry.version = undefined
|
|
122
|
+
entry.caps = undefined
|
|
123
|
+
entry.lastProbe = 0
|
|
95
124
|
trace(`扩展 ${version} → ${want}:已让它重载`)
|
|
96
125
|
} catch (e) {
|
|
97
126
|
trace(`检查扩展版本失败(忽略): ${e && e.message}`)
|
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 {
|
|
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
|
|
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
|
-
|
|
21
|
-
|
|
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
|
-
|
|
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
|
-
|
|
27
|
-
|
|
28
|
-
call('
|
|
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
|
-
|
|
31
|
-
const
|
|
32
|
-
if (
|
|
33
|
-
|
|
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
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
|
46
|
-
if (
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
if (
|
|
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
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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
|
|
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
|
-
|
|
108
|
-
|
|
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
|
-
|
|
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}`
|