dsh-builtin-browser 0.5.6 → 0.5.7

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 (63) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/README.en.md +67 -99
  3. package/README.md +67 -100
  4. package/client.js +381 -322
  5. package/desktop-bridge/install.mjs +122 -33
  6. package/desktop-bridge/plugin-browser-bridge.js +9 -4
  7. package/docs/tool-reference.md +20 -1
  8. package/lib/browser/runtime.d.ts +3 -1
  9. package/lib/browser/runtime.js +9 -0
  10. package/lib/browser/types.d.ts +42 -0
  11. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  12. package/lib/browser-electron/authenticated-route.js +39 -0
  13. package/lib/browser-electron/bridge-endpoint.js +7 -0
  14. package/lib/browser-electron/bridge-install.d.ts +48 -0
  15. package/lib/browser-electron/bridge-install.js +98 -0
  16. package/lib/browser-electron/bridge-status.js +21 -2
  17. package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
  18. package/lib/browser-electron/desktop-bridge-host.js +36 -15
  19. package/lib/browser-electron/electron-provision.d.ts +1 -1
  20. package/lib/browser-electron/electron-provision.js +31 -11
  21. package/lib/browser-electron/entry.js +84 -8
  22. package/lib/browser-electron/host-main.js +48 -27
  23. package/lib/browser-electron/provider.d.ts +9 -2
  24. package/lib/browser-electron/provider.js +76 -6
  25. package/lib/browser-electron/remote-host.js +4 -4
  26. package/lib/browser-electron/runtime-route.d.ts +3 -5
  27. package/lib/browser-electron/runtime-status.js +4 -2
  28. package/lib/browser-electron/settings-route.d.ts +5 -18
  29. package/lib/browser-electron/settings-route.js +4 -14
  30. package/lib/browser-electron/settings-store.d.ts +17 -0
  31. package/lib/browser-electron/settings-store.js +24 -0
  32. package/lib/browser-electron/system-browser.d.ts +5 -2
  33. package/lib/browser-electron/system-browser.js +12 -4
  34. package/lib/tool-browser/index.js +1041 -4
  35. package/lib/tool-browser/page-probe.d.ts +86 -0
  36. package/lib/tool-browser/page-probe.js +460 -0
  37. package/package.json +4 -2
  38. package/scripts/verify-runtime-status.mjs +14 -0
  39. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  40. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  41. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  42. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  43. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  44. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  45. package/src/browser/runtime.ts +11 -0
  46. package/src/browser/types.ts +19 -0
  47. package/src/browser-electron/authenticated-route.ts +56 -0
  48. package/src/browser-electron/bridge-endpoint.ts +7 -0
  49. package/src/browser-electron/bridge-install.ts +122 -0
  50. package/src/browser-electron/bridge-status.ts +22 -2
  51. package/src/browser-electron/desktop-bridge-host.ts +33 -15
  52. package/src/browser-electron/electron-provision.ts +30 -12
  53. package/src/browser-electron/entry.ts +76 -8
  54. package/src/browser-electron/host-main.ts +41 -22
  55. package/src/browser-electron/provider.ts +90 -6
  56. package/src/browser-electron/remote-host.ts +4 -4
  57. package/src/browser-electron/runtime-route.ts +3 -5
  58. package/src/browser-electron/runtime-status.ts +4 -2
  59. package/src/browser-electron/settings-route.ts +9 -32
  60. package/src/browser-electron/settings-store.ts +39 -0
  61. package/src/browser-electron/system-browser.ts +9 -3
  62. package/src/tool-browser/index.ts +991 -7
  63. package/src/tool-browser/page-probe.ts +474 -0
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The page-side probe: one script that makes a page observable without touching the host.
3
+ *
4
+ * WHY THIS EXISTS
5
+ * Three capabilities the model needs are not tools here yet: what the console said, which network
6
+ * responses arrived, and what happened to a JavaScript dialog. All three live *inside* the page, and
7
+ * a dialog blocks the page until someone answers it — which is why a `confirm()` used to hang a whole
8
+ * tool call with no explanation.
9
+ *
10
+ * The obvious implementation is CDP event capture (`Runtime.consoleAPICalled`, `Network.*`,
11
+ * `Page.javascriptDialogOpening`) inside the host. That would mean a new capability in all three
12
+ * carriers — the self-hosted child, the driven Chrome and the sidebar bridge — plus a protocol
13
+ * version for the bridge. This probe instead installs itself with the `execute` path every carrier
14
+ * already has, so it works everywhere on day one and cannot drift per carrier.
15
+ *
16
+ * What it costs, stated plainly:
17
+ * - `console` and `network` see what the PAGE can see. A response that never reached `fetch`/`XHR`
18
+ * (a document navigation, an `<img>` failure the browser handled internally) appears only as a
19
+ * resource-timing entry, with no status code. CDP would know more.
20
+ * - Dialog capture works by replacing `window.alert/confirm/prompt` BEFORE they are called. A dialog
21
+ * produced by the browser itself (`beforeunload`, HTTP auth, permission prompts) is not covered.
22
+ * - It is an override, so a page that captured `window.fetch` earlier keeps its own copy. Installed
23
+ * at first use, which is early enough for every ordinary page and honest about the rest.
24
+ *
25
+ * Idempotent by version: installing twice keeps the buffers that already exist.
26
+ * @module dsh-browser/tool-browser/page-probe
27
+ */
28
+ import type { BrowserPageOperationRequest } from '../browser/types.js';
29
+ /** Bumped when the probe's shape changes; an older probe is replaced rather than trusted. */
30
+ export declare const PROBE_VERSION = 4;
31
+ /**
32
+ * The installer, as one expression that returns the installed version.
33
+ *
34
+ * Written as a string because it runs in the page, not here. Keep it dependency-free and ES5-safe:
35
+ * a page may be older than the harness.
36
+ */
37
+ export declare const PROBE_INSTALL_SCRIPT: string;
38
+ /**
39
+ * One probe call, evaluated in the page, with its result serialised as JSON.
40
+ *
41
+ * JSON in, JSON out, because that is the only shape every carrier's `execute` can carry reliably.
42
+ * @param method - the probe function to call (`read`, `settle`, `find`, `overlayAt`, `clear`, …).
43
+ * @param args - arguments, already JSON-serialisable.
44
+ * @returns a script whose value is the JSON text of the result (or an error object).
45
+ */
46
+ export declare function probeCallScript(method: string, args?: readonly unknown[]): string;
47
+ /**
48
+ * Dispatch a pointer drag in the page, for elements that accept synthetic pointer events.
49
+ *
50
+ * Uses `PointerEvent` when the page has it and `MouseEvent` otherwise, because a canvas app that
51
+ * listens for `mousedown` never sees a pointer event. This is a page-level gesture: a page that
52
+ * demands trusted input (some canvas editors) ignores it, exactly like `click_sequence`'s
53
+ * coordinate clicks are the trusted counterpart.
54
+ * @param from - start point in viewport CSS pixels.
55
+ * @param to - end point.
56
+ * @param steps - intermediate moves; more steps make a slider or a canvas app follow the path.
57
+ * @returns a script value: `{ ok: true, moved, at }` or `{ ok: false, reason }`.
58
+ */
59
+ export declare function dragScript(from: {
60
+ readonly x: number;
61
+ readonly y: number;
62
+ }, to: {
63
+ readonly x: number;
64
+ readonly y: number;
65
+ }, steps?: number): string;
66
+ /**
67
+ * Put a local file into an `<input type=file>`, without CDP.
68
+ *
69
+ * The page cannot read a disk path, so the bytes travel in as base64 and are rebuilt as a `File`
70
+ * in page context, then attached through a `DataTransfer`. That is what a drag-and-drop handler
71
+ * sees, so frameworks that read `input.files` or a drop event both work. The admission decision
72
+ * (which path may be read at all) belongs to the caller; this only carries the bytes.
73
+ * @param target - how to find the input: a CSS selector or visible text near it.
74
+ * @param file - name, MIME type and base64 of the bytes.
75
+ * @returns a script value: `{ ok: true, name, size }` or `{ ok: false, reason }`.
76
+ */
77
+ export declare function uploadScript(target: {
78
+ readonly by: 'css' | 'text' | 'xpath';
79
+ readonly value: string;
80
+ }, file: {
81
+ readonly name: string;
82
+ readonly mime: string;
83
+ readonly base64: string;
84
+ }): string;
85
+ /** Build a fixed page operation, rejecting unknown operations before any code runs. */
86
+ export declare function pageOperationScript(request: BrowserPageOperationRequest): string;
@@ -0,0 +1,460 @@
1
+ /**
2
+ * The page-side probe: one script that makes a page observable without touching the host.
3
+ *
4
+ * WHY THIS EXISTS
5
+ * Three capabilities the model needs are not tools here yet: what the console said, which network
6
+ * responses arrived, and what happened to a JavaScript dialog. All three live *inside* the page, and
7
+ * a dialog blocks the page until someone answers it — which is why a `confirm()` used to hang a whole
8
+ * tool call with no explanation.
9
+ *
10
+ * The obvious implementation is CDP event capture (`Runtime.consoleAPICalled`, `Network.*`,
11
+ * `Page.javascriptDialogOpening`) inside the host. That would mean a new capability in all three
12
+ * carriers — the self-hosted child, the driven Chrome and the sidebar bridge — plus a protocol
13
+ * version for the bridge. This probe instead installs itself with the `execute` path every carrier
14
+ * already has, so it works everywhere on day one and cannot drift per carrier.
15
+ *
16
+ * What it costs, stated plainly:
17
+ * - `console` and `network` see what the PAGE can see. A response that never reached `fetch`/`XHR`
18
+ * (a document navigation, an `<img>` failure the browser handled internally) appears only as a
19
+ * resource-timing entry, with no status code. CDP would know more.
20
+ * - Dialog capture works by replacing `window.alert/confirm/prompt` BEFORE they are called. A dialog
21
+ * produced by the browser itself (`beforeunload`, HTTP auth, permission prompts) is not covered.
22
+ * - It is an override, so a page that captured `window.fetch` earlier keeps its own copy. Installed
23
+ * at first use, which is early enough for every ordinary page and honest about the rest.
24
+ *
25
+ * Idempotent by version: installing twice keeps the buffers that already exist.
26
+ * @module dsh-browser/tool-browser/page-probe
27
+ */
28
+ /** Bumped when the probe's shape changes; an older probe is replaced rather than trusted. */
29
+ export const PROBE_VERSION = 4;
30
+ /** Where the probe keeps itself, and the only global it adds. */
31
+ const PROBE_KEY = '__dshProbe';
32
+ /**
33
+ * The installer, as one expression that returns the installed version.
34
+ *
35
+ * Written as a string because it runs in the page, not here. Keep it dependency-free and ES5-safe:
36
+ * a page may be older than the harness.
37
+ */
38
+ export const PROBE_INSTALL_SCRIPT = `(() => {
39
+ const KEY = ${JSON.stringify(PROBE_KEY)}
40
+ const VERSION = ${PROBE_VERSION}
41
+ const previous = globalThis[KEY]
42
+ if (previous && previous.version === VERSION) return VERSION
43
+ if (previous) {
44
+ if (typeof previous.dispose !== 'function') throw new Error('reload this page to replace the older browser probe')
45
+ previous.dispose()
46
+ }
47
+ const restore = []
48
+ const replace = (target, key, value) => {
49
+ const original = target[key]
50
+ target[key] = value
51
+ restore.push(() => { if (target[key] === value) target[key] = original })
52
+ }
53
+
54
+ const state = {
55
+ version: VERSION,
56
+ startedAt: Date.now(),
57
+ console: [],
58
+ network: [],
59
+ dialogs: [],
60
+ dialogPolicy: 'native',
61
+ networkSequence: 0,
62
+ pending: 0,
63
+ lastNetworkAt: Date.now(),
64
+ lastMutationAt: Date.now(),
65
+ }
66
+ const cap = (list, item, limit) => { list.push(item); if (list.length > limit) list.splice(0, list.length - limit) }
67
+ const asText = (value) => {
68
+ try { return typeof value === 'string' ? value : JSON.stringify(value) } catch (error) { return String(value) }
69
+ }
70
+ const short = (value, limit) => { const text = String(value == null ? '' : value); return text.length > limit ? text.slice(0, limit) + '…' : text }
71
+
72
+ for (const level of ['log', 'info', 'warn', 'error', 'debug']) {
73
+ const original = console[level]
74
+ if (typeof original !== 'function') continue
75
+ replace(console, level, function () {
76
+ const parts = []
77
+ for (let i = 0; i < arguments.length; i += 1) parts.push(asText(arguments[i]))
78
+ cap(state.console, { at: Date.now(), level: level, text: short(parts.join(' '), 500) }, 200)
79
+ return original.apply(this, arguments)
80
+ })
81
+ }
82
+
83
+ const note = (entry) => { state.lastNetworkAt = Date.now(); entry.receivedAt = state.lastNetworkAt; entry.sequence = ++state.networkSequence; cap(state.network, entry, 300) }
84
+ const nativeFetch = globalThis.fetch
85
+ if (typeof nativeFetch === 'function') {
86
+ replace(globalThis, 'fetch', function (input, init) {
87
+ const url = typeof input === 'string' ? input : (input && input.url) || String(input)
88
+ const method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase()
89
+ const started = Date.now()
90
+ state.pending += 1
91
+ const settle = (status) => {
92
+ state.pending = Math.max(0, state.pending - 1)
93
+ note({ at: started, kind: 'fetch', method: method, url: short(url, 300), status: status, ms: Date.now() - started })
94
+ }
95
+ return nativeFetch.apply(this, arguments).then(
96
+ (response) => { settle(response.status); return response },
97
+ (error) => { settle(0); throw error },
98
+ )
99
+ })
100
+ }
101
+
102
+ const XHR = globalThis.XMLHttpRequest
103
+ if (XHR && XHR.prototype && typeof XHR.prototype.send === 'function') {
104
+ const open = XHR.prototype.open
105
+ const send = XHR.prototype.send
106
+ replace(XHR.prototype, 'open', function (method, url) {
107
+ this.__dshNetwork = { method: String(method || 'GET').toUpperCase(), url: String(url || ''), at: Date.now() }
108
+ return open.apply(this, arguments)
109
+ })
110
+ replace(XHR.prototype, 'send', function () {
111
+ const meta = this.__dshNetwork || { method: 'GET', url: '', at: Date.now() }
112
+ state.pending += 1
113
+ const done = () => {
114
+ state.pending = Math.max(0, state.pending - 1)
115
+ note({ at: meta.at, kind: 'xhr', method: meta.method, url: short(meta.url, 300), status: this.status || 0, ms: Date.now() - meta.at })
116
+ this.removeEventListener('loadend', done)
117
+ }
118
+ this.addEventListener('loadend', done)
119
+ return send.apply(this, arguments)
120
+ })
121
+ }
122
+
123
+ if (typeof PerformanceObserver === 'function') {
124
+ try {
125
+ const seen = new Set()
126
+ const observer = new PerformanceObserver((list) => {
127
+ const entries = list.getEntries()
128
+ for (let i = 0; i < entries.length; i += 1) {
129
+ const entry = entries[i]
130
+ const key = entry.name + '|' + entry.startTime
131
+ if (seen.has(key)) continue
132
+ seen.add(key)
133
+ note({ at: Math.round((performance.timeOrigin || Date.now()) + entry.startTime), kind: 'resource', method: 'GET', url: short(entry.name, 300), status: 0, ms: Math.round(entry.duration), bytes: entry.transferSize || 0 })
134
+ }
135
+ })
136
+ observer.observe({ type: 'resource', buffered: true })
137
+ restore.push(() => observer.disconnect())
138
+ } catch (error) { /* a page with no resource timing still has fetch and XHR */ }
139
+ }
140
+
141
+ const nativeDialogs = {}
142
+ const dialogWrappers = {}
143
+ for (const kind of ['alert', 'confirm', 'prompt']) {
144
+ const original = globalThis[kind]
145
+ if (typeof original !== 'function') continue
146
+ nativeDialogs[kind] = original
147
+ const wrapper = function (message, value) {
148
+ const accept = state.dialogPolicy === 'accept'
149
+ cap(state.dialogs, { at: Date.now(), kind: kind, message: short(message, 300), policy: state.dialogPolicy, answered: accept ? 'accepted' : 'dismissed' }, 50)
150
+ if (!accept) return kind === 'confirm' ? false : kind === 'prompt' ? null : undefined
151
+ return kind === 'prompt' ? String(value == null ? '' : value) : kind === 'confirm' ? true : undefined
152
+ }
153
+ dialogWrappers[kind] = wrapper
154
+ restore.push(() => { if (globalThis[kind] === wrapper) globalThis[kind] = nativeDialogs[kind] })
155
+ }
156
+
157
+ try {
158
+ const observer = new MutationObserver(() => { state.lastMutationAt = Date.now() })
159
+ observer.observe(document.documentElement || document, { subtree: true, childList: true, attributes: true })
160
+ restore.push(() => observer.disconnect())
161
+ } catch (error) { /* no observer: quiet time falls back to network only */ }
162
+
163
+ const describe = (node) => {
164
+ if (!node || !node.tagName) return 'unknown'
165
+ const name = (node.getAttribute && (node.getAttribute('aria-label') || node.getAttribute('name'))) || ''
166
+ const text = short((node.innerText || '').trim().replace(/\\s+/g, ' '), 60)
167
+ return node.tagName.toLowerCase() + (name ? '[' + name + ']' : '') + (text ? ' "' + text + '"' : '')
168
+ }
169
+
170
+ state.settle = function () {
171
+ const quietFrom = Math.max(state.lastNetworkAt, state.lastMutationAt)
172
+ return { pending: state.pending, quietMs: Date.now() - quietFrom, readyState: String(document.readyState) }
173
+ }
174
+
175
+ state.find = function (target, scroll) {
176
+ if (!target) return null
177
+ let node = null
178
+ try {
179
+ if (target.css) node = document.querySelector(String(target.css))
180
+ else if (target.xpath) node = document.evaluate(String(target.xpath), document, null, 9, null).singleNodeValue
181
+ else if (target.text) {
182
+ const wanted = String(target.text).trim().toLowerCase()
183
+ const nodes = document.querySelectorAll('button, a, [role=button], input, label, [role=tab], [role=option], [role=link]')
184
+ for (let i = 0; i < nodes.length; i += 1) {
185
+ const value = ((nodes[i].innerText || nodes[i].getAttribute('aria-label') || nodes[i].value || '') + '').trim().toLowerCase()
186
+ if (value && value.indexOf(wanted) !== -1) { node = nodes[i]; break }
187
+ }
188
+ }
189
+ } catch (error) { return null }
190
+ if (!node) return null
191
+ if (scroll === true && typeof node.scrollIntoView === 'function') node.scrollIntoView({ block: 'center', inline: 'center', behavior: 'instant' })
192
+ const rect = node.getBoundingClientRect()
193
+ return { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2), w: Math.round(rect.width), h: Math.round(rect.height), described: describe(node) }
194
+ }
195
+
196
+ const DISMISS = /(accept|agree|allow|continue|close|got it|dismiss|ok|agree|同意|接受|允许|继续|关闭|知道了|我知道了|我同意)/i
197
+
198
+ state.overlayAt = function (x, y) {
199
+ const top = document.elementFromPoint(Number(x), Number(y))
200
+ if (!top) return { covers: null, dismiss: null }
201
+ let node = top
202
+ let depth = 0
203
+ while (node && depth < 8) {
204
+ let style = null
205
+ try { style = getComputedStyle(node) } catch (error) { style = null }
206
+ const floating = style && (style.position === 'fixed' || style.position === 'sticky' || Number(style.zIndex) >= 100)
207
+ if (floating) {
208
+ const buttons = node.querySelectorAll('button, [role=button], a')
209
+ for (let i = 0; i < buttons.length && i < 60; i += 1) {
210
+ const label = ((buttons[i].innerText || '') + ' ' + (buttons[i].getAttribute('aria-label') || '')).trim()
211
+ if (DISMISS.test(label)) {
212
+ const rect = buttons[i].getBoundingClientRect()
213
+ return { covers: describe(top), dismiss: { label: short(label, 40), x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2) } }
214
+ }
215
+ }
216
+ return { covers: describe(top), dismiss: null }
217
+ }
218
+ node = node.parentElement
219
+ depth += 1
220
+ }
221
+ return { covers: describe(top), dismiss: null }
222
+ }
223
+
224
+ state.read = function (kind, filter, limit) {
225
+ const list = kind === 'console' ? state.console : kind === 'network' ? state.network : state.dialogs
226
+ const needle = filter ? String(filter).toLowerCase() : ''
227
+ const rows = needle === '' ? list : list.filter((row) => ((row.url || '') + ' ' + (row.text || '') + ' ' + (row.message || '')).toLowerCase().indexOf(needle) !== -1)
228
+ const max = Math.max(0, Math.min(Number(limit) || 20, 100))
229
+ return rows.slice(Math.max(0, rows.length - max))
230
+ }
231
+
232
+ state.clear = function (kind) {
233
+ if (kind === 'console') state.console.length = 0
234
+ else if (kind === 'network') state.network.length = 0
235
+ else if (kind === 'dialogs') state.dialogs.length = 0
236
+ return true
237
+ }
238
+
239
+ state.setDialogPolicy = function (policy) {
240
+ if (policy !== 'native' && policy !== 'accept' && policy !== 'dismiss') return state.dialogPolicy
241
+ const previousPolicy = state.dialogPolicy
242
+ state.dialogPolicy = policy
243
+ for (const kind of Object.keys(nativeDialogs)) {
244
+ if (policy === 'native') {
245
+ if (globalThis[kind] === dialogWrappers[kind]) globalThis[kind] = nativeDialogs[kind]
246
+ } else {
247
+ if (previousPolicy === 'native' && globalThis[kind] !== dialogWrappers[kind]) nativeDialogs[kind] = globalThis[kind]
248
+ globalThis[kind] = dialogWrappers[kind]
249
+ }
250
+ }
251
+ return state.dialogPolicy
252
+ }
253
+
254
+ state.dialogStatus = function () { return state.dialogPolicy }
255
+ state.networkCursor = function () { return { startedAt: state.startedAt, sequence: state.networkSequence } }
256
+ state.dispose = function () {
257
+ for (const undo of restore.reverse()) { try { undo() } catch (error) {} }
258
+ if (globalThis[KEY] === state) delete globalThis[KEY]
259
+ }
260
+
261
+ state.findText = function (text, all) {
262
+ const needle = String(text || '')
263
+ const out = []
264
+ if (needle === '') return out
265
+ const wanted = needle.toLowerCase()
266
+ const root = document.body || document.documentElement
267
+ if (!root || typeof document.createTreeWalker !== 'function') return out
268
+ const walker = document.createTreeWalker(root, 4, null) // 4 = SHOW_TEXT
269
+ let node = walker.nextNode()
270
+ while (node) {
271
+ const value = node.nodeValue || ''
272
+ let at = value.toLowerCase().indexOf(wanted)
273
+ while (at !== -1) {
274
+ const range = document.createRange()
275
+ range.setStart(node, at)
276
+ range.setEnd(node, at + needle.length)
277
+ const rect = range.getBoundingClientRect()
278
+ out.push({
279
+ text: short(value.slice(Math.max(0, at - 20), at + needle.length + 20).replace(/\s+/g, ' ').trim(), 80),
280
+ x: Math.round(rect.left + rect.width / 2),
281
+ y: Math.round(rect.top + rect.height / 2),
282
+ host: node.parentElement ? describe(node.parentElement) : 'text',
283
+ })
284
+ if (out.length >= (all ? 50 : 5)) return out
285
+ at = value.toLowerCase().indexOf(wanted, at + 1)
286
+ }
287
+ node = walker.nextNode()
288
+ }
289
+ return out
290
+ }
291
+
292
+ const hoverEvent = (type, node, x, y) => {
293
+ const init = { bubbles: type.indexOf('enter') === -1, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: 0 }
294
+ try {
295
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
296
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
297
+ } catch (error) { return null }
298
+ return null
299
+ }
300
+
301
+ state.hoverAt = function (x, y) {
302
+ const node = document.elementFromPoint(Number(x), Number(y))
303
+ if (!node) return false
304
+ const types = ['pointerover', 'pointerenter', 'mouseover', 'mouseenter', 'mousemove']
305
+ let fired = 0
306
+ for (let i = 0; i < types.length; i += 1) {
307
+ const event = hoverEvent(types[i], node, Number(x), Number(y))
308
+ if (event && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); fired += 1 }
309
+ }
310
+ return fired > 0
311
+ }
312
+
313
+ state.summary = function () {
314
+ const body = document.body ? document.body.innerText : ''
315
+ const query = (selector) => { try { return document.querySelectorAll(selector).length } catch (error) { return 0 } }
316
+ const settled = state.settle()
317
+ return {
318
+ url: String(location.href),
319
+ title: String(document.title || ''),
320
+ readyState: settled.readyState,
321
+ pending: settled.pending,
322
+ quietMs: settled.quietMs,
323
+ inputs: query('input, textarea, select'),
324
+ buttons: query('button, [role=button]'),
325
+ links: query('a[href]'),
326
+ scrollX: Math.round(globalThis.scrollX || 0),
327
+ scrollY: Math.round(globalThis.scrollY || 0),
328
+ selection: short(globalThis.getSelection ? String(globalThis.getSelection()) : '', 120),
329
+ text: short(String(body || '').replace(/\s+/g, ' ').trim(), 400),
330
+ }
331
+ }
332
+ globalThis[KEY] = state
333
+ return VERSION
334
+ })()`;
335
+ /**
336
+ * One probe call, evaluated in the page, with its result serialised as JSON.
337
+ *
338
+ * JSON in, JSON out, because that is the only shape every carrier's `execute` can carry reliably.
339
+ * @param method - the probe function to call (`read`, `settle`, `find`, `overlayAt`, `clear`, …).
340
+ * @param args - arguments, already JSON-serialisable.
341
+ * @returns a script whose value is the JSON text of the result (or an error object).
342
+ */
343
+ export function probeCallScript(method, args = []) {
344
+ return `(() => {
345
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
346
+ if (!probe) return JSON.stringify({ error: 'probe-not-installed' })
347
+ if (typeof probe[${JSON.stringify(method)}] !== 'function') return JSON.stringify({ error: 'probe-method-missing' })
348
+ try { return JSON.stringify(probe[${JSON.stringify(method)}].apply(probe, ${JSON.stringify(args)})) } catch (error) { return JSON.stringify({ error: String(error) }) }
349
+ })()`;
350
+ }
351
+ /**
352
+ * Dispatch a pointer drag in the page, for elements that accept synthetic pointer events.
353
+ *
354
+ * Uses `PointerEvent` when the page has it and `MouseEvent` otherwise, because a canvas app that
355
+ * listens for `mousedown` never sees a pointer event. This is a page-level gesture: a page that
356
+ * demands trusted input (some canvas editors) ignores it, exactly like `click_sequence`'s
357
+ * coordinate clicks are the trusted counterpart.
358
+ * @param from - start point in viewport CSS pixels.
359
+ * @param to - end point.
360
+ * @param steps - intermediate moves; more steps make a slider or a canvas app follow the path.
361
+ * @returns a script value: `{ ok: true, moved, at }` or `{ ok: false, reason }`.
362
+ */
363
+ export function dragScript(from, to, steps = 12) {
364
+ const points = JSON.stringify({ from, to, steps });
365
+ return `(() => {
366
+ const spec = ${points}
367
+ const at = (x, y) => document.elementFromPoint(x, y)
368
+ const start = at(spec.from.x, spec.from.y)
369
+ if (!start) return JSON.stringify({ ok: false, reason: 'nothing at the start point' })
370
+ const make = (type, x, y, extra) => {
371
+ const init = Object.assign({ bubbles: true, cancelable: true, composed: true, clientX: x, clientY: y, button: 0, buttons: type === 'pointerup' || type === 'mouseup' ? 0 : 1 }, extra || {})
372
+ try {
373
+ if (type.indexOf('pointer') === 0 && typeof PointerEvent === 'function') return new PointerEvent(type, Object.assign({ pointerId: 1, pointerType: 'mouse', isPrimary: true }, init))
374
+ if (typeof MouseEvent === 'function') return new MouseEvent(type.replace('pointer', 'mouse'), init)
375
+ } catch (error) { /* fall through to the null below */ }
376
+ return null
377
+ }
378
+ const fire = (node, type, x, y, extra) => {
379
+ const event = make(type, x, y, extra)
380
+ if (event !== null && node && typeof node.dispatchEvent === 'function') { node.dispatchEvent(event); return true }
381
+ return false
382
+ }
383
+ if (!fire(start, 'pointerdown', spec.from.x, spec.from.y)) {
384
+ return JSON.stringify({ ok: false, reason: 'this page exposes no event constructors to dispatch a drag' })
385
+ }
386
+ fire(start, 'mousedown', spec.from.x, spec.from.y)
387
+ const total = Math.max(1, Math.min(Number(spec.steps) || 12, 60))
388
+ for (let i = 1; i <= total; i += 1) {
389
+ const x = Math.round(spec.from.x + (spec.to.x - spec.from.x) * (i / total))
390
+ const y = Math.round(spec.from.y + (spec.to.y - spec.from.y) * (i / total))
391
+ const node = at(x, y) || start
392
+ fire(node, 'pointermove', x, y)
393
+ fire(node, 'mousemove', x, y)
394
+ }
395
+ const end = at(spec.to.x, spec.to.y) || start
396
+ fire(end, 'pointerup', spec.to.x, spec.to.y)
397
+ fire(end, 'mouseup', spec.to.x, spec.to.y)
398
+ return JSON.stringify({ ok: true, moved: total, at: spec.to })
399
+ })()`;
400
+ }
401
+ /**
402
+ * Put a local file into an `<input type=file>`, without CDP.
403
+ *
404
+ * The page cannot read a disk path, so the bytes travel in as base64 and are rebuilt as a `File`
405
+ * in page context, then attached through a `DataTransfer`. That is what a drag-and-drop handler
406
+ * sees, so frameworks that read `input.files` or a drop event both work. The admission decision
407
+ * (which path may be read at all) belongs to the caller; this only carries the bytes.
408
+ * @param target - how to find the input: a CSS selector or visible text near it.
409
+ * @param file - name, MIME type and base64 of the bytes.
410
+ * @returns a script value: `{ ok: true, name, size }` or `{ ok: false, reason }`.
411
+ */
412
+ export function uploadScript(target, file) {
413
+ const spec = JSON.stringify({ target, file });
414
+ return `(() => {
415
+ const spec = ${spec}
416
+ const probe = globalThis[${JSON.stringify(PROBE_KEY)}]
417
+ const where = probe ? probe.find(spec.target) : null
418
+ let node = null
419
+ try {
420
+ if (spec.target.by === 'css') node = document.querySelector(spec.target.value)
421
+ else if (spec.target.by === 'xpath') node = document.evaluate(spec.target.value, document, null, 9, null).singleNodeValue
422
+ else if (where) node = document.elementFromPoint(where.x, where.y)
423
+ } catch (error) { node = null }
424
+ if (node && node.tagName !== 'INPUT' && node.querySelector) {
425
+ const nested = node.querySelector('input[type=file]')
426
+ if (nested) node = nested
427
+ }
428
+ if (!node || node.tagName !== 'INPUT' || String(node.type).toLowerCase() !== 'file') {
429
+ return JSON.stringify({ ok: false, reason: 'no file input at that target (' + (where ? where.described : 'nothing matched') + ')' })
430
+ }
431
+ const binary = atob(spec.file.base64)
432
+ const bytes = new Uint8Array(binary.length)
433
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)
434
+ const blob = new File([bytes], spec.file.name, { type: spec.file.mime || 'application/octet-stream' })
435
+ const transfer = new DataTransfer()
436
+ transfer.items.add(blob)
437
+ node.files = transfer.files
438
+ node.dispatchEvent(new Event('input', { bubbles: true }))
439
+ node.dispatchEvent(new Event('change', { bubbles: true }))
440
+ return JSON.stringify({ ok: true, name: blob.name, size: blob.size, files: node.files ? node.files.length : 0 })
441
+ })()`;
442
+ }
443
+ /** Build a fixed page operation, rejecting unknown operations before any code runs. */
444
+ export function pageOperationScript(request) {
445
+ switch (request.operation) {
446
+ case 'install': return PROBE_INSTALL_SCRIPT;
447
+ case 'url': return 'JSON.stringify(location.href)';
448
+ case 'text': return 'JSON.stringify((document.body ? document.body.innerText : "").indexOf(' + JSON.stringify(request.text) + ') !== -1)';
449
+ case 'drag': return dragScript(request.from, request.to, request.steps);
450
+ case 'upload': return uploadScript(request.target, request.file);
451
+ case 'probe': {
452
+ const methods = ['read', 'clear', 'settle', 'find', 'overlayAt', 'summary',
453
+ 'findText', 'hoverAt', 'setDialogPolicy', 'dialogStatus', 'networkCursor'];
454
+ if (!methods.includes(request.method))
455
+ throw new Error('browser: unsupported fixed page operation');
456
+ return probeCallScript(request.method, request.args);
457
+ }
458
+ default: throw new Error('browser: unsupported fixed page operation');
459
+ }
460
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-builtin-browser",
3
- "version": "0.5.6",
3
+ "version": "0.5.7",
4
4
  "description": "Shared real browser plugin for DeepSeek Harness: install-and-use — a visible native browser the human can take over, driven by the agent over CDP. DOM-level interaction (React/Vue safe), per-task session isolation, cookie persistence (dsh_browser_auth), CAPTCHA detection, batch form fill (dsh_browser_fill), authenticated download, history/replay, action restriction",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -35,6 +35,7 @@
35
35
  "lib",
36
36
  "src",
37
37
  "docs",
38
+ "skills",
38
39
  "desktop-bridge",
39
40
  "client.js",
40
41
  "cordis.patch.yml",
@@ -114,7 +115,8 @@
114
115
  "0.2.0-rc.2": "compatible",
115
116
  "0.2.1-alpha.1": "compatible",
116
117
  "0.2.1-rc.1": "compatible",
117
- "0.2.1-rc.5": "compatible"
118
+ "0.2.1-rc.5": "compatible",
119
+ "0.2.2-alpha.3": "compatible"
118
120
  }
