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.
Files changed (53) hide show
  1. package/README.en.md +1 -1
  2. package/README.md +1 -1
  3. package/core/ext.js +44 -15
  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 +118 -36
  10. package/features/frames.js +5 -2
  11. package/i18n/en.js +37 -7
  12. package/i18n/ru.js +37 -7
  13. package/i18n/zh.js +37 -7
  14. package/nav.js +103 -32
  15. package/package.json +1 -1
  16. package/refs.js +317 -77
  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 +52 -9
  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/screenshot.js +10 -1
  27. package/tools/tabs.js +16 -2
  28. package/tools/wait.js +14 -6
  29. package/vendor/cb +3 -2
  30. package/vendor/extension/in-page-cursor.js +49 -11
  31. package/vendor/extension/manifest.json +1 -1
  32. package/vendor/extension/popup.css +1 -0
  33. package/vendor/extension/popup.html +6 -3
  34. package/vendor/extension/popup.js +19 -13
  35. package/vendor/extension/sw/actions.js +573 -0
  36. package/vendor/extension/sw/boot.js +7 -1
  37. package/vendor/extension/sw/cdp.js +219 -33
  38. package/vendor/extension/sw/conditions.js +176 -0
  39. package/vendor/extension/sw/confirm.js +39 -7
  40. package/vendor/extension/sw/cursor.js +534 -49
  41. package/vendor/extension/sw/dispatch.js +43 -8
  42. package/vendor/extension/sw/frames.js +643 -49
  43. package/vendor/extension/sw/imaging.js +35 -17
  44. package/vendor/extension/sw/lifecycle.js +82 -0
  45. package/vendor/extension/sw/ops.js +1028 -148
  46. package/vendor/extension/sw/page-access.js +292 -0
  47. package/vendor/extension/sw/popup-api.js +42 -10
  48. package/vendor/extension/sw/record.js +22 -5
  49. package/vendor/extension/sw/snapshot.js +251 -0
  50. package/vendor/extension/sw/state.js +24 -5
  51. package/vendor/extension/sw/tabui.js +10 -2
  52. package/vendor/in-page-cursor.js +49 -11
  53. 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 { cursorReady, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
6
- import { probeState, actionReceipt } from '../core/receipt.js'
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 { locate } from '../refs.js'
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
- await cursorReady()
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 count = Number(args.count || 1)
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
- const el = await locate(call, tabId, args.ref, { wantPoint: legacyPoint })
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 r = await call('dialog', { tabId, action: args.action, text: args.text || undefined })
19
- return { text: r.action === 'accept' ? t('res.dialog.accepted') : t('res.dialog.dismissed') }
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,15 +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 { cursorReady, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
5
- import { locate } from '../refs.js'
6
- import { drag } from '../drag.js'
4
+ import { hasCap, emulateFocus, withCursor, hasBuiltinCursor } from '../core/ext.js'
5
+ import { isFrameRef } from '../features/frames.js'
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'
7
9
 
8
10
  export function buildDrag({ resolveTab, TAB, REF }) {
9
11
  return defineTool({
10
12
  name: 'browser_drag',
11
13
  description: t('tool.drag.desc'),
12
14
  parameters: {
15
+ observe: observeParam(),
13
16
  tab: { type: 'string', description: TAB },
14
17
  fromRef: { type: 'integer', description: t('tool.drag.fromRef', { ref: REF }) },
15
18
  fromSelector: { type: 'string', description: t('tool.drag.fromSelector') },
@@ -42,20 +45,60 @@ export function buildDrag({ resolveTab, TAB, REF }) {
42
45
  }
43
46
  const from = end('from')
44
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
+ }
45
71
  await emulateFocus(tabId)
46
- for (const target of [from, to]) if (target.ref != null) await locate(call, tabId, target.ref)
47
- await cursorReady()
72
+ const before = await probeState(tabId)
73
+ for (const target of [from, to]) {
74
+ if (target.ref != null && isFrameRef(target.ref)) {
75
+ const located = await locate(call, tabId, target.ref)
76
+ target.label = `[${target.ref}]`
77
+ target.crossFrame = true
78
+ target.frameId = located.frameId
79
+ target.draggable = Boolean(located.draggable)
80
+ delete target.ref
81
+ target.x = located.x
82
+ target.y = located.y
83
+ }
84
+ }
85
+ if (from.crossFrame && to.crossFrame) {
86
+ throw new Error(t('err.dragCrossFrameUnsupported'))
87
+ }
48
88
  const cursorArgs = withCursor()
49
89
  const cursor = hasBuiltinCursor() || cursorArgs.script
50
90
  ? {
51
91
  move: async (x, y, o = {}) => (await call('cursor', {
52
- tabId, action: 'move', x: Math.round(x), y: Math.round(y), duration: o.duration, straight: o.straight, text: o.label, ...cursorArgs,
92
+ tabId, action: 'move', x: Math.round(x), y: Math.round(y), duration: o.duration, straight: o.straight, text: o.label,
93
+ ...(Number.isInteger(o.controlEpoch) ? { controlEpoch: o.controlEpoch } : {}),
94
+ ...cursorArgs,
53
95
  })).duration,
54
- down: () => call('cursor', { tabId, action: 'down', ...cursorArgs }),
55
- up: () => call('cursor', { tabId, action: 'up', ...cursorArgs }),
96
+ down: (o = {}) => call('cursor', { tabId, action: 'down', ...(Number.isInteger(o.controlEpoch) ? { controlEpoch: o.controlEpoch } : {}), ...cursorArgs }),
97
+ up: (o = {}) => call('cursor', { tabId, action: 'up', ...(Number.isInteger(o.controlEpoch) ? { controlEpoch: o.controlEpoch } : {}), ...cursorArgs }),
56
98
  }
57
99
  : undefined
58
- return { text: await drag(call, tabId, from, to, { steps: args.steps, cursor }) }
100
+ const text = await drag(call, tabId, from, to, { steps: args.steps, cursor })
101
+ return finishAction(tabId, text, { before, observe: args.observe })
59
102
  },
60
103
  })
61
104
  }