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/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 { cursorReady, emulateFocus, withCursor } from '../core/ext.js'
6
- import { probeState, actionReceipt } from '../core/receipt.js'
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 { locate, setField } from '../refs.js'
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 ?? (typeof f?.checked === 'boolean' && f?.value === undefined ? 'check' : 'fill')
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
- if (submitRef !== undefined) await cursorReady()
49
- await emulateFocus(tabId)
50
- const before = await probeState(tabId)
51
- const done = async (text, result) => ({ text: text + await actionReceipt(tabId, before, result) })
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
- for (const field of fields) {
56
- const { ref, value, checked } = field
57
- const action = fieldAction(field)
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
- await setField(call, tabId, { ref, value, action, checked })
60
- filled.push(`[${ref}]`)
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
- return done(summary() + '\n' + t('res.fill.stopped', { ref, reason: error.message }))
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(call, tabId, submitRef)
115
+ const el = await locate(guardedCall, tabId, submitRef)
68
116
  const r = el.selector
69
- ? await call('clickEl', { tabId, selector: el.selector, ...withCursor(), chooser: true })
70
- : await call('click', { tabId, x: el.x, y: el.y, ...withCursor(), chooser: true })
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
- return done(summary() + '\n' + t('res.fill.submitFailed', { ref: submitRef, reason: error.message }))
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
  })
package/tools/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { t } from '../core/locale.js'
2
+ import { buildBatch } from './batch.js'
2
3
  import { buildTabs } from './tabs.js'
3
4
  import { buildRead } from './read.js'
4
5
  import { buildClick } from './click.js'
