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.
- package/README.en.md +1 -1
- package/README.md +1 -1
- package/core/ext.js +8 -1
- 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 +10 -10
- package/features/frames.js +5 -2
- package/i18n/en.js +34 -7
- package/i18n/ru.js +34 -7
- package/i18n/zh.js +34 -7
- package/nav.js +103 -32
- package/package.json +1 -1
- package/refs.js +309 -73
- package/tools/batch.js +311 -0
- package/tools/click.js +37 -11
- package/tools/dialog.js +19 -2
- package/tools/drag.js +31 -5
- 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/tabs.js +16 -2
- package/tools/wait.js +14 -6
- package/vendor/extension/in-page-cursor.js +1 -1
- 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 +2 -1
- package/vendor/extension/sw/cdp.js +139 -11
- package/vendor/extension/sw/conditions.js +176 -0
- package/vendor/extension/sw/confirm.js +39 -7
- package/vendor/extension/sw/cursor.js +176 -14
- package/vendor/extension/sw/dispatch.js +6 -1
- package/vendor/extension/sw/frames.js +543 -47
- package/vendor/extension/sw/lifecycle.js +82 -0
- package/vendor/extension/sw/ops.js +801 -139
- package/vendor/extension/sw/page-access.js +292 -0
- package/vendor/extension/sw/popup-api.js +28 -7
- package/vendor/extension/sw/snapshot.js +251 -0
- package/vendor/extension/sw/state.js +16 -5
- package/vendor/extension/sw/tabui.js +9 -2
- package/vendor/in-page-cursor.js +1 -1
- package/vendor/skill/SKILL.md +8 -7
package/tools/batch.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
import { t } from '../core/locale.js'
|
|
2
|
+
import { hasCap } from '../core/ext.js'
|
|
3
|
+
import { actionReceipt, blocksObservation, observeParam, observeResult, originOf, probeState, validateExpect, validateNavWait } from '../core/receipt.js'
|
|
4
|
+
import { callInfo } from '../core/transport.js'
|
|
5
|
+
import { defineTool, executeInScope, present, short, textOutput, WAIT_MAX_MS } from '../core/tooldef.js'
|
|
6
|
+
import { isFrameRef } from '../features/frames.js'
|
|
7
|
+
|
|
8
|
+
const INPUT_PREFIX = 'browser_input'
|
|
9
|
+
const STEP_FIELDS = {
|
|
10
|
+
click: [['browser_click', 'ref selector text x y count button expect']],
|
|
11
|
+
type: [[INPUT_PREFIX, 'ref selector text clear submit']],
|
|
12
|
+
key: [[INPUT_PREFIX, 'key']],
|
|
13
|
+
select: [[INPUT_PREFIX, 'ref selector value']],
|
|
14
|
+
check: [[INPUT_PREFIX, 'ref selector checked']],
|
|
15
|
+
fill: [['browser_fill', 'fields submitRef expect'], [INPUT_PREFIX, 'ref selector value text']],
|
|
16
|
+
hover: [[INPUT_PREFIX, 'ref selector x y']],
|
|
17
|
+
scroll: [[INPUT_PREFIX, 'ref selector dx dy x y']],
|
|
18
|
+
wait: [['browser_wait', 'selector text url gone network responseUrl newTab timeoutMs']],
|
|
19
|
+
nav: [['browser_nav', 'url wait expect']],
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const validType = (spec, value) => {
|
|
23
|
+
switch (spec.type) {
|
|
24
|
+
case 'integer':
|
|
25
|
+
return Number.isSafeInteger(value) && value >= (spec.minimum ?? -Infinity) && value <= (spec.maximum ?? Infinity)
|
|
26
|
+
case 'string':
|
|
27
|
+
return typeof value === 'string' && (!spec.enum || spec.enum.includes(value))
|
|
28
|
+
case 'boolean':
|
|
29
|
+
return typeof value === 'boolean'
|
|
30
|
+
case 'object':
|
|
31
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
32
|
+
case 'array':
|
|
33
|
+
return Array.isArray(value)
|
|
34
|
+
default:
|
|
35
|
+
return false
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isInlineNavigation(step) {
|
|
40
|
+
if (step?.action !== 'nav' || typeof step.url !== 'string') return false
|
|
41
|
+
try { return ['javascript:', 'data:'].includes(new URL(step.url).protocol) }
|
|
42
|
+
catch { return false }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const validPosRef = (ref) => Number.isSafeInteger(ref) && ref >= 1
|
|
46
|
+
const hasVal = (v) => v !== undefined && v !== null && v !== ''
|
|
47
|
+
const KEY_MODS = new Set(['alt', 'ctrl', 'meta', 'shift'])
|
|
48
|
+
const KEY_NAMES = new Set([
|
|
49
|
+
'enter', 'tab', 'escape', 'esc', 'backspace', 'delete',
|
|
50
|
+
'arrowup', 'arrowdown', 'arrowleft', 'arrowright',
|
|
51
|
+
'home', 'end', 'pageup', 'pagedown', 'space',
|
|
52
|
+
])
|
|
53
|
+
|
|
54
|
+
function isValidKeySpec(spec) {
|
|
55
|
+
if (typeof spec !== 'string') return false
|
|
56
|
+
const parts = spec.split('+').map((s) => s.trim()).filter(Boolean)
|
|
57
|
+
if (!parts.length) return false
|
|
58
|
+
const keyName = parts.pop()
|
|
59
|
+
for (const mod of parts) if (!KEY_MODS.has(mod.toLowerCase())) return false
|
|
60
|
+
return KEY_NAMES.has(keyName.toLowerCase()) || keyName.length === 1
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function validateStepSemantics(step, toolName) {
|
|
64
|
+
if (step.ref !== undefined && !validPosRef(step.ref)) return t('err.refNotInt', { ref: step.ref })
|
|
65
|
+
if (step.expect !== undefined) {
|
|
66
|
+
try { validateExpect(step.expect) } catch (e) { return e.message }
|
|
67
|
+
}
|
|
68
|
+
const hasRef = step.ref != null
|
|
69
|
+
const hasSel = hasVal(step.selector)
|
|
70
|
+
const hasText = hasVal(step.text)
|
|
71
|
+
const hasXY = step.x !== undefined || step.y !== undefined
|
|
72
|
+
const bothXY = step.x !== undefined && step.y !== undefined
|
|
73
|
+
switch (step.action) {
|
|
74
|
+
case 'click': {
|
|
75
|
+
const targets = Number(hasRef) + Number(hasSel) + Number(hasText) + Number(hasXY)
|
|
76
|
+
if (targets !== 1 || (hasXY && !bothXY)) return targets === 0 ? t('err.clickNeeds') : t('err.batchStep')
|
|
77
|
+
if (step.count !== undefined && (!Number.isSafeInteger(step.count) || step.count < 1)) return t('err.batchStep')
|
|
78
|
+
return null
|
|
79
|
+
}
|
|
80
|
+
case 'type':
|
|
81
|
+
if (hasRef && hasSel) return t('err.batchStep')
|
|
82
|
+
return typeof step.text === 'string' ? null : t('err.typeNeedsText')
|
|
83
|
+
case 'key':
|
|
84
|
+
if (!hasVal(step.key)) return t('err.keyNeedsKey')
|
|
85
|
+
return isValidKeySpec(step.key) ? null : t('err.batchStep')
|
|
86
|
+
case 'select':
|
|
87
|
+
if (Number(hasRef) + Number(hasSel) !== 1) return !hasRef && !hasSel ? t('err.selectNeedsTarget') : t('err.batchStep')
|
|
88
|
+
return step.value !== undefined ? null : t('err.selectNeedsValue')
|
|
89
|
+
case 'check':
|
|
90
|
+
if (hasRef && hasSel) return t('err.batchStep')
|
|
91
|
+
return typeof step.checked === 'boolean' ? null : t('err.checkedNeeded')
|
|
92
|
+
case 'fill': {
|
|
93
|
+
if (toolName === 'browser_fill') {
|
|
94
|
+
const { fields, submitRef } = step
|
|
95
|
+
if (!Array.isArray(fields) || fields.length < 1 || fields.length > 30) return t('err.fillCount')
|
|
96
|
+
const allowedKeys = new Set(['ref', 'value', 'action', 'checked'])
|
|
97
|
+
for (const f of fields) {
|
|
98
|
+
if (!f || typeof f !== 'object' || Array.isArray(f) || !Object.keys(f).every((k) => allowedKeys.has(k))) {
|
|
99
|
+
return t('err.fillField', { ref: f?.ref ?? '?' })
|
|
100
|
+
}
|
|
101
|
+
if (f.value !== undefined && typeof f.value !== 'string') return t('err.fillField', { ref: f.ref ?? '?' })
|
|
102
|
+
if (f.checked !== undefined && typeof f.checked !== 'boolean') return t('err.fillField', { ref: f.ref ?? '?' })
|
|
103
|
+
if (f.action !== undefined && (typeof f.action !== 'string' || !['fill', 'select', 'check'].includes(f.action))) {
|
|
104
|
+
return t('err.fillField', { ref: f.ref ?? '?' })
|
|
105
|
+
}
|
|
106
|
+
const act = f.action !== undefined ? f.action : (typeof f.checked === 'boolean' && f.value === undefined ? 'check' : 'fill')
|
|
107
|
+
if (!validPosRef(f.ref) || !['fill', 'select', 'check'].includes(act) ||
|
|
108
|
+
(act === 'check' ? (typeof f.checked !== 'boolean' || f.value !== undefined)
|
|
109
|
+
: (typeof f.value !== 'string' || f.checked !== undefined))) {
|
|
110
|
+
return t('err.fillField', { ref: f.ref ?? '?' })
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (submitRef !== undefined && !validPosRef(submitRef)) return t('err.refNotInt', { ref: submitRef })
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
if (hasRef && hasSel) return t('err.batchStep')
|
|
117
|
+
if (step.value !== undefined && step.text !== undefined) return t('err.batchStep')
|
|
118
|
+
return step.value !== undefined || step.text !== undefined ? null : t('err.typeNeedsText')
|
|
119
|
+
}
|
|
120
|
+
case 'hover': {
|
|
121
|
+
const targets = Number(hasRef) + Number(hasSel) + Number(hasXY)
|
|
122
|
+
if (targets !== 1 || (hasXY && !bothXY)) return targets === 0 ? t('err.hoverNeedsTarget') : t('err.batchStep')
|
|
123
|
+
return null
|
|
124
|
+
}
|
|
125
|
+
case 'scroll': {
|
|
126
|
+
const targets = Number(hasRef) + Number(hasSel) + Number(hasXY)
|
|
127
|
+
if (targets > 1 || (hasXY && !bothXY)) return t('err.batchStep')
|
|
128
|
+
return null
|
|
129
|
+
}
|
|
130
|
+
case 'wait': {
|
|
131
|
+
const extWait = step.network === 'idle' || hasVal(step.responseUrl) || step.newTab === true
|
|
132
|
+
const given = [step.selector, step.text, !step.newTab ? step.url : undefined, step.network, step.responseUrl].filter(hasVal).length +
|
|
133
|
+
Number(step.newTab === true)
|
|
134
|
+
if (given !== 1 || (extWait && step.gone)) return t('err.waitNeedsOne')
|
|
135
|
+
if (step.timeoutMs !== undefined && (!Number.isSafeInteger(step.timeoutMs) || step.timeoutMs < 1 || step.timeoutMs > WAIT_MAX_MS)) {
|
|
136
|
+
return t('err.batchStep')
|
|
137
|
+
}
|
|
138
|
+
return null
|
|
139
|
+
}
|
|
140
|
+
case 'nav': {
|
|
141
|
+
if (typeof step.url !== 'string' || !step.url.trim()) return t('err.navNeedsUrl')
|
|
142
|
+
let parsed
|
|
143
|
+
try { parsed = new URL(step.url) } catch { return t('err.batchStep') }
|
|
144
|
+
if (['javascript:', 'data:', 'chrome-extension:'].includes(parsed.protocol)) return t('err.batchStep')
|
|
145
|
+
if (step.wait !== undefined) {
|
|
146
|
+
try { validateNavWait(step.wait) } catch (e) { return e.message }
|
|
147
|
+
}
|
|
148
|
+
return null
|
|
149
|
+
}
|
|
150
|
+
default:
|
|
151
|
+
return t('err.batchStep')
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function usesFrameRef(step) {
|
|
156
|
+
return isFrameRef(step.ref) || isFrameRef(step.submitRef) ||
|
|
157
|
+
(Array.isArray(step.fields) && step.fields.some((f) => isFrameRef(f?.ref)))
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function buildBatch({ resolveTab, TAB }, tools) {
|
|
161
|
+
const byName = new Map(tools.map((tool) => [tool.name, tool]))
|
|
162
|
+
const stripDesc = (schema) => {
|
|
163
|
+
if (!schema || typeof schema !== 'object') return schema
|
|
164
|
+
const { description: _d, ...rest } = schema
|
|
165
|
+
if (rest.items) rest.items = stripDesc(rest.items)
|
|
166
|
+
if (rest.properties) {
|
|
167
|
+
rest.properties = Object.fromEntries(Object.entries(rest.properties).map(([k, v]) => [k, stripDesc(v)]))
|
|
168
|
+
}
|
|
169
|
+
return rest
|
|
170
|
+
}
|
|
171
|
+
const flatProps = { action: { type: 'string', enum: Object.keys(STEP_FIELDS) } }
|
|
172
|
+
const variants = Object.entries(STEP_FIELDS).flatMap(([action, choices]) => choices.map(([name, fields]) => {
|
|
173
|
+
const tool = byName.get(name)
|
|
174
|
+
const properties = { action: { type: 'string', enum: [action] } }
|
|
175
|
+
for (const field of fields.split(' ')) {
|
|
176
|
+
const clean = stripDesc(tool.parameters.properties[field])
|
|
177
|
+
properties[field] = clean
|
|
178
|
+
if (!(field in flatProps)) flatProps[field] = clean
|
|
179
|
+
}
|
|
180
|
+
const required = name === 'browser_fill' ? ['action', 'fields'] : ['action']
|
|
181
|
+
return { tool, shape: { type: 'object', properties, required, additionalProperties: false } }
|
|
182
|
+
}))
|
|
183
|
+
|
|
184
|
+
return defineTool({
|
|
185
|
+
name: 'browser_batch',
|
|
186
|
+
description: t('tool.batch.desc'),
|
|
187
|
+
parameters: {
|
|
188
|
+
tab: { type: 'string', description: TAB },
|
|
189
|
+
steps: { type: 'array', required: true, minItems: 1, maxItems: 12,
|
|
190
|
+
items: { type: 'object', required: ['action'], properties: flatProps, additionalProperties: false },
|
|
191
|
+
description: t('tool.batch.steps') },
|
|
192
|
+
stopOnNav: { type: 'boolean', default: true, description: t('tool.batch.stopOnNav') },
|
|
193
|
+
observe: observeParam(),
|
|
194
|
+
},
|
|
195
|
+
output: textOutput,
|
|
196
|
+
presentCall: present('batch', 'browser_batch'),
|
|
197
|
+
async execute({ tab, steps, stopOnNav = true, observe = 'diff' }, exec) {
|
|
198
|
+
if (!Array.isArray(steps) || steps.length < 1 || steps.length > 12) throw new Error(t('err.batchCount'))
|
|
199
|
+
if (typeof stopOnNav !== 'boolean' || !observeParam().enum.includes(observe)) throw new Error(t('err.batchOptions'))
|
|
200
|
+
const planned = steps.map((step, index) => {
|
|
201
|
+
const variant = step && !Array.isArray(step) && typeof step === 'object' &&
|
|
202
|
+
variants.find(({ shape }) => shape.required.every((key) => Object.hasOwn(step, key)) &&
|
|
203
|
+
Object.entries(step).every(([key, value]) =>
|
|
204
|
+
Object.hasOwn(shape.properties, key) && validType(shape.properties[key], value)))
|
|
205
|
+
const tool = isInlineNavigation(step) ? undefined : variant?.tool
|
|
206
|
+
const reason = tool ? validateStepSemantics(step, tool.name) : t('err.batchStep')
|
|
207
|
+
return { step, index: index + 1, tool: reason ? undefined : tool, reason }
|
|
208
|
+
})
|
|
209
|
+
const invalid = planned.find(({ tool }) => !tool)
|
|
210
|
+
if (invalid) {
|
|
211
|
+
return { text: t('res.batch.stopped', { step: invalid.index, reason: invalid.reason || t('err.batchStep') }) }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
const tabId = await resolveTab(tab)
|
|
215
|
+
const [modernAct, modernWait] = await Promise.all([hasCap('actV1'), hasCap('inPageWait')])
|
|
216
|
+
const batch = { tabId, stopOnNav }
|
|
217
|
+
const store = callInfo.getStore()
|
|
218
|
+
const lines = []
|
|
219
|
+
let count = 0
|
|
220
|
+
let stopped
|
|
221
|
+
let latest
|
|
222
|
+
let suppressObservation = false
|
|
223
|
+
await callInfo.run({ ...store, batch }, async () => {
|
|
224
|
+
try {
|
|
225
|
+
batch.current = await probeState(tabId, { strict: true })
|
|
226
|
+
if (!Number.isInteger(batch.current?.controlEpoch)) throw new Error(t('err.batchControl'))
|
|
227
|
+
batch.controlEpoch = batch.current.controlEpoch
|
|
228
|
+
if (stopOnNav && batch.current?.documentToken == null) {
|
|
229
|
+
stopped = { step: 1, reason: t('res.batch.unverified') }
|
|
230
|
+
suppressObservation = true
|
|
231
|
+
return
|
|
232
|
+
}
|
|
233
|
+
batch.expectedUrlHash = batch.current?.urlHash
|
|
234
|
+
batch.expectedDocToken = batch.current?.documentToken
|
|
235
|
+
batch.expectedNavGen = batch.current?.navGeneration
|
|
236
|
+
} catch (error) {
|
|
237
|
+
stopped = { step: 1, reason: error.message }
|
|
238
|
+
return
|
|
239
|
+
}
|
|
240
|
+
for (const { step, index, tool } of planned) {
|
|
241
|
+
const { action, ...params } = step
|
|
242
|
+
batch.receipt = null
|
|
243
|
+
batch.error = null
|
|
244
|
+
batch.skipObservation = false
|
|
245
|
+
try {
|
|
246
|
+
const swDocGuarded = action === 'wait'
|
|
247
|
+
? (modernWait && step.newTab !== true)
|
|
248
|
+
: (modernAct && (action === 'click' || !usesFrameRef(step)))
|
|
249
|
+
if (stopOnNav && index > 1 && action !== 'nav' && !swDocGuarded) {
|
|
250
|
+
const now = await probeState(tabId, { strict: true })
|
|
251
|
+
if (!now || now.documentToken == null) {
|
|
252
|
+
stopped = { step: index, reason: t('res.batch.unverified') }
|
|
253
|
+
suppressObservation = true
|
|
254
|
+
break
|
|
255
|
+
}
|
|
256
|
+
if ((batch.expectedUrlHash && now.urlHash && now.urlHash !== batch.expectedUrlHash) ||
|
|
257
|
+
(batch.expectedDocToken != null && now.documentToken !== batch.expectedDocToken) ||
|
|
258
|
+
(Number.isInteger(batch.expectedNavGen) && Number.isInteger(now.navGeneration) && now.navGeneration !== batch.expectedNavGen)) {
|
|
259
|
+
stopped = { step: index, reason: t('res.batch.navigated') }
|
|
260
|
+
suppressObservation = true
|
|
261
|
+
break
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
const args = tool.name === INPUT_PREFIX ? { ...params, action } : params
|
|
265
|
+
if (action === 'nav') args.action = 'go'
|
|
266
|
+
const result = await executeInScope(tool, args, exec)
|
|
267
|
+
latest = batch.receipt || await actionReceipt(tabId, batch.current)
|
|
268
|
+
if (stopOnNav && latest && !latest.pendingDialog && !latest.protectedSite &&
|
|
269
|
+
!latest.navigated && !latest.originChanged) {
|
|
270
|
+
if (latest.documentToken == null) {
|
|
271
|
+
latest = { ...latest, unverified: true }
|
|
272
|
+
} else if ((batch.expectedUrlHash && latest.urlHash && latest.urlHash !== batch.expectedUrlHash) ||
|
|
273
|
+
(batch.expectedDocToken != null && latest.documentToken !== batch.expectedDocToken) ||
|
|
274
|
+
(Number.isInteger(batch.expectedNavGen) && Number.isInteger(latest.navGeneration) && latest.navGeneration !== batch.expectedNavGen)) {
|
|
275
|
+
latest = { ...latest, navigated: true }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
suppressObservation ||= blocksObservation(latest)
|
|
279
|
+
lines.push(`${index}. ${result.text}`)
|
|
280
|
+
if (batch.error || latest.error) throw batch.error || latest.error
|
|
281
|
+
count++
|
|
282
|
+
if (latest.pendingDialog || latest.unverified || latest.protectedSite ||
|
|
283
|
+
stopOnNav && (latest.navigated || latest.originChanged)) {
|
|
284
|
+
const reason = latest.pendingDialog ? t('res.batch.dialog')
|
|
285
|
+
: latest.protectedSite ? t('res.batch.protected')
|
|
286
|
+
: latest.unverified ? t('res.batch.unverified') : t('res.batch.navigated')
|
|
287
|
+
stopped = { step: index, reason }
|
|
288
|
+
break
|
|
289
|
+
}
|
|
290
|
+
if (latest.url) {
|
|
291
|
+
batch.current = { url: latest.url, urlHash: latest.urlHash, title: latest.title, documentToken: latest.documentToken, navGeneration: latest.navGeneration }
|
|
292
|
+
batch.expectedUrlHash = latest.urlHash
|
|
293
|
+
batch.expectedDocToken = latest.documentToken
|
|
294
|
+
batch.expectedNavGen = latest.navGeneration
|
|
295
|
+
}
|
|
296
|
+
} catch (error) {
|
|
297
|
+
const isNav = error.code === 'BATCH_NAVIGATED' || String(error.message || '').startsWith('BATCH_NAVIGATED')
|
|
298
|
+
stopped = { step: index, reason: isNav ? t('res.batch.navigated') : error.message }
|
|
299
|
+
suppressObservation = true
|
|
300
|
+
break
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
})
|
|
304
|
+
if (count) lines.unshift(t('res.batch.completed', { count }))
|
|
305
|
+
if (stopped) lines.push(t('res.batch.stopped', { step: stopped.step, reason: short(stopped.reason, 300) }))
|
|
306
|
+
const observation = !suppressObservation && !batch.skipObservation && latest && originOf(latest.url)
|
|
307
|
+
? await observeResult(tabId, latest, observe, batch.controlEpoch) : ''
|
|
308
|
+
return { text: lines.join('\n') + observation }
|
|
309
|
+
},
|
|
310
|
+
})
|
|
311
|
+
}
|
package/tools/click.js
CHANGED
|
@@ -2,16 +2,19 @@ import { t } from '../core/locale.js'
|
|
|
2
2
|
import { call } from '../core/transport.js'
|
|
3
3
|
import { defineTool, present, textOutput } from '../core/tooldef.js'
|
|
4
4
|
import { recordAction } from '../core/session.js'
|
|
5
|
-
import {
|
|
6
|
-
import { probeState,
|
|
5
|
+
import { hasCap, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
|
|
6
|
+
import { probeState, finishAction, observeParam, expectParam, validateExpect, performAct, inBatch } from '../core/receipt.js'
|
|
7
7
|
import { chooserNote } from '../core/upload.js'
|
|
8
|
-
import {
|
|
8
|
+
import { isFrameRef } from '../features/frames.js'
|
|
9
|
+
import { expectedDocId, locate, staleRefHint } from '../refs.js'
|
|
9
10
|
|
|
10
11
|
export function buildClick({ resolveTab, TAB, REF }) {
|
|
11
12
|
return defineTool({
|
|
12
13
|
name: 'browser_click',
|
|
13
14
|
description: t('tool.click.desc'),
|
|
14
15
|
parameters: {
|
|
16
|
+
observe: observeParam(),
|
|
17
|
+
expect: expectParam(),
|
|
15
18
|
tab: { type: 'string', description: TAB },
|
|
16
19
|
ref: { type: 'integer', description: REF },
|
|
17
20
|
selector: { type: 'string', description: t('tool.click.selector') },
|
|
@@ -24,33 +27,56 @@ export function buildClick({ resolveTab, TAB, REF }) {
|
|
|
24
27
|
output: textOutput,
|
|
25
28
|
presentCall: present('click', 'browser_click'),
|
|
26
29
|
async execute(args) {
|
|
30
|
+
validateExpect(args.expect)
|
|
31
|
+
const count = Number(args.count || 1)
|
|
32
|
+
const { ref, selector, text, x, y, button, expect, observe } = args
|
|
33
|
+
const kind = ref != null ? 'clickRef' : selector ? 'clickEl' : text ? 'clickText'
|
|
34
|
+
: x !== undefined && y !== undefined ? 'click' : null
|
|
35
|
+
if (!kind) throw new Error(t('err.clickNeeds'))
|
|
36
|
+
if (ref != null && (!Number.isInteger(Number(ref)) || Number(ref) < 1)) throw new Error(t('err.refNotInt', { ref }))
|
|
27
37
|
const tabId = await resolveTab(args.tab)
|
|
28
38
|
recordAction(tabId)
|
|
29
|
-
|
|
39
|
+
const done = (text, result, before) => finishAction(tabId, text + chooserNote(result, tabId), { before, result, expect, observe })
|
|
40
|
+
const modernAct = await hasCap('actV1')
|
|
41
|
+
if (modernAct) {
|
|
42
|
+
const actKind = isFrameRef(ref) ? 'clickFrameRef' : kind
|
|
43
|
+
const r = await performAct(tabId, {
|
|
44
|
+
kind: actKind, ref: ref == null ? undefined : Number(ref), expectedDocId: ref == null || isFrameRef(ref) ? undefined : expectedDocId(tabId),
|
|
45
|
+
selector, text, exact: kind === 'clickText' ? false : undefined, x, y, clickCount: count, button, chooser: true, expect,
|
|
46
|
+
})
|
|
47
|
+
if (kind === 'click') return done(t('res.click.atCoords', { x: r.x, y: r.y }), r)
|
|
48
|
+
const details = { ref, tag: r.target?.tag ?? '', text: r.target?.text ?? '', x: r.x, y: r.y, count }
|
|
49
|
+
return done(t(ref == null ? 'res.click.byTag' : count > 1 ? 'res.click.atRefCount' : 'res.click.atRef', details), r)
|
|
50
|
+
}
|
|
30
51
|
await emulateFocus(tabId)
|
|
31
|
-
const
|
|
32
|
-
const options = { tabId, clickCount: count, button: args.button, ...withCursor(), chooser: true }
|
|
52
|
+
const options = { tabId, clickCount: count, button, ...withCursor(), chooser: true }
|
|
33
53
|
const before = await probeState(tabId)
|
|
34
|
-
const done = async (text, r) => ({ text: text + chooserNote(r, tabId) + await actionReceipt(tabId, before, r) })
|
|
35
54
|
if (args.ref != null) {
|
|
36
55
|
const legacyPoint = !hasBuiltinCursor() && (count > 1 || (args.button && args.button !== 'left'))
|
|
37
|
-
|
|
56
|
+
let el
|
|
57
|
+
try { el = await locate(call, tabId, args.ref, { wantPoint: legacyPoint }) }
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (inBatch() || error.code !== 'REF_GONE' && error.message !== t('err.refGone', { ref })) throw error
|
|
60
|
+
const hint = await staleRefHint(call, tabId, Number(args.ref)).catch(() => '')
|
|
61
|
+
if (hint) throw new Error(error.message + hint, { cause: error })
|
|
62
|
+
throw error
|
|
63
|
+
}
|
|
38
64
|
const r = el.selector && !legacyPoint
|
|
39
65
|
? await call('clickEl', { ...options, selector: el.selector })
|
|
40
66
|
: await call('click', { ...options, x: el.x, y: el.y })
|
|
41
67
|
const target = r.target || el
|
|
42
68
|
const details = { ref: args.ref, tag: target.tag, text: target.text, x: r.x, y: r.y, count }
|
|
43
|
-
return done(count > 1 ? t('res.click.atRefCount', details) : t('res.click.atRef', details), r)
|
|
69
|
+
return done(count > 1 ? t('res.click.atRefCount', details) : t('res.click.atRef', details), r, before)
|
|
44
70
|
}
|
|
45
71
|
if (args.selector || args.text) {
|
|
46
72
|
const r = args.selector
|
|
47
73
|
? await call('clickEl', { ...options, selector: args.selector })
|
|
48
74
|
: await call('clickText', { ...options, text: args.text, exact: false })
|
|
49
|
-
return done(t('res.click.byTag', { tag: r.target.tag, text: r.target.text, x: r.x, y: r.y }), r)
|
|
75
|
+
return done(t('res.click.byTag', { tag: r.target.tag, text: r.target.text, x: r.x, y: r.y }), r, before)
|
|
50
76
|
}
|
|
51
77
|
if (args.x !== undefined && args.y !== undefined) {
|
|
52
78
|
const r = await call('click', { ...options, x: Number(args.x), y: Number(args.y) })
|
|
53
|
-
return done(t('res.click.atCoords', { x: r.x, y: r.y }), r)
|
|
79
|
+
return done(t('res.click.atCoords', { x: r.x, y: r.y }), r, before)
|
|
54
80
|
}
|
|
55
81
|
throw new Error(t('err.clickNeeds'))
|
|
56
82
|
},
|
package/tools/dialog.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { t } from '../core/locale.js'
|
|
2
2
|
import { call } from '../core/transport.js'
|
|
3
|
+
import { hasCap } from '../core/ext.js'
|
|
4
|
+
import { finishAction, lastReceipt, observeParam } from '../core/receipt.js'
|
|
3
5
|
import { defineTool, present, textOutput } from '../core/tooldef.js'
|
|
4
6
|
|
|
5
7
|
export function buildDialog({ resolveTab, TAB }) {
|
|
@@ -8,6 +10,7 @@ export function buildDialog({ resolveTab, TAB }) {
|
|
|
8
10
|
description: t('tool.dialog.desc'),
|
|
9
11
|
parameters: {
|
|
10
12
|
action: { type: 'string', required: true, enum: ['accept', 'dismiss'], description: t('tool.dialog.action') },
|
|
13
|
+
observe: observeParam(),
|
|
11
14
|
tab: { type: 'string', description: TAB },
|
|
12
15
|
text: { type: 'string', description: t('tool.dialog.text') },
|
|
13
16
|
},
|
|
@@ -15,8 +18,22 @@ export function buildDialog({ resolveTab, TAB }) {
|
|
|
15
18
|
presentCall: present('dialog', 'browser_dialog'),
|
|
16
19
|
async execute(args) {
|
|
17
20
|
const tabId = await resolveTab(args.tab)
|
|
18
|
-
const
|
|
19
|
-
|
|
21
|
+
const modern = await hasCap('actV1')
|
|
22
|
+
const known = lastReceipt(tabId)
|
|
23
|
+
const before = modern
|
|
24
|
+
? known
|
|
25
|
+
: known?.pendingDialog ? known : (await call('tabs', {}, 1500, true).catch(() => []))
|
|
26
|
+
.find(({ id }) => id === tabId)
|
|
27
|
+
const epochOpt = Number.isInteger(known?.controlEpoch) ? { controlEpoch: known.controlEpoch } : {}
|
|
28
|
+
const r = await call('dialog', {
|
|
29
|
+
tabId, action: args.action, text: args.text || undefined,
|
|
30
|
+
...(modern ? { receipt: true } : {}),
|
|
31
|
+
...epochOpt,
|
|
32
|
+
})
|
|
33
|
+
return finishAction(tabId, r.action === 'accept' ? t('res.dialog.accepted') : t('res.dialog.dismissed'), {
|
|
34
|
+
before: !modern && !Number.isInteger(before?.controlEpoch) ? undefined : before,
|
|
35
|
+
result: r, observe: args.observe,
|
|
36
|
+
})
|
|
20
37
|
},
|
|
21
38
|
})
|
|
22
39
|
}
|
package/tools/drag.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { t } from '../core/locale.js'
|
|
2
2
|
import { call } from '../core/transport.js'
|
|
3
3
|
import { defineTool, present, textOutput } from '../core/tooldef.js'
|
|
4
|
-
import {
|
|
4
|
+
import { hasCap, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
|
|
5
5
|
import { isFrameRef } from '../features/frames.js'
|
|
6
|
-
import { locate } from '../refs.js'
|
|
7
|
-
import {
|
|
6
|
+
import { expectedDocId, locate, staleRefHint } from '../refs.js'
|
|
7
|
+
import { finishAction, observeParam, probeState, inBatch } from '../core/receipt.js'
|
|
8
|
+
import { describeDragEnd, drag } from '../drag.js'
|
|
8
9
|
|
|
9
10
|
export function buildDrag({ resolveTab, TAB, REF }) {
|
|
10
11
|
return defineTool({
|
|
11
12
|
name: 'browser_drag',
|
|
12
13
|
description: t('tool.drag.desc'),
|
|
13
14
|
parameters: {
|
|
15
|
+
observe: observeParam(),
|
|
14
16
|
tab: { type: 'string', description: TAB },
|
|
15
17
|
fromRef: { type: 'integer', description: t('tool.drag.fromRef', { ref: REF }) },
|
|
16
18
|
fromSelector: { type: 'string', description: t('tool.drag.fromSelector') },
|
|
@@ -43,7 +45,31 @@ export function buildDrag({ resolveTab, TAB, REF }) {
|
|
|
43
45
|
}
|
|
44
46
|
const from = end('from')
|
|
45
47
|
const to = end('to')
|
|
48
|
+
if (!isFrameRef(from.ref) && !isFrameRef(to.ref) && await hasCap('swDrag')) {
|
|
49
|
+
let r
|
|
50
|
+
try {
|
|
51
|
+
r = await call('dragGesture', {
|
|
52
|
+
tabId, from, to, steps: args.steps ?? 12, fromSelector: from.selector, toSelector: to.selector,
|
|
53
|
+
expectedDocId: from.ref != null || to.ref != null ? expectedDocId(tabId) : undefined, receipt: true,
|
|
54
|
+
})
|
|
55
|
+
} catch (error) {
|
|
56
|
+
const match = /\bREF_GONE\s+(\d+)\b/.exec(error.message)
|
|
57
|
+
if (!match) throw error
|
|
58
|
+
const refNum = Number(match[1])
|
|
59
|
+
const hint = inBatch() ? '' : await staleRefHint(call, tabId, refNum).catch(() => '')
|
|
60
|
+
throw new Error(t('err.refGone', { ref: refNum }) + hint, { cause: error })
|
|
61
|
+
}
|
|
62
|
+
const ends = { from: describeDragEnd(from), to: describeDragEnd(to) }
|
|
63
|
+
const text = r.html5 || r.native
|
|
64
|
+
? t('res.drag.doneHtml5', { ...ends, verdict: t(r.accepted ? 'res.drag.accepted' : 'res.drag.notAccepted') })
|
|
65
|
+
: t('res.drag.doneCoords', {
|
|
66
|
+
...ends, x1: r.from?.x ?? r.x1 ?? from.x ?? '—', y1: r.from?.y ?? r.y1 ?? from.y ?? '—',
|
|
67
|
+
x2: r.to?.x ?? r.x2 ?? to.x ?? '—', y2: r.to?.y ?? r.y2 ?? to.y ?? '—',
|
|
68
|
+
})
|
|
69
|
+
return finishAction(tabId, text, { result: r, observe: args.observe })
|
|
70
|
+
}
|
|
46
71
|
await emulateFocus(tabId)
|
|
72
|
+
const before = await probeState(tabId)
|
|
47
73
|
for (const target of [from, to]) {
|
|
48
74
|
if (target.ref != null && isFrameRef(target.ref)) {
|
|
49
75
|
const located = await locate(call, tabId, target.ref)
|
|
@@ -59,7 +85,6 @@ export function buildDrag({ resolveTab, TAB, REF }) {
|
|
|
59
85
|
if (from.crossFrame && to.crossFrame) {
|
|
60
86
|
throw new Error(t('err.dragCrossFrameUnsupported'))
|
|
61
87
|
}
|
|
62
|
-
await cursorReady()
|
|
63
88
|
const cursorArgs = withCursor()
|
|
64
89
|
const cursor = hasBuiltinCursor() || cursorArgs.script
|
|
65
90
|
? {
|
|
@@ -72,7 +97,8 @@ export function buildDrag({ resolveTab, TAB, REF }) {
|
|
|
72
97
|
up: (o = {}) => call('cursor', { tabId, action: 'up', ...(Number.isInteger(o.controlEpoch) ? { controlEpoch: o.controlEpoch } : {}), ...cursorArgs }),
|
|
73
98
|
}
|
|
74
99
|
: undefined
|
|
75
|
-
|
|
100
|
+
const text = await drag(call, tabId, from, to, { steps: args.steps, cursor })
|
|
101
|
+
return finishAction(tabId, text, { before, observe: args.observe })
|
|
76
102
|
},
|
|
77
103
|
})
|
|
78
104
|
}
|
package/tools/fill.js
CHANGED
|
@@ -2,16 +2,19 @@ import { t } from '../core/locale.js'
|
|
|
2
2
|
import { call } from '../core/transport.js'
|
|
3
3
|
import { defineTool, present, textOutput } from '../core/tooldef.js'
|
|
4
4
|
import { recordAction } from '../core/session.js'
|
|
5
|
-
import {
|
|
6
|
-
import { probeState,
|
|
5
|
+
import { hasCap, emulateFocus, withCursor } from '../core/ext.js'
|
|
6
|
+
import { probeState, finishAction, observeParam, expectParam, validateExpect, performAct, inBatch } from '../core/receipt.js'
|
|
7
7
|
import { chooserNote } from '../core/upload.js'
|
|
8
|
-
import {
|
|
8
|
+
import { isFrameRef } from '../features/frames.js'
|
|
9
|
+
import { expectedDocId, locate, setField, setFields, staleRefHint } from '../refs.js'
|
|
9
10
|
|
|
10
11
|
export function buildFill({ resolveTab, TAB }) {
|
|
11
12
|
return defineTool({
|
|
12
13
|
name: 'browser_fill',
|
|
13
14
|
description: t('tool.fill.desc'),
|
|
14
15
|
parameters: {
|
|
16
|
+
observe: observeParam(),
|
|
17
|
+
expect: expectParam(),
|
|
15
18
|
tab: { type: 'string', description: TAB },
|
|
16
19
|
fields: {
|
|
17
20
|
type: 'array', required: true, minItems: 1, maxItems: 30,
|
|
@@ -30,13 +33,14 @@ export function buildFill({ resolveTab, TAB }) {
|
|
|
30
33
|
},
|
|
31
34
|
output: textOutput,
|
|
32
35
|
presentCall: present('fill', 'browser_fill'),
|
|
33
|
-
async execute({ tab, fields, submitRef }) {
|
|
36
|
+
async execute({ tab, fields, submitRef, expect, observe }) {
|
|
37
|
+
validateExpect(expect)
|
|
34
38
|
const validRef = (ref) => Number.isSafeInteger(ref) && ref > 0
|
|
35
39
|
if (!Array.isArray(fields) || fields.length < 1 || fields.length > 30) throw new Error(t('err.fillCount'))
|
|
36
|
-
const fieldAction = (f) => f?.action
|
|
40
|
+
const fieldAction = (f) => f?.action !== undefined ? f.action : (typeof f?.checked === 'boolean' && f?.value === undefined ? 'check' : 'fill')
|
|
37
41
|
for (const field of fields) {
|
|
38
42
|
const action = fieldAction(field)
|
|
39
|
-
if (!validRef(field?.ref) || !['fill', 'select', 'check'].includes(action) ||
|
|
43
|
+
if (!validRef(field?.ref) || typeof action !== 'string' || !['fill', 'select', 'check'].includes(action) ||
|
|
40
44
|
(action === 'check' ? typeof field.checked !== 'boolean' : typeof field.value !== 'string')) {
|
|
41
45
|
throw new Error(t('err.fillField', { ref: field?.ref ?? '?' }))
|
|
42
46
|
}
|
|
@@ -45,32 +49,77 @@ export function buildFill({ resolveTab, TAB }) {
|
|
|
45
49
|
|
|
46
50
|
const tabId = await resolveTab(tab)
|
|
47
51
|
recordAction(tabId)
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
const done =
|
|
52
|
+
const normalized = fields.map((field) => ({
|
|
53
|
+
ref: field.ref, action: fieldAction(field), value: field.value, checked: field.checked,
|
|
54
|
+
}))
|
|
55
|
+
const done = (text, result, before, error) => finishAction(tabId, text, { before, result, observe, expect: error ? undefined : expect, error })
|
|
52
56
|
const filled = []
|
|
53
57
|
const summary = () => t('res.fill.done', { refs: filled.join(', ') || '—' })
|
|
58
|
+
if (await hasCap('actV1') && !isFrameRef(submitRef) && normalized.every(({ ref }) => !isFrameRef(ref))) {
|
|
59
|
+
const r = await performAct(tabId, {
|
|
60
|
+
kind: 'fillFields', fields: normalized, submitRef, expectedDocId: expectedDocId(tabId), chooser: submitRef !== undefined, expect,
|
|
61
|
+
})
|
|
62
|
+
const completed = r.filledRefs || r.filled || normalized.map(({ ref }) => ref)
|
|
63
|
+
if (Array.isArray(completed)) filled.push(...completed.map((ref) => `[${ref}]`))
|
|
64
|
+
const failedRef = r.failedRef ?? r.stoppedAt
|
|
65
|
+
let error
|
|
66
|
+
if (failedRef !== undefined) {
|
|
67
|
+
const goneMatch = /\bREF_GONE\s+(\d+)\b/.exec(String(r.reason || ''))
|
|
68
|
+
if (goneMatch) {
|
|
69
|
+
const refNum = Number(goneMatch[1])
|
|
70
|
+
const hint = inBatch() ? '' : await staleRefHint(call, tabId, refNum).catch(() => '')
|
|
71
|
+
error = new Error(t('err.refGone', { ref: refNum }) + hint)
|
|
72
|
+
} else {
|
|
73
|
+
error = new Error(String(r.reason || r.error || t('err.fieldRejected')))
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const note = error
|
|
77
|
+
? (failedRef === submitRef && filled.length === normalized.length
|
|
78
|
+
? t('res.fill.submitFailed', { ref: submitRef, reason: error.message })
|
|
79
|
+
: t('res.fill.stopped', { ref: failedRef, reason: error.message }))
|
|
80
|
+
: submitRef !== undefined ? t('res.fill.submitted', { ref: submitRef }) : ''
|
|
81
|
+
return done(summary() + (note ? '\n' + note : '') + chooserNote(r, tabId), r, undefined, error)
|
|
82
|
+
}
|
|
54
83
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
84
|
+
await emulateFocus(tabId)
|
|
85
|
+
const before = await probeState(tabId)
|
|
86
|
+
const epoch = Number.isInteger(before?.controlEpoch) ? { controlEpoch: before.controlEpoch } : {}
|
|
87
|
+
const guardedCall = (op, args, ...rest) => call(op, { ...args, ...epoch }, ...rest)
|
|
88
|
+
for (let i = 0; i < normalized.length;) {
|
|
89
|
+
const field = normalized[i]
|
|
90
|
+
let failedRef = field.ref
|
|
58
91
|
try {
|
|
59
|
-
|
|
60
|
-
|
|
92
|
+
if (isFrameRef(field.ref)) {
|
|
93
|
+
await setField(guardedCall, tabId, field)
|
|
94
|
+
filled.push(`[${field.ref}]`)
|
|
95
|
+
i++
|
|
96
|
+
continue
|
|
97
|
+
}
|
|
98
|
+
let end = i + 1
|
|
99
|
+
while (end < normalized.length && !isFrameRef(normalized[end].ref)) end++
|
|
100
|
+
const chunk = normalized.slice(i, end)
|
|
101
|
+
const partial = await setFields(guardedCall, tabId, chunk)
|
|
102
|
+
filled.push(...chunk.slice(0, partial.completed).map(({ ref }) => `[${ref}]`))
|
|
103
|
+
if (partial.error) {
|
|
104
|
+
failedRef = chunk[partial.completed].ref
|
|
105
|
+
throw partial.error
|
|
106
|
+
}
|
|
107
|
+
i = end
|
|
61
108
|
} catch (error) {
|
|
62
|
-
|
|
109
|
+
if (error.code === 'NO_TAB') throw error
|
|
110
|
+
return done(summary() + '\n' + t('res.fill.stopped', { ref: failedRef, reason: error.message }), undefined, before, error)
|
|
63
111
|
}
|
|
64
112
|
}
|
|
65
|
-
if (submitRef === undefined) return done(summary())
|
|
113
|
+
if (submitRef === undefined) return done(summary(), undefined, before)
|
|
66
114
|
try {
|
|
67
|
-
const el = await locate(
|
|
115
|
+
const el = await locate(guardedCall, tabId, submitRef)
|
|
68
116
|
const r = el.selector
|
|
69
|
-
? await
|
|
70
|
-
: await
|
|
71
|
-
return done(summary() + '\n' + t('res.fill.submitted', { ref: submitRef }) + chooserNote(r, tabId), r)
|
|
117
|
+
? await guardedCall('clickEl', { tabId, selector: el.selector, ...withCursor(), chooser: true })
|
|
118
|
+
: await guardedCall('click', { tabId, x: el.x, y: el.y, ...withCursor(), chooser: true })
|
|
119
|
+
return done(summary() + '\n' + t('res.fill.submitted', { ref: submitRef }) + chooserNote(r, tabId), r, before)
|
|
72
120
|
} catch (error) {
|
|
73
|
-
|
|
121
|
+
if (error.code === 'NO_TAB') throw error
|
|
122
|
+
return done(summary() + '\n' + t('res.fill.submitFailed', { ref: submitRef, reason: error.message }), undefined, before, error)
|
|
74
123
|
}
|
|
75
124
|
},
|
|
76
125
|
})
|