dsh-chrome-bridge 1.20.0 → 2.0.1

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 (88) hide show
  1. package/README.en.md +6 -2
  2. package/README.md +6 -2
  3. package/client.js +110 -29
  4. package/core/ext.js +119 -0
  5. package/core/hosts.js +277 -0
  6. package/core/locale.js +8 -0
  7. package/core/receipt.js +56 -0
  8. package/core/session.js +157 -0
  9. package/core/shots.js +56 -0
  10. package/core/tooldef.js +142 -0
  11. package/core/transport.js +212 -0
  12. package/core/upload.js +59 -0
  13. package/devtools.js +18 -8
  14. package/download.js +879 -60
  15. package/drag.js +38 -20
  16. package/features/frames.js +58 -0
  17. package/features/gif.js +203 -0
  18. package/features/index.js +1 -0
  19. package/features/mock-har.js +85 -0
  20. package/features/record.js +225 -0
  21. package/i18n/en.js +168 -16
  22. package/i18n/ru.js +168 -16
  23. package/i18n/zh.js +168 -16
  24. package/image-guard.js +13 -6
  25. package/index.js +17 -1155
  26. package/locale/ru.json +7 -0
  27. package/nav.js +43 -5
  28. package/package.json +8 -1
  29. package/panel.js +10 -1
  30. package/refs.js +275 -230
  31. package/setup.js +214 -46
  32. package/tools/click.js +58 -0
  33. package/tools/devtools.js +61 -0
  34. package/tools/dialog.js +22 -0
  35. package/tools/download.js +50 -0
  36. package/tools/drag.js +61 -0
  37. package/tools/eval.js +22 -0
  38. package/tools/fill.js +77 -0
  39. package/tools/handoff.js +40 -0
  40. package/tools/index.js +38 -0
  41. package/tools/input.js +147 -0
  42. package/tools/nav.js +57 -0
  43. package/tools/read.js +87 -0
  44. package/tools/record.js +120 -0
  45. package/tools/screenshot.js +231 -0
  46. package/tools/tabs.js +131 -0
  47. package/tools/wait.js +56 -0
  48. package/vendor/cb +616 -35
  49. package/vendor/extension/_locales/en/messages.json +3 -0
  50. package/vendor/extension/_locales/ru/messages.json +3 -0
  51. package/vendor/extension/_locales/zh_CN/messages.json +3 -0
  52. package/vendor/extension/_locales/zh_TW/messages.json +3 -0
  53. package/vendor/extension/background.js +2 -1969
  54. package/vendor/extension/confirm.css +148 -0
  55. package/vendor/extension/confirm.html +49 -0
  56. package/vendor/extension/confirm.js +188 -0
  57. package/vendor/extension/in-page-cursor.js +599 -0
  58. package/vendor/extension/manifest.json +11 -2
  59. package/vendor/extension/popup.css +99 -5
  60. package/vendor/extension/popup.html +28 -2
  61. package/vendor/extension/popup.js +430 -45
  62. package/vendor/extension/sw/boot.js +111 -0
  63. package/vendor/extension/sw/cdp.js +411 -0
  64. package/vendor/extension/sw/chooser.js +192 -0
  65. package/vendor/extension/sw/confirm.js +608 -0
  66. package/vendor/extension/sw/cursor.js +241 -0
  67. package/vendor/extension/sw/dispatch.js +129 -0
  68. package/vendor/extension/sw/download.js +279 -0
  69. package/vendor/extension/sw/fetch-hub.js +224 -0
  70. package/vendor/extension/sw/frames.js +651 -0
  71. package/vendor/extension/sw/imaging.js +439 -0
  72. package/vendor/extension/sw/native.js +111 -0
  73. package/vendor/extension/sw/net-tools.js +525 -0
  74. package/vendor/extension/sw/ops.js +829 -0
  75. package/vendor/extension/sw/popup-api.js +303 -0
  76. package/vendor/extension/sw/profile.js +166 -0
  77. package/vendor/extension/sw/record.js +494 -0
  78. package/vendor/extension/sw/state.js +161 -0
  79. package/vendor/extension/sw/tabui.js +219 -0
  80. package/vendor/extension/sw/util.js +166 -0
  81. package/vendor/extension/sw/welcome.js +26 -0
  82. package/vendor/extension/sw/windows.js +94 -0
  83. package/vendor/extension/welcome.css +189 -0
  84. package/vendor/extension/welcome.html +70 -0
  85. package/vendor/extension/welcome.js +157 -0
  86. package/vendor/host/host.js +476 -71
  87. package/vendor/in-page-cursor.js +309 -37
  88. package/vendor/skill/SKILL.md +34 -16