@@ -18,7 +19,7 @@ import { buildRecord } from './record.js'
18
19
  export function buildTools(deps) {
19
20
  // 好几处参数说明共用这两段,按当前语言取一次。
20
21
  const toolDeps = { ...deps, TAB: t('param.tab'), REF: t('param.ref') }
21
- return [
22
+ const tools = [
22
23
  buildTabs(toolDeps),
23
24
  buildRead(toolDeps),
24
25
  buildClick(toolDeps),
@@ -35,4 +36,5 @@ export function buildTools(deps) {
35
36
  buildDevtools(toolDeps),
36
37
  buildRecord(toolDeps),
37
38
  ]
39
+ return [...tools, buildBatch(toolDeps, tools)]
38
40
  }
package/tools/input.js CHANGED
@@ -2,10 +2,11 @@ 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, chooserKey, pruneEntries, chooserIds, CHOOSER_TTL, sessionCwd } from '../core/session.js'
5
- import { cursorReady, emulateFocus, withCursor } from '../core/ext.js'
6
- import { probeState, actionReceipt } from '../core/receipt.js'
5
+ import { hasCap, emulateFocus, withCursor } from '../core/ext.js'
6
+ import { probeState, finishAction, observeParam, performAct, inBatch } from '../core/receipt.js'
7
7
  import { chooserNote, uploadable, uploadError } from '../core/upload.js'
8
- import { locate, focusShadow, selectInPage, setField, scrollElement } from '../refs.js'
8
+ import { isFrameRef } from '../features/frames.js'
9
+ import { expectedDocId, locate, focusShadow, selectInPage, setField, scrollElement, staleRefHint } from '../refs.js'
9
10
 
10
11
  export function buildInput({ resolveTab, TAB, REF }) {
11
12
  return defineTool({
@@ -16,6 +17,9 @@ export function buildInput({ resolveTab, TAB, REF }) {
16
17
  type: 'string', required: true, enum: ['type', 'fill', 'check', 'key', 'select', 'upload', 'focus', 'hover', 'scroll'],
17
18
  description: t('tool.input.action'),
18
19
  },
20
+ observe: observeParam(),
21
+ clear: { type: 'boolean', description: t('tool.input.clear') },
22
+ submit: { type: 'boolean', description: t('tool.input.submit') },
19
23
  tab: { type: 'string', description: TAB },
20
24
  text: { type: 'string', description: t('tool.input.text') },
21
25
  ref: { type: 'integer', description: t('tool.input.ref', { ref: REF }) },
@@ -34,10 +38,73 @@ export function buildInput({ resolveTab, TAB, REF }) {
34
38
  async execute(args, exec) {
35
39
  const tabId = await resolveTab(args.tab)
36
40
  recordAction(tabId)
37
- if (args.action === 'type' || args.action === 'hover') await cursorReady()
38
- if (args.action !== 'scroll') await emulateFocus(tabId)
39
- const before = ['type', 'fill', 'check', 'key', 'select'].includes(args.action) ? await probeState(tabId) : undefined
40
- const done = async (text, result) => ({ text: text + await actionReceipt(tabId, before, result) })
41
+ const { action, ref, observe } = args
42
+ if (action === 'type' && typeof args.text !== 'string') throw new Error(t('err.typeNeedsText'))
43
+ if (action === 'key' && !args.key) throw new Error(t('err.keyNeedsKey'))
44
+ if (action === 'hover' && ref == null && !args.selector && (args.x === undefined || args.y === undefined)) {
45
+ throw new Error(t('err.hoverNeedsTarget'))
46
+ }
47
+ if (['type', 'hover', 'scroll'].includes(action) && ref != null && (!Number.isInteger(Number(ref)) || Number(ref) < 1)) {
48
+ throw new Error(t('err.refNotInt', { ref }))
49
+ }
50
+ const targetLabel = ref != null ? `[${ref}]` : args.selector
51
+ const typed = (r) => t('res.input.typed', { n: r.typed ?? args.text.length }) +
52
+ (targetLabel ? t('res.input.typedAfterFocus', { target: targetLabel }) : '') + chooserNote(r, tabId)
53
+ const hovered = (r) => t('res.input.hovered', { x: r.x, y: r.y }) +
54
+ (r.target ? t('res.input.hoveredEl', { tag: r.target.tag, text: r.target.text }) : '')
55
+ const scrolled = (r) => targetLabel ? t('res.input.scrolledEl', r)
56
+ : t('res.input.scrolled', { dy: `${r.deltaY}px`, scrollY: r.scrollY, pageHeight: r.pageHeight })
57
+ const pressed = (r) => t('res.input.pressedKey', { key: args.key }) + chooserNote(r, tabId)
58
+ if (['type', 'key', 'hover', 'scroll'].includes(action) && !isFrameRef(ref) && await hasCap('actV1')) {
59
+ const hasTarget = action !== 'key'
60
+ const r = await performAct(tabId, {
61
+ kind: action, ref: hasTarget ? ref : undefined, selector: hasTarget ? args.selector : undefined,
62
+ expectedDocId: hasTarget && ref != null ? expectedDocId(tabId) : undefined,
63
+ text: action === 'type' ? args.text : undefined, clear: args.clear, submit: args.submit, key: args.key,
64
+ chooser: action === 'key' || action === 'type' && args.submit === true,
65
+ x: args.x, y: args.y, deltaX: action === 'scroll' ? Number(args.dx || 0) : undefined,
66
+ deltaY: action === 'scroll' ? Number(args.dy ?? 600) : undefined,
67
+ })
68
+ const formats = { type: typed, key: pressed, hover: hovered, scroll: scrolled }
69
+ return finishAction(tabId, formats[action](r), { result: r, observe })
70
+ }
71
+ if (['fill', 'check', 'select'].includes(action) && !isFrameRef(ref) && (ref != null || args.selector || action !== 'select') && await hasCap('actV1')) {
72
+ if (ref != null && (!Number.isInteger(Number(ref)) || Number(ref) < 1)) throw new Error(t('err.refNotInt', { ref }))
73
+ const value = action === 'fill' ? (args.value ?? args.text) : args.value
74
+ if (action === 'fill' && value === undefined) throw new Error(t('err.typeNeedsText'))
75
+ if (action === 'check' && typeof args.checked !== 'boolean') throw new Error(t('err.checkedNeeded'))
76
+ if (action === 'select' && value === undefined) throw new Error(t('err.selectNeedsValue'))
77
+ const field = {
78
+ ...(ref != null ? { ref: Number(ref) } : args.selector ? { selector: args.selector } : { activeElement: true }),
79
+ action,
80
+ ...(action === 'check' ? { checked: args.checked } : { value: String(value) }),
81
+ }
82
+ const r = await performAct(tabId, {
83
+ kind: 'fillFields', fields: [field], expectedDocId: ref != null ? expectedDocId(tabId) : undefined,
84
+ })
85
+ if (r.failedRef !== undefined) {
86
+ if (r.status === 'gone') {
87
+ const hint = inBatch() ? '' : await staleRefHint(call, tabId, Number(ref)).catch(() => '')
88
+ throw new Error(t('err.refGone', { ref: Number(ref) }) + hint)
89
+ }
90
+ if (r.status === 'missing') throw new Error(t('err.noElement', { sel: args.selector || t('res.input.active') }))
91
+ if (r.status === 'disabled') throw new Error(t('err.fieldDisabled'))
92
+ if (action === 'select') {
93
+ const why = r.status === 'noOption' ? t('err.selectNoOption') : t('err.selectNotSelect')
94
+ const options = r.options ? t('err.selectOptions', { options: r.options.join(', ') }) : ''
95
+ throw new Error(t('err.selectFailed', { why, options }))
96
+ }
97
+ if (r.status === 'wrong') throw new Error(t('err.fieldWrong'))
98
+ throw new Error(t('err.fieldRejected'))
99
+ }
100
+ const text = action === 'select'
101
+ ? t('res.input.selected', { label: r.selected?.label ?? '', value: r.selected?.value ?? String(value) })
102
+ : t('res.input.fieldDone', { target: targetLabel || t('res.input.active') })
103
+ return finishAction(tabId, text, { result: r, observe })
104
+ }
105
+ if (action !== 'scroll') await emulateFocus(tabId)
106
+ const before = action === 'upload' && !args.files?.length ? undefined : await probeState(tabId)
107
+ const done = (text, result) => finishAction(tabId, text, { before, result, observe })
41
108
  // 有编号就先把它换成选择器;shadow DOM / iframe 里的元素换不成,下面各自按坐标/页内处理
42
109
  const hasRef = args.ref !== undefined && args.ref !== null &&
43
110
  ['type', 'select', 'upload', 'focus', 'hover'].includes(args.action)
@@ -49,15 +116,22 @@ export function buildInput({ resolveTab, TAB, REF }) {
49
116
  }
50
117
  switch (args.action) {
51
118
  case 'type': {
52
- if (args.text === undefined) throw new Error(t('err.typeNeedsText'))
53
- if (el && el.shadow) {
54
- const clicked = await call('click', { tabId, x: el.x, y: el.y, ...withCursor() })
55
- const r = await call('type', { tabId, text: args.text })
56
- return done(t('res.input.typedAfterClick', { n: r.typed, target }), { ...clicked, ...r })
119
+ const epoch = Number.isInteger(before?.controlEpoch) ? { controlEpoch: before.controlEpoch } : {}
120
+ let clicked
121
+ if (el?.shadow) clicked = await call('click', { tabId, x: el.x, y: el.y, ...withCursor(), ...epoch })
122
+ else if (args.clear && selector) clicked = await call('clickEl', { tabId, selector, ...withCursor(), ...epoch })
123
+ if (args.clear) {
124
+ await call('key', { tabId, key: process.platform === 'darwin' ? 'Meta+a' : 'Ctrl+a', ...epoch })
125
+ await call('key', { tabId, key: 'Backspace', ...epoch })
57
126
  }
58
- const r = await call('type', { tabId, text: args.text, selector: selector || undefined, ...withCursor() })
59
- const text = t('res.input.typed', { n: r.typed }) + (selector ? t('res.input.typedAfterFocus', { target }) : '')
60
- return done(text, r)
127
+ const r = await call('type', {
128
+ tabId, text: args.text, selector: !clicked ? selector || undefined : undefined, ...withCursor(),
129
+ ...(args.clear || args.submit ? epoch : {}),
130
+ })
131
+ const submitted = args.submit ? await call('key', { tabId, key: 'Enter', chooser: true, ...epoch }) : null
132
+ const result = { ...clicked, ...r, ...submitted }
133
+ const text = el?.shadow ? t('res.input.typedAfterClick', { n: r.typed, target }) + chooserNote(result, tabId) : typed(result)
134
+ return done(text, result)
61
135
  }
62
136
  case 'fill':
63
137
  case 'check': {
@@ -71,7 +145,7 @@ export function buildInput({ resolveTab, TAB, REF }) {
71
145
  case 'key': {
72
146
  if (!args.key) throw new Error(t('err.keyNeedsKey'))
73
147
  const r = await call('key', { tabId, key: args.key, chooser: true })
74
- return done(t('res.input.pressedKey', { key: args.key }) + chooserNote(r, tabId), r)
148
+ return done(pressed(r), r)
75
149
  }
76
150
  case 'select': {
77
151
  if (!selector && !el) throw new Error(t('err.selectNeedsTarget'))
@@ -95,17 +169,17 @@ export function buildInput({ resolveTab, TAB, REF }) {
95
169
  if (!r || !r.chooser) throw new Error(t('err.uploadNeedsTarget'))
96
170
  // 等回包时这个会话可能又点开了新框(存了新 id):只删这次用掉的
97
171
  if (chooserIds.get(key) === used) chooserIds.delete(key)
98
- return { text: t('res.input.uploadedChooser', { n: r.files.length }) }
172
+ return done(t('res.input.uploadedChooser', { n: r.files.length }), r)
99
173
  }
100
174
  let r
101
175
  try { r = await call('upload', { tabId, selector, files }) } catch (e) { throw uploadError(e) }
102
- return { text: t('res.input.uploaded', { n: r.files.length, target }) }
176
+ return done(t('res.input.uploaded', { n: r.files.length, target }), r)
103
177
  }
104
178
  case 'focus': {
105
179
  if (!selector && !el) throw new Error(t('err.focusNeedsTarget'))
106
180
  if (el && el.shadow) await focusShadow(call, tabId, args.ref)
107
181
  else await call('focus', { tabId, selector })
108
- return { text: t('res.input.focused', { target }) }
182
+ return done(t('res.input.focused', { target }))
109
183
  }
110
184
  case 'hover': {
111
185
  const byPoint = el && el.shadow
@@ -119,25 +193,12 @@ export function buildInput({ resolveTab, TAB, REF }) {
119
193
  selector: byPoint ? undefined : selector || undefined,
120
194
  ...withCursor(),
121
195
  })
122
- return {
123
- text:
124
- t('res.input.hovered', { x: r.x, y: r.y }) +
125
- (r.target ? t('res.input.hoveredEl', { tag: r.target.tag, text: r.target.text }) : ''),
126
- }
196
+ return done(hovered(r), r)
127
197
  }
128
198
  case 'scroll': {
129
- if (args.ref != null || args.selector) {
130
- const r = await scrollElement(call, tabId, args)
131
- return { text: t('res.input.scrolledEl', r) }
132
- }
133
- const r = await call('scroll', { tabId, deltaY: Number(args.dy ?? 600), deltaX: Number(args.dx || 0) })
134
- return {
135
- text: t('res.input.scrolled', {
136
- dy: `${r.deltaY}px`,
137
- scrollY: r.scrollY,
138
- pageHeight: r.pageHeight,
139
- }),
140
- }
199
+ const r = targetLabel ? await scrollElement(call, tabId, args)
200
+ : await call('scroll', { tabId, deltaY: Number(args.dy ?? 600), deltaX: Number(args.dx || 0) })
201
+ return done(scrolled(r), r)
141
202
  }
142
203
  default:
143
204
  throw new Error(t('err.unknownAction', { action: args.action }))
package/tools/nav.js CHANGED
@@ -2,7 +2,8 @@ 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 { probeState, actionReceipt } from '../core/receipt.js'
5
+ import { hasCap } from '../core/ext.js'
6
+ import { probeState, finishAction, navWaitParam, observeParam, expectParam, validateNavWait, validateExpect, originOf } from '../core/receipt.js'
6
7
  import { historyNav } from '../nav.js'
7
8
 
8
9
  export function buildNav({ resolveTab, TAB }) {
@@ -15,43 +16,65 @@ export function buildNav({ resolveTab, TAB }) {
15
16
  description: t('tool.nav.action'),
16
17
  },
17
18
  url: { type: 'string', description: t('tool.nav.url') },
19
+ observe: observeParam(),
20
+ expect: expectParam(),
21
+ wait: navWaitParam(),
18
22
  tab: { type: 'string', description: TAB },
19
23
  },
20
24
  output: textOutput,
21
25
  presentCall: present('nav', 'browser_nav'),
22
26
  async execute(args) {
27
+ const action = args.action || 'go'
28
+ const { expect, observe } = args
29
+ const wait = validateNavWait(args.wait)
30
+ validateExpect(expect)
31
+ if (!['go', 'back', 'forward', 'reload'].includes(action)) throw new Error(t('err.unknownAction', { action }))
32
+ if (action === 'go' && !args.url) throw new Error(t('err.navNeedsUrl'))
23
33
  const tabId = await resolveTab(args.tab)
24
34
  recordAction(tabId)
25
- const action = args.action || 'go'
26
- const before = await probeState(tabId)
27
35
  if (action === 'go') {
28
- if (!args.url) throw new Error(t('err.navNeedsUrl'))
29
- const r = await call('nav', { tabId, url: args.url, wait: true }, 60000)
30
- const late = r.loaded === false ? t('res.nav.late') : ''
31
- return {
32
- text: t('res.nav.go', {
33
- url: r.url,
34
- title: r.title ? t('res.nav.subtitle', { title: r.title }) : '',
35
- late,
36
- }) + await actionReceipt(tabId, before, r),
37
- }
36
+ const modern = await hasCap('navLifecycle')
37
+ const r = await call('nav', { tabId, url: args.url, wait: modern ? wait : wait !== 'none',
38
+ ...(modern ? { receipt: true } : {}) }, modern ? 95_000 : 60_000)
39
+ const late = wait !== 'none' && r.loaded === false ? t('res.nav.late') : ''
40
+ const url = r.receipt?.url || r.url || args.url
41
+ const originChanged = r.receipt?.originChanged ?? (Boolean(originOf(args.url)) && originOf(args.url) !== originOf(url))
42
+ const privateDestination = r.receipt?.protectedSite || r.protectedSite || originChanged
43
+ const text = t('res.nav.go', {
44
+ url: privateDestination ? originOf(url) || '—' : url,
45
+ title: !privateDestination && r.title ? t('res.nav.subtitle', { title: r.title }) : '',
46
+ late,
47
+ })
48
+ const result = r.receipt
49
+ ? { ...r, receipt: { ...r.receipt, navigated: true } }
50
+ : { ...r, navigated: true }
51
+ return finishAction(tabId, text, { before: { url: args.url }, result, observe, expect, skipObservation: wait === 'none' || r.loaded === false })
38
52
  }
39
- const r = await historyNav(call, tabId, action)
40
53
  const verb = {
41
54
  back: t('res.nav.back'),
42
55
  forward: t('res.nav.forward'),
43
56
  reload: t('res.nav.reload'),
44
57
  }[action]
45
- if (!verb) throw new Error(t('err.unknownAction', { action }))
46
- const late = r.done ? '' : t('res.nav.late')
47
- return {
48
- text: t('res.nav.history', {
49
- verb,
50
- url: r.url,
51
- title: r.title ? t('res.nav.subtitle', { title: r.title }) : '',
52
- late,
53
- }) + await actionReceipt(tabId, before, r),
58
+ const atomicHistory = await hasCap('navLifecycle')
59
+ if (wait === 'none') {
60
+ const r = await historyNav(call, tabId, action, 20000, 'none', { atomic: atomicHistory, requireEpoch: !atomicHistory })
61
+ const text = t('res.nav.history', { verb, url: '—', title: '', late: '' })
62
+ return finishAction(tabId, text, {
63
+ result: { ...r, receipt: { beforeUrl: '', url: '', title: '', navigated: false, unverified: true } },
64
+ observe, expect, skipObservation: true,
65
+ })
54
66
  }
67
+ const before = await probeState(tabId)
68
+ const r = await historyNav(call, tabId, action, 20000, wait, { controlEpoch: before?.controlEpoch, atomic: atomicHistory, requireEpoch: !atomicHistory })
69
+ const late = !r.done ? t('res.nav.late') : ''
70
+ const originChanged = before?.url && originOf(before.url) !== originOf(r.url)
71
+ const text = t('res.nav.history', {
72
+ verb,
73
+ url: originChanged ? originOf(r.url) || '—' : r.url,
74
+ title: !originChanged && r.title ? t('res.nav.subtitle', { title: r.title }) : '',
75
+ late,
76
+ })
77
+ return finishAction(tabId, text, { before, result: { ...r, navigated: r.done }, observe, expect, skipObservation: !r.done })
55
78
  },
56
79
  })
57
80
  }
package/tools/read.js CHANGED
@@ -14,6 +14,7 @@ export function buildRead({ resolveTab, TAB }) {
14
14
  name: { type: 'string', description: t('tool.read.name') },
15
15
  limit: { type: 'integer', minimum: 1, description: t('tool.read.limit') },
16
16
  scope: { type: 'string', enum: ['all', 'viewport'], description: t('tool.read.scope') },
17
+ mode: { type: 'string', enum: ['interactive', 'page'], default: 'interactive', description: t('tool.read.mode') },
17
18
  diff: { type: 'boolean', description: t('tool.read.diff') },
18
19
  query: { type: 'string', description: t('tool.read.query') },
19
20
  cursor: { type: 'integer', minimum: 0, description: t('tool.read.cursor') },
@@ -28,6 +29,7 @@ export function buildRead({ resolveTab, TAB }) {
28
29
  const text = await snapshot(call, tabId, {
29
30
  selector: args.selector || undefined,
30
31
  scope: args.scope,
32
+ mode: args.mode,
31
33
  diff: args.diff,
32
34
  query: args.query,
33
35
  cursor: Math.max(0, Number(args.cursor) || 0),
@@ -106,8 +106,17 @@ async function captureViewportLegacy(call, tabId, encoding, maxWidth) {
106
106
  async function captureElementLegacy(call, tabId, box, encoding, maxWidth) {
107
107
  const dpr = maxWidth > 0 ? await devicePixelRatio(call, tabId) : 1
108
108
  const scale = maxWidth > 0 ? Math.min(1, maxWidth / (Math.max(1, box.width) * dpr)) : 1
109
+ let ox = 0
110
+ let oy = 0
111
+ try {
112
+ const metrics = (await call('cdp', { tabId, method: 'Page.getLayoutMetrics', params: {} }, 5000)).result
113
+ const view = metrics?.cssVisualViewport || metrics?.visualViewport
114
+ ox = Number(view?.pageX) || 0
115
+ oy = Number(view?.pageY) || 0
116
+ } catch {}
117
+ const clip = { ...box, x: box.x + ox, y: box.y + oy, scale }
109
118
  const capture = () => call('cdp', {
110
- tabId, method: 'Page.captureScreenshot', params: { ...encoding, clip: { ...box, scale } },
119
+ tabId, method: 'Page.captureScreenshot', params: { ...encoding, clip },
111
120
  }, 90000)
112
121
  const first = capture()
113
122
  first.catch(() => {})
package/tools/tabs.js CHANGED
@@ -2,6 +2,8 @@ import { t } from '../core/locale.js'
2
2
  import { call } from '../core/transport.js'
3
3
  import { formatTabId, isMultiHost, resolveHost, scanHosts } from '../core/hosts.js'
4
4
  import { defineTool, present, textOutput } from '../core/tooldef.js'
5
+ import { hasCap } from '../core/ext.js'
6
+ import { finishAction, navWaitParam, observeParam, validateNavWait, originOf } from '../core/receipt.js'
5
7
  import { bindCallHost, forgetTab, getSessionHost, getSessionTab, rememberHost, rememberTab } from '../core/session.js'
6
8
 
7
9
  function pickTargetHost(profile) {
@@ -32,6 +34,8 @@ export function buildTabs({ resolveTab, userTab }) {
32
34
  query: { type: 'string', description: t('tool.tabs.query') },
33
35
  url: { type: 'string', description: t('tool.tabs.url') },
34
36
  tab: { type: 'string', description: t('tool.tabs.tab') },
37
+ wait: navWaitParam(),
38
+ observe: observeParam(),
35
39
  profile: { type: 'string', description: t('tool.tabs.profile') },
36
40
  },
37
41
  output: textOutput,
@@ -82,11 +86,21 @@ export function buildTabs({ resolveTab, userTab }) {
82
86
  case 'open': {
83
87
  if (!args.url) throw new Error(t('err.openNeedsUrl'))
84
88
  const target = pickTargetHost(args.profile)
85
- const r = await call('open', { url: args.url }, 65000, false, target.id ? { host: target.id } : {})
89
+ const wait = validateNavWait(args.wait)
90
+ const modern = await hasCap('navLifecycle')
91
+ const r = await call('open', { url: args.url, ...(modern ? { wait, receipt: true } : {}) },
92
+ modern ? 95_000 : 65_000, false, target.id ? { host: target.id } : {})
86
93
  rememberTab(r.tabId, target.id)
87
94
  const where = r.window === 'agent' ? t('res.tabs.agentHint') : t('res.tabs.background')
88
95
  const displayId = formatTabId(r.tabId, target.id, isMultiHost())
89
- return { text: t('res.tabs.opened', { id: displayId, where, url: r.url }) }
96
+ const url = r.receipt?.url || r.url || args.url
97
+ const privateDestination = r.receipt?.protectedSite || r.protectedSite ||
98
+ (r.receipt?.originChanged ?? originOf(url) !== originOf(args.url))
99
+ const text = t('res.tabs.opened', { id: displayId, where, url: privateDestination ? originOf(url) || '—' : url })
100
+ return finishAction(r.tabId, text, {
101
+ before: { url: args.url }, result: r, observe: args.observe, opened: true,
102
+ skipObservation: wait === 'none' || r.loaded === false,
103
+ })
90
104
  }
91
105
  case 'close': {
92
106
  const tabSpec = args.profile && args.tab && !String(args.tab).includes(':')
package/tools/wait.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { t } from '../core/locale.js'
2
- import { call } from '../core/transport.js'
2
+ import { call, callInfo } from '../core/transport.js'
3
3
  import { defineTool, present, textOutput, WAIT_MAX_MS } from '../core/tooldef.js'
4
4
  import { lastActionAt } from '../core/session.js'
5
- import { waitForExtension, waitUntil } from '../nav.js'
5
+ import { hasCap } from '../core/ext.js'
6
+ import { waitForExtension, waitForCondition } from '../nav.js'
6
7
 
7
8
  export function buildWait({ resolveTab, TAB }) {
8
9
  return defineTool({
@@ -29,8 +30,15 @@ export function buildWait({ resolveTab, TAB }) {
29
30
  const given = [args.selector, args.text, !args.newTab ? args.url : undefined, args.network, args.responseUrl].filter(has).length +
30
31
  Number(args.newTab === true)
31
32
  if (given !== 1 || (extensionWait && args.gone)) throw new Error(t('err.waitNeedsOne'))
32
- if (extensionWait) return { text: await waitForExtension(call, tabId, { ...args, timeoutMs, since: lastActionAt.get(tabId) }) }
33
- if (has(args.selector) && !args.gone) {
33
+ const batch = callInfo.getStore()?.batch
34
+ const onReceipt = batch ? (rct) => { if (rct) batch.receipt = rct } : undefined
35
+ const modern = await hasCap('inPageWait')
36
+ if (extensionWait) {
37
+ return { text: await waitForExtension(call, tabId, {
38
+ ...args, timeoutMs, since: lastActionAt.get(tabId), receipt: Boolean(batch && modern), onReceipt,
39
+ }) }
40
+ }
41
+ if (!modern && has(args.selector) && !args.gone) {
34
42
  // 客户端超时 = 确认上限 60 秒 + 执行时限 + 传输余量
35
43
  const r = await call('waitFor', { tabId, selector: args.selector, timeoutMs, visible: true }, timeoutMs + 65_000)
36
44
  return {
@@ -43,13 +51,13 @@ export function buildWait({ resolveTab, TAB }) {
43
51
  }),
44
52
  }
45
53
  }
46
- const text = await waitUntil(call, tabId, {
54
+ const text = await waitForCondition(call, tabId, {
47
55
  selector: has(args.selector) ? args.selector : undefined,
48
56
  text: has(args.text) ? args.text : undefined,
49
57
  url: has(args.url) ? args.url : undefined,
50
58
  gone: !!args.gone,
51
59
  timeoutMs,
52
- })
60
+ }, modern, { receipt: Boolean(batch), onReceipt })
53
61
  return { text }
54
62
  },
55
63
  })
package/vendor/cb CHANGED
@@ -451,7 +451,7 @@ function cursorScript() {
451
451
  }
452
452
 
453
453
  async function cursorArg() {
454
- if (flags['no-cursor']) return {}
454
+ if (flags['no-cursor']) return { noCursor: true }
455
455
  // v1.16.0 起由扩展加载包内的光标,旧版仍需要脚本。
456
456
  const { version } = await call('version', {}, 1200).catch(() => ({}))
457
457
  if (/^\d+(?:\.\d+){2,3}$/.test(version || '')) {
@@ -939,7 +939,7 @@ async function main() {
939
939
  case 'hover': {
940
940
  const [tabSpec, x, y] = rest
941
941
  const tabId = await resolveTab(tabSpec)
942
- const r = await call('hover', { tabId, x: Number(x), y: Number(y), selector: flags.sel || undefined })
942
+ const r = await call('hover', { tabId, x: Number(x), y: Number(y), selector: flags.sel || undefined, ...await cursorArg() })
943
943
  out(`悬停到 (${r.x}, ${r.y})${r.target ? ` ${r.target.tag}「${r.target.text}」` : ''}`, r)
944
944
  return
945
945
  }
@@ -948,6 +948,7 @@ async function main() {
948
948
  const r = await call('scroll', {
949
949
  tabId, x: Number(flags.x || 200), y: Number(flags.y || 200),
950
950
  deltaY: Number(flags.dy || 600), deltaX: Number(flags.dx || 0),
951
+ ...(flags['no-cursor'] ? { noCursor: true } : {}),
951
952
  })
952
953
  out(`滚了 ${r.deltaY}px,现在 scrollY=${r.scrollY} / 页高 ${r.pageHeight}`, r)
953
954
  return