119
121
  }
120
122
  }
@@ -80,7 +80,21 @@ class StubWebServer extends cordis.Service {
80
80
  }
81
81
 
82
82
  const root = new cordis.Context()
83
+
84
+ /** The host's authentication service: this probe checks our handlers, not the host's cookie. */
85
+ class StubConnection extends cordis.Service {
86
+ constructor(ctx) {
87
+ super(ctx, 'connection')
88
+ this.calls = 0
89
+ }
90
+ authorizeIndex() {
91
+ this.calls += 1
92
+ return true
93
+ }
94
+ }
95
+
83
96
  new StubWebServer(root)
97
+ new StubConnection(root)
84
98
 
85
99
  const seam = await import(new URL('lib/browser/runtime.js', REPO).href)
86
100
  new seam.default(root)
@@ -0,0 +1,64 @@
1
+ ---
2
+ name: dsh-builtin-browser
3
+ description: Use when a task needs a real web page — opening a URL, reading or extracting from it, filling and submitting a form, uploading an attachment, checking whether a result actually happened, or recovering after a page or carrier goes away. Covers which dsh_browser_* tool to reach for, how to batch steps, and how to verify instead of guessing.
4
+ ---
5
+
6
+ # Driving the browser
7
+
8
+ The browser is a real Chromium the human can watch and take over. Your tools drive it over the
9
+ page itself, so everything here works the same on the desktop sidebar, on an installed Chrome and
10
+ on the plugin's own window.
11
+
12
+ ## Before acting
13
+
14
+ 1. `dsh_browser_state` — where am I? URL, load state, requests in flight, what is on the page.
15
+ 2. `dsh_browser_snapshot` (numbered interactive elements) or `dsh_browser_a11y` (roles, names,
16
+ states) — pick the structure map, not a screenshot, unless the page is canvas-only.
17
+ 3. Then act with a semantic target: `{by: "text"|"css"|"xpath", value}`. Elements carry a stable
18
+ CSS selector, so a click re-resolves the element; never trust an index from an older snapshot.
19
+
20
+ ## Batch, do not drip
21
+
22
+ `dsh_browser_do` runs a list of steps in ONE call and stops at the first that cannot proceed.
23
+ "Click search → type the query → press Enter → wait for results" is one call, not five. Steps:
24
+ `open`, `tap`, `field`, `type`, `key`, `scroll`, `sleep_ms`, `wait_text`, `wait_gone`, `wait_url`,
25
+ `wait_idle`, `eval`, `check`. Waits are condition-based; a `tap` whose target is covered by a
26
+ cookie banner dismisses the banner first.
27
+
28
+ ## Wait on facts, not on time
29
+
30
+ - `dsh_browser_wait` — load complete, an expected URL or a selector.
31
+ - `dsh_browser_wait_for_response` — a server answer arrived **after** this call started. This is
32
+ the "did the submit reach the server" wait; a screenshot cannot answer it.
33
+ - `dsh_browser_console` / `dsh_browser_network` — what the page actually did when the screen does
34
+ not explain the failure.
35
+
36
+ ## Verify, then retry
37
+
38
+ `dsh_browser_assert` checks a selector, text, URL or JS predicate and returns evidence per check.
39
+ "Clicked" and "the form accepted it" are different claims. Before retrying anything that changes
40
+ server state, assert that the previous attempt did not already take effect.
41
+
42
+ ## Files
43
+
44
+ - `dsh_browser_download` — save a URL through the directory admission gate (never overwrites).
45
+ - `dsh_browser_upload` — put a local file (inside the workspace) into a file input.
46
+ - `dsh_browser_screenshot` — for the human, or when the page has no usable DOM.
47
+
48
+ ## When the page fights you
49
+
50
+ - Dialogs: native page handling by default. Explicit accept/dismiss enables automatic answers; native restores page handling. `dsh_browser_dialog` reports them and can
51
+ switch the policy to accept.
52
+ - Menus that appear on hover: use `dsh_browser_hover` before snapshotting. It moves the browser
53
+ pointer and activates CSS hover styles and mouse handlers.
54
+ - Sliders, sortable lists, drop targets, and canvas strokes: use `dsh_browser_drag` with viewport
55
+ CSS coordinates, then verify the resulting value, order, dropped data, or canvas state.
56
+ - Runs of canvas clicks: use `dsh_browser_click_sequence`.
57
+ - Something is odd and nothing explains it: `dsh_browser_doctor`, then `dsh_browser_help`.
58
+
59
+ ## Never
60
+
61
+ - Do not re-submit a form whose result you have not verified — a lost reply is not a failed submit.
62
+ - Do not paste cookies, tokens or exported login state into the conversation.
63
+ - Do not assume another task's tabs or navigation are visible to you: each task has its own
64
+ session, and `dsh_browser_reset_session` ends yours without touching anyone else's.