package/tools/drag.js ADDED
@@ -0,0 +1,61 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
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'
7
+
8
+ export function buildDrag({ resolveTab, TAB, REF }) {
9
+ return defineTool({
10
+ name: 'browser_drag',
11
+ description: t('tool.drag.desc'),
12
+ parameters: {
13
+ tab: { type: 'string', description: TAB },
14
+ fromRef: { type: 'integer', description: t('tool.drag.fromRef', { ref: REF }) },
15
+ fromSelector: { type: 'string', description: t('tool.drag.fromSelector') },
16
+ fromText: { type: 'string', description: t('tool.drag.fromText') },
17
+ fromX: { type: 'integer', description: t('tool.drag.fromX') },
18
+ fromY: { type: 'integer', description: t('tool.drag.fromY') },
19
+ toRef: { type: 'integer', description: t('tool.drag.toRef') },
20
+ toSelector: { type: 'string', description: t('tool.drag.toSelector') },
21
+ toText: { type: 'string', description: t('tool.drag.toText') },
22
+ toX: { type: 'integer', description: t('tool.drag.toX') },
23
+ toY: { type: 'integer', description: t('tool.drag.toY') },
24
+ steps: { type: 'integer', description: t('tool.drag.steps') },
25
+ },
26
+ output: textOutput,
27
+ presentCall: present('drag', 'browser_drag'),
28
+ async execute(args) {
29
+ const tabId = await resolveTab(args.tab)
30
+ const end = (p) => {
31
+ const ref = args[`${p}Ref`]
32
+ if (ref !== undefined && ref !== null) return { ref: Number(ref) }
33
+ if (args[`${p}Selector`]) return { selector: args[`${p}Selector`] }
34
+ if (args[`${p}Text`]) return { text: args[`${p}Text`] }
35
+ const x = args[`${p}X`]
36
+ const y = args[`${p}Y`]
37
+ if (x !== undefined && x !== null && y !== undefined && y !== null) return { x: Number(x), y: Number(y) }
38
+ throw new Error(t('err.dragNeedsEnd', {
39
+ which: p === 'from' ? t('which.start') : t('which.end'),
40
+ ref: `${p}Ref`, sel: `${p}Selector`, txt: `${p}Text`, xy: `${p}X+${p}Y`,
41
+ }))
42
+ }
43
+ const from = end('from')
44
+ const to = end('to')
45
+ await emulateFocus(tabId)
46
+ for (const target of [from, to]) if (target.ref != null) await locate(call, tabId, target.ref)
47
+ await cursorReady()
48
+ const cursorArgs = withCursor()
49
+ const cursor = hasBuiltinCursor() || cursorArgs.script
50
+ ? {
51
+ 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,
53
+ })).duration,
54
+ down: () => call('cursor', { tabId, action: 'down', ...cursorArgs }),
55
+ up: () => call('cursor', { tabId, action: 'up', ...cursorArgs }),
56
+ }
57
+ : undefined
58
+ return { text: await drag(call, tabId, from, to, { steps: args.steps, cursor }) }
59
+ },
60
+ })
61
+ }
package/tools/eval.js ADDED
@@ -0,0 +1,22 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput, clip } from '../core/tooldef.js'
4
+
5
+ export function buildEval({ resolveTab, TAB }) {
6
+ return defineTool({
7
+ name: 'browser_eval',
8
+ description: t('tool.eval.desc'),
9
+ parameters: {
10
+ expression: { type: 'string', required: true, description: t('tool.eval.expression') },
11
+ tab: { type: 'string', description: TAB },
12
+ },
13
+ output: textOutput,
14
+ presentCall: present('eval', 'browser_eval'),
15
+ async execute(args) {
16
+ const tabId = await resolveTab(args.tab)
17
+ const r = await call('eval', { tabId, expression: args.expression })
18
+ const v = r.value
19
+ return { text: typeof v === 'string' ? clip(v) : clip(JSON.stringify(v, null, 2) ?? 'undefined') }
20
+ },
21
+ })
22
+ }
package/tools/fill.js ADDED
@@ -0,0 +1,77 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput } from '../core/tooldef.js'
4
+ import { recordAction } from '../core/session.js'
5
+ import { cursorReady, emulateFocus, withCursor } from '../core/ext.js'
6
+ import { probeState, actionReceipt } from '../core/receipt.js'
7
+ import { chooserNote } from '../core/upload.js'
8
+ import { locate, setField } from '../refs.js'
9
+
10
+ export function buildFill({ resolveTab, TAB }) {
11
+ return defineTool({
12
+ name: 'browser_fill',
13
+ description: t('tool.fill.desc'),
14
+ parameters: {
15
+ tab: { type: 'string', description: TAB },
16
+ fields: {
17
+ type: 'array', required: true, minItems: 1, maxItems: 30,
18
+ description: t('tool.fill.fields'),
19
+ items: {
20
+ type: 'object', required: ['ref'], additionalProperties: false,
21
+ properties: {
22
+ ref: { type: 'integer', minimum: 1 },
23
+ value: { type: 'string' },
24
+ action: { type: 'string', enum: ['fill', 'select', 'check'], default: 'fill' },
25
+ checked: { type: 'boolean' },
26
+ },
27
+ },
28
+ },
29
+ submitRef: { type: 'integer', minimum: 1, description: t('tool.fill.submitRef') },
30
+ },
31
+ output: textOutput,
32
+ presentCall: present('fill', 'browser_fill'),
33
+ async execute({ tab, fields, submitRef }) {
34
+ const validRef = (ref) => Number.isSafeInteger(ref) && ref > 0
35
+ 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')
37
+ for (const field of fields) {
38
+ const action = fieldAction(field)
39
+ if (!validRef(field?.ref) || !['fill', 'select', 'check'].includes(action) ||
40
+ (action === 'check' ? typeof field.checked !== 'boolean' : typeof field.value !== 'string')) {
41
+ throw new Error(t('err.fillField', { ref: field?.ref ?? '?' }))
42
+ }
43
+ }
44
+ if (submitRef !== undefined && !validRef(submitRef)) throw new Error(t('err.refNotInt', { ref: submitRef }))
45
+
46
+ const tabId = await resolveTab(tab)
47
+ 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 filled = []
53
+ const summary = () => t('res.fill.done', { refs: filled.join(', ') || '—' })
54
+
55
+ for (const field of fields) {
56
+ const { ref, value, checked } = field
57
+ const action = fieldAction(field)
58
+ try {
59
+ await setField(call, tabId, { ref, value, action, checked })
60
+ filled.push(`[${ref}]`)
61
+ } catch (error) {
62
+ return done(summary() + '\n' + t('res.fill.stopped', { ref, reason: error.message }))
63
+ }
64
+ }
65
+ if (submitRef === undefined) return done(summary())
66
+ try {
67
+ const el = await locate(call, tabId, submitRef)
68
+ 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)
72
+ } catch (error) {
73
+ return done(summary() + '\n' + t('res.fill.submitFailed', { ref: submitRef, reason: error.message }))
74
+ }
75
+ },
76
+ })
77
+ }
@@ -0,0 +1,40 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput, short } from '../core/tooldef.js'
4
+ import { requireExtensionOp } from '../nav.js'
5
+
6
+ export function buildHandoff({ resolveTab, TAB }) {
7
+ return defineTool({
8
+ name: 'browser_handoff',
9
+ description: t('tool.handoff.desc'),
10
+ parameters: {
11
+ reason: { type: 'string', required: true, description: t('tool.handoff.reason') },
12
+ tab: { type: 'string', description: TAB },
13
+ timeoutSec: { type: 'integer', minimum: 10, maximum: 600, default: 300, description: t('tool.handoff.timeout') },
14
+ focus: { type: 'boolean', default: true, description: t('tool.handoff.focus') },
15
+ },
16
+ output: textOutput,
17
+ presentCall: present('handoff', 'browser_handoff'),
18
+ async execute(args) {
19
+ if (typeof args.reason !== 'string' || !args.reason.trim()) throw new Error(t('err.handoffReason'))
20
+ const timeoutSec = args.timeoutSec ?? 300
21
+ if (!Number.isInteger(timeoutSec) || timeoutSec < 10 || timeoutSec > 600) throw new Error(t('err.handoffTimeout'))
22
+ const timeoutMs = timeoutSec * 1000
23
+ const tabId = await resolveTab(args.tab)
24
+ let r
25
+ try {
26
+ r = await requireExtensionOp(call, 'handoff', {
27
+ tabId, reason: args.reason, timeoutMs, focus: args.focus !== false,
28
+ }, timeoutMs + 15_000, () => t('err.handoffUpgrade'))
29
+ } catch (error) {
30
+ // The host caps its own deadline at 600 seconds. At that limit it can
31
+ // report the timeout before the extension finishes clearing the handoff.
32
+ if (timeoutSec === 600 && error.code === 'EXTENSION_TIMEOUT') return { text: t('res.handoff.timeout') }
33
+ throw error
34
+ }
35
+ if (!r.done) return { text: r.timedOut ? t('res.handoff.timeout') : t('res.handoff.interrupted') }
36
+ const page = [short(r.title, 100), short(r.url, 250)].filter(Boolean).join(' ') || '—'
37
+ return { text: t('res.handoff.done', { page }) }
38
+ },
39
+ })
40
+ }
package/tools/index.js ADDED
@@ -0,0 +1,38 @@
1
+ import { t } from '../core/locale.js'
2
+ import { buildTabs } from './tabs.js'
3
+ import { buildRead } from './read.js'
4
+ import { buildClick } from './click.js'
5
+ import { buildInput } from './input.js'
6
+ import { buildFill } from './fill.js'
7
+ import { buildNav } from './nav.js'
8
+ import { buildScreenshot } from './screenshot.js'
9
+ import { buildEval } from './eval.js'
10
+ import { buildWait } from './wait.js'
11
+ import { buildDialog } from './dialog.js'
12
+ import { buildDrag } from './drag.js'
13
+ import { buildDownload } from './download.js'
14
+ import { buildHandoff } from './handoff.js'
15
+ import { buildDevtools } from './devtools.js'
16
+ import { buildRecord } from './record.js'
17
+
18
+ export function buildTools(deps) {
19
+ // 好几处参数说明共用这两段,按当前语言取一次。
20
+ const toolDeps = { ...deps, TAB: t('param.tab'), REF: t('param.ref') }
21
+ return [
22
+ buildTabs(toolDeps),
23
+ buildRead(toolDeps),
24
+ buildClick(toolDeps),
25
+ buildInput(toolDeps),
26
+ buildFill(toolDeps),
27
+ buildNav(toolDeps),
28
+ buildScreenshot(toolDeps),
29
+ buildEval(toolDeps),
30
+ buildWait(toolDeps),
31
+ buildDialog(toolDeps),
32
+ buildDrag(toolDeps),
33
+ buildDownload(toolDeps),
34
+ buildHandoff(toolDeps),
35
+ buildDevtools(toolDeps),
36
+ buildRecord(toolDeps),
37
+ ]
38
+ }
package/tools/input.js ADDED
@@ -0,0 +1,147 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput } from '../core/tooldef.js'
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'
7
+ import { chooserNote, uploadable, uploadError } from '../core/upload.js'
8
+ import { locate, focusShadow, selectInPage, setField, scrollElement } from '../refs.js'
9
+
10
+ export function buildInput({ resolveTab, TAB, REF }) {
11
+ return defineTool({
12
+ name: 'browser_input',
13
+ description: t('tool.input.desc'),
14
+ parameters: {
15
+ action: {
16
+ type: 'string', required: true, enum: ['type', 'fill', 'check', 'key', 'select', 'upload', 'focus', 'hover', 'scroll'],
17
+ description: t('tool.input.action'),
18
+ },
19
+ tab: { type: 'string', description: TAB },
20
+ text: { type: 'string', description: t('tool.input.text') },
21
+ ref: { type: 'integer', description: t('tool.input.ref', { ref: REF }) },
22
+ selector: { type: 'string', description: t('tool.input.selector') },
23
+ key: { type: 'string', description: t('tool.input.key') },
24
+ value: { type: 'string', description: t('tool.input.value') },
25
+ checked: { type: 'boolean', description: t('tool.input.checked') },
26
+ files: { type: 'array', items: { type: 'string' }, description: t('tool.input.files') },
27
+ dy: { type: 'integer', description: t('tool.input.dy') },
28
+ dx: { type: 'integer', description: t('tool.input.dx') },
29
+ x: { type: 'integer', description: t('tool.input.x') },
30
+ y: { type: 'integer', description: t('tool.input.y') },
31
+ },
32
+ output: textOutput,
33
+ presentCall: present('input', 'browser_input'),
34
+ async execute(args, exec) {
35
+ const tabId = await resolveTab(args.tab)
36
+ 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
+ // 有编号就先把它换成选择器;shadow DOM / iframe 里的元素换不成,下面各自按坐标/页内处理
42
+ const hasRef = args.ref !== undefined && args.ref !== null &&
43
+ ['type', 'select', 'upload', 'focus', 'hover'].includes(args.action)
44
+ const el = hasRef ? await locate(call, tabId, args.ref) : null
45
+ const selector = el ? el.selector : args.selector
46
+ const target = hasRef ? `[${args.ref}]` : args.selector
47
+ const noShadow = (what) => {
48
+ if (el && el.shadow) throw new Error(t('err.shadowUnsupported', { ref: args.ref, action: what }))
49
+ }
50
+ switch (args.action) {
51
+ 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 })
57
+ }
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)
61
+ }
62
+ case 'fill':
63
+ case 'check': {
64
+ const { ref, action, checked } = args
65
+ const value = args.value ?? args.text
66
+ if (action === 'fill' && value === undefined) throw new Error(t('err.typeNeedsText'))
67
+ if (action === 'check' && typeof checked !== 'boolean') throw new Error(t('err.checkedNeeded'))
68
+ await setField(call, tabId, { action, ref, selector: args.selector, value, checked })
69
+ return done(t('res.input.fieldDone', { target: ref != null ? `[${ref}]` : args.selector || t('res.input.active') }))
70
+ }
71
+ case 'key': {
72
+ if (!args.key) throw new Error(t('err.keyNeedsKey'))
73
+ 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)
75
+ }
76
+ case 'select': {
77
+ if (!selector && !el) throw new Error(t('err.selectNeedsTarget'))
78
+ if (args.value === undefined) throw new Error(t('err.selectNeedsValue'))
79
+ const r = el?.shadow
80
+ ? await selectInPage(call, tabId, args.ref, args.value)
81
+ : await call('select', { tabId, selector, value: args.value })
82
+ return done(t('res.input.selected', { label: r.label, value: r.value }), r)
83
+ }
84
+ case 'upload': {
85
+ if (!args.files?.length) throw new Error(t('err.uploadNeedsFiles'))
86
+ noShadow('upload')
87
+ const files = uploadable(args.files, sessionCwd(exec))
88
+ if (!selector && !el) {
89
+ // 没给目标:塞给本会话刚才点击时拦下的那个选文件框(带着点击回话里的 id 去,扩展核对)
90
+ const key = chooserKey(tabId)
91
+ pruneEntries(chooserIds, CHOOSER_TTL)
92
+ const used = chooserIds.get(key)
93
+ let r
94
+ try { r = await call('upload', { tabId, files, chooserId: used?.value }) } catch (e) { throw uploadError(e, true) }
95
+ if (!r || !r.chooser) throw new Error(t('err.uploadNeedsTarget'))
96
+ // 等回包时这个会话可能又点开了新框(存了新 id):只删这次用掉的
97
+ if (chooserIds.get(key) === used) chooserIds.delete(key)
98
+ return { text: t('res.input.uploadedChooser', { n: r.files.length }) }
99
+ }
100
+ let r
101
+ 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 }) }
103
+ }
104
+ case 'focus': {
105
+ if (!selector && !el) throw new Error(t('err.focusNeedsTarget'))
106
+ if (el && el.shadow) await focusShadow(call, tabId, args.ref)
107
+ else await call('focus', { tabId, selector })
108
+ return { text: t('res.input.focused', { target }) }
109
+ }
110
+ case 'hover': {
111
+ const byPoint = el && el.shadow
112
+ if (!selector && !byPoint && (args.x === undefined || args.y === undefined)) {
113
+ throw new Error(t('err.hoverNeedsTarget'))
114
+ }
115
+ const r = await call('hover', {
116
+ tabId,
117
+ x: byPoint ? el.x : selector ? undefined : Number(args.x),
118
+ y: byPoint ? el.y : selector ? undefined : Number(args.y),
119
+ selector: byPoint ? undefined : selector || undefined,
120
+ ...withCursor(),
121
+ })
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
+ }
127
+ }
128
+ 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
+ }
141
+ }
142
+ default:
143
+ throw new Error(t('err.unknownAction', { action: args.action }))
144
+ }
145
+ },
146
+ })
147
+ }
package/tools/nav.js ADDED
@@ -0,0 +1,57 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput } from '../core/tooldef.js'
4
+ import { recordAction } from '../core/session.js'
5
+ import { probeState, actionReceipt } from '../core/receipt.js'
6
+ import { historyNav } from '../nav.js'
7
+
8
+ export function buildNav({ resolveTab, TAB }) {
9
+ return defineTool({
10
+ name: 'browser_nav',
11
+ description: t('tool.nav.desc'),
12
+ parameters: {
13
+ action: {
14
+ type: 'string', enum: ['go', 'back', 'forward', 'reload'],
15
+ description: t('tool.nav.action'),
16
+ },
17
+ url: { type: 'string', description: t('tool.nav.url') },
18
+ tab: { type: 'string', description: TAB },
19
+ },
20
+ output: textOutput,
21
+ presentCall: present('nav', 'browser_nav'),
22
+ async execute(args) {
23
+ const tabId = await resolveTab(args.tab)
24
+ recordAction(tabId)
25
+ const action = args.action || 'go'
26
+ const before = await probeState(tabId)
27
+ 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
+ }
38
+ }
39
+ const r = await historyNav(call, tabId, action)
40
+ const verb = {
41
+ back: t('res.nav.back'),
42
+ forward: t('res.nav.forward'),
43
+ reload: t('res.nav.reload'),
44
+ }[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),
54
+ }
55
+ },
56
+ })
57
+ }
package/tools/read.js ADDED
@@ -0,0 +1,87 @@
1
+ import { t } from '../core/locale.js'
2
+ import { call } from '../core/transport.js'
3
+ import { defineTool, present, textOutput, clip, pageContent } from '../core/tooldef.js'
4
+ import { snapshot, frameTexts, readStructured } from '../refs.js'
5
+
6
+ export function buildRead({ resolveTab, TAB }) {
7
+ return defineTool({
8
+ name: 'browser_read',
9
+ description: t('tool.read.desc'),
10
+ parameters: {
11
+ what: { type: 'string', required: true, enum: ['snapshot', 'text', 'html', 'markdown', 'table', 'attr', 'info'], description: t('tool.read.what') },
12
+ tab: { type: 'string', description: TAB },
13
+ selector: { type: 'string', description: t('tool.read.selector') },
14
+ name: { type: 'string', description: t('tool.read.name') },
15
+ limit: { type: 'integer', minimum: 1, description: t('tool.read.limit') },
16
+ scope: { type: 'string', enum: ['all', 'viewport'], description: t('tool.read.scope') },
17
+ diff: { type: 'boolean', description: t('tool.read.diff') },
18
+ query: { type: 'string', description: t('tool.read.query') },
19
+ cursor: { type: 'integer', minimum: 0, description: t('tool.read.cursor') },
20
+ },
21
+ output: textOutput,
22
+ presentCall: present('read', 'browser_read'),
23
+ async execute(args) {
24
+ const tabId = await resolveTab(args.tab)
25
+ const limit = Math.max(1, Number(args.limit) || (args.what === 'snapshot' ? 300 : 6000))
26
+ switch (args.what) {
27
+ case 'snapshot': {
28
+ const text = await snapshot(call, tabId, {
29
+ selector: args.selector || undefined,
30
+ scope: args.scope,
31
+ diff: args.diff,
32
+ query: args.query,
33
+ cursor: Math.max(0, Number(args.cursor) || 0),
34
+ limit,
35
+ })
36
+ return { text: pageContent(text) }
37
+ }
38
+ case 'text': {
39
+ const r = await call('text', { tabId, selector: args.selector || undefined, limit })
40
+ let text = r.text || ''
41
+ // 整页读时把同源 iframe 里的字接在后面(innerText 不含框架内容);跨站的给一行提示
42
+ if (!args.selector) {
43
+ for (const f of await frameTexts(call, tabId).catch(() => [])) {
44
+ text += f.cross
45
+ ? t('res.read.iframeCross', { src: f.src })
46
+ : f.text ? `\n\n[iframe] ${f.src}\n${f.text}` : ''
47
+ }
48
+ }
49
+ return { text: pageContent(clip(text.trim(), limit) || t('res.read.noText')) }
50
+ }
51
+ case 'html': {
52
+ const r = await call('html', { tabId, selector: args.selector || 'body', limit })
53
+ return { text: pageContent(clip(r.html, limit)) }
54
+ }
55
+ case 'markdown':
56
+ case 'table': {
57
+ const text = await readStructured(call, tabId, { what: args.what, selector: args.selector, limit })
58
+ return { text: pageContent(clip(text, limit) || t('res.read.noText')) }
59
+ }
60
+ case 'attr': {
61
+ if (!args.selector || !args.name) throw new Error(t('err.attrNeeds'))
62
+ const r = await call('attr', { tabId, selector: args.selector, name: args.name })
63
+ return { text: r.value === null ? t('res.read.noAttr') : String(r.value) }
64
+ }
65
+ case 'info': {
66
+ const r = await call('info', { tabId })
67
+ const v = r.viewport
68
+ ? t('res.read.viewport', {
69
+ w: r.viewport.w,
70
+ h: r.viewport.h,
71
+ scrollYpx: `${r.viewport.scrollY}px`,
72
+ })
73
+ : ''
74
+ const d = r.pendingDialog
75
+ ? t('res.read.dialog', {
76
+ type: r.pendingDialog.type,
77
+ message: r.pendingDialog.message,
78
+ })
79
+ : ''
80
+ return { text: `${r.title}\n${r.url}${v}${d}` }
81
+ }
82
+ default:
83
+ throw new Error(t('err.unknownWhat', { what: args.what }))
84
+ }
85
+ },
86
+ })
87
+ }
@@ -0,0 +1,120 @@
1
+ import { t } from '../core/locale.js'
2
+ import { sessionCwd } from '../core/session.js'
3
+ import { shotRefs } from '../core/shots.js'
4
+ import { call } from '../core/transport.js'
5
+ import { defineTool, present } from '../core/tooldef.js'
6
+ import { downloadsDir, humanSize } from '../download.js'
7
+ import { saveContactPreview, saveRecording } from '../features/record.js'
8
+
9
+ function integer(value, fallback, min, max, errFn) {
10
+ const n = value === undefined || value === null || value === '' ? fallback : Number(value)
11
+ if (!Number.isInteger(n) || n < min || n > max) throw new Error(errFn({ min, max }))
12
+ return n
13
+ }
14
+
15
+ function unknownOp(error, op) {
16
+ return new RegExp('(?:未知操作|unknown (?:operation|op))\\s*[::]\\s*' + op + '\\b', 'i').test(String(error && error.message || error))
17
+ }
18
+
19
+ function mapRecordError(error, op) {
20
+ const message = String(error && error.message || error)
21
+ if (unknownOp(error, op)) return new Error(t('err.recordNeedsExt'))
22
+ if (message.startsWith('RECORD_ACTIVE')) return new Error(t('err.recordActive'))
23
+ if (message.startsWith('RECORD_NOT_STARTED')) return new Error(t('err.recordNotStarted'))
24
+ if (message.startsWith('RECORD_EMPTY')) return new Error(t('err.recordEmpty'))
25
+ return error
26
+ }
27
+
28
+ async function recordCall(op, args, timeoutMs) {
29
+ try {
30
+ return await call(op, args, timeoutMs)
31
+ } catch (error) {
32
+ throw mapRecordError(error, op)
33
+ }
34
+ }
35
+
36
+ export function buildRecord({ resolveTab, getAttachments, TAB, run }) {
37
+ return defineTool({
38
+ name: 'browser_record',
39
+ description: t('tool.record.desc'),
40
+ parameters: {
41
+ action: { type: 'string', required: true, enum: ['start', 'stop', 'clip'], description: t('tool.record.action') },
42
+ tab: { type: 'string', description: TAB },
43
+ durationSec: { type: 'integer', minimum: 1, maximum: 60, description: t('tool.record.durationSec') },
44
+ fps: { type: 'integer', minimum: 1, maximum: 8, description: t('tool.record.fps') },
45
+ maxWidth: { type: 'integer', minimum: 320, maximum: 1280, description: t('tool.record.maxWidth') },
46
+ format: { type: 'string', enum: ['gif', 'mp4', 'webm'], description: t('tool.record.format') },
47
+ to: { type: 'string', enum: ['downloads', 'workdir'], description: t('tool.record.to') },
48
+ filename: { type: 'string', description: t('tool.record.filename') },
49
+ },
50
+ output: {
51
+ schema: {
52
+ type: 'object',
53
+ additionalProperties: false,
54
+ properties: {
55
+ text: { type: 'string' },
56
+ token: { type: 'string' },
57
+ },
58
+ required: ['text', 'token'],
59
+ },
60
+ render: (_args, value) => {
61
+ const blocks = [{ type: 'text', text: value.text }]
62
+ const ref = shotRefs.get(value.token)
63
+ if (ref) {
64
+ shotRefs.delete(value.token)
65
+ blocks.push({ type: 'image', attachment: ref })
66
+ }
67
+ return blocks
68
+ },
69
+ },
70
+ presentCall: present('record', 'browser_record'),
71
+ async execute(args, exec) {
72
+ const action = String(args.action || '')
73
+ if (!['start', 'stop', 'clip'].includes(action)) throw new Error(t('err.unknownAction', { action }))
74
+ const tabId = await resolveTab(args.tab)
75
+ const fps = integer(args.fps, 3, 1, 8, (v) => t('err.recordFps', v))
76
+ const maxWidth = integer(args.maxWidth, 640, 320, 1280, (v) => t('err.recordWidth', v))
77
+ const format = ['mp4', 'webm'].includes(args.format) ? args.format : 'gif'
78
+
79
+ if (action === 'start') {
80
+ const durationSec = integer(args.durationSec, 30, 1, 60, (v) => t('err.recordDuration', v))
81
+ const result = await recordCall('recordStart', {
82
+ tabId, fps, maxWidth, quality: 68, maxDurationMs: durationSec * 1000,
83
+ }, 75000)
84
+ return {
85
+ text: t('res.record.started', { seconds: durationSec, fps: result.fps || fps, width: result.maxWidth || maxWidth }),
86
+ token: '',
87
+ }
88
+ }
89
+
90
+ const durationSec = integer(args.durationSec, 5, 1, 60, (v) => t('err.recordDuration', v))
91
+ const result = action === 'clip'
92
+ ? await recordCall('recordClip', {
93
+ tabId, durationMs: durationSec * 1000, fps, maxWidth, quality: 68, needPixels: true,
94
+ }, durationSec * 1000 + 90000)
95
+ : await recordCall('recordStop', { tabId, needPixels: true, maxWidth }, 90000)
96
+ if (!result || !Array.isArray(result.frames) || !result.frames.length) throw new Error(t('err.recordEmpty'))
97
+
98
+ let dir = downloadsDir()
99
+ if (args.to === 'workdir') {
100
+ dir = sessionCwd(exec)
101
+ if (!dir) throw new Error(t('err.noWorkdir'))
102
+ }
103
+ const saved = await saveRecording(result, { format, fps, dir, filename: args.filename, run })
104
+ const token = await saveContactPreview(result.contactSheet, getAttachments)
105
+ const warning = saved.fallback === 'missing' ? t('res.record.ffmpegMissing')
106
+ : saved.fallback === 'failed' ? t('res.record.ffmpegFailed') : ''
107
+ return {
108
+ text: t('res.record.done', {
109
+ file: saved.file,
110
+ size: humanSize(saved.size),
111
+ format: saved.format,
112
+ count: saved.count,
113
+ seconds: (saved.durationMs / 1000).toFixed(1),
114
+ warning,
115
+ }),
116
+ token,
117
+ }
118
+ },
119
+ })
120
+ }