dsh-builtin-browser 0.5.6 → 0.5.8

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 (119) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.en.md +75 -81
  3. package/README.md +75 -82
  4. package/client.js +831 -384
  5. package/desktop-bridge/install-and-start.cmd +4 -5
  6. package/desktop-bridge/install.mjs +322 -141
  7. package/desktop-bridge/maintenance-progress.ps1 +166 -0
  8. package/desktop-bridge/plugin-browser-bridge.js +157 -19
  9. package/desktop-bridge/request-desktop-quit.ps1 +170 -0
  10. package/docs/tool-reference.md +20 -1
  11. package/docs/user-guide.md +28 -4
  12. package/lib/browser/runtime.d.ts +3 -1
  13. package/lib/browser/runtime.js +9 -0
  14. package/lib/browser/types.d.ts +42 -0
  15. package/lib/browser-electron/authenticated-route.d.ts +27 -0
  16. package/lib/browser-electron/authenticated-route.js +39 -0
  17. package/lib/browser-electron/automatic-maintenance.d.ts +41 -0
  18. package/lib/browser-electron/automatic-maintenance.js +426 -0
  19. package/lib/browser-electron/bridge-auto.d.ts +93 -0
  20. package/lib/browser-electron/bridge-auto.js +113 -0
  21. package/lib/browser-electron/bridge-connection.d.ts +0 -2
  22. package/lib/browser-electron/bridge-connection.js +2 -4
  23. package/lib/browser-electron/bridge-endpoint.js +8 -19
  24. package/lib/browser-electron/bridge-install.d.ts +85 -0
  25. package/lib/browser-electron/bridge-install.js +211 -0
  26. package/lib/browser-electron/bridge-maintenance.d.ts +24 -0
  27. package/lib/browser-electron/bridge-maintenance.js +125 -0
  28. package/lib/browser-electron/bridge-status.d.ts +10 -3
  29. package/lib/browser-electron/bridge-status.js +74 -24
  30. package/lib/browser-electron/desktop-bridge-host.d.ts +11 -5
  31. package/lib/browser-electron/desktop-bridge-host.js +67 -25
  32. package/lib/browser-electron/desktop-identity.js +21 -9
  33. package/lib/browser-electron/electron-provision.d.ts +1 -1
  34. package/lib/browser-electron/electron-provision.js +36 -13
  35. package/lib/browser-electron/entry.js +173 -67
  36. package/lib/browser-electron/ephemeral-profile.js +67 -26
  37. package/lib/browser-electron/history-store.js +2 -2
  38. package/lib/browser-electron/host-main.js +48 -38
  39. package/lib/browser-electron/http-body.d.ts +24 -0
  40. package/lib/browser-electron/http-body.js +33 -0
  41. package/lib/browser-electron/json-reply.d.ts +13 -1
  42. package/lib/browser-electron/json-reply.js +16 -2
  43. package/lib/browser-electron/maintenance-broker.d.ts +35 -0
  44. package/lib/browser-electron/maintenance-broker.js +114 -0
  45. package/lib/browser-electron/maintenance-lifecycle.d.ts +32 -0
  46. package/lib/browser-electron/maintenance-lifecycle.js +67 -0
  47. package/lib/browser-electron/maintenance-route.d.ts +18 -0
  48. package/lib/browser-electron/maintenance-route.js +75 -0
  49. package/lib/browser-electron/paths.d.ts +4 -0
  50. package/lib/browser-electron/paths.js +19 -0
  51. package/lib/browser-electron/process.d.ts +14 -0
  52. package/lib/browser-electron/process.js +24 -0
  53. package/lib/browser-electron/provider.d.ts +16 -9
  54. package/lib/browser-electron/provider.js +87 -18
  55. package/lib/browser-electron/remote-host.js +22 -20
  56. package/lib/browser-electron/runtime-route.d.ts +3 -5
  57. package/lib/browser-electron/runtime-status.d.ts +27 -13
  58. package/lib/browser-electron/runtime-status.js +28 -6
  59. package/lib/browser-electron/settings-route.d.ts +5 -18
  60. package/lib/browser-electron/settings-route.js +4 -14
  61. package/lib/browser-electron/settings-store.d.ts +28 -0
  62. package/lib/browser-electron/settings-store.js +32 -2
  63. package/lib/browser-electron/sidebar-only-host.d.ts +36 -0
  64. package/lib/browser-electron/sidebar-only-host.js +192 -0
  65. package/lib/browser-electron/system-browser.d.ts +6 -11
  66. package/lib/browser-electron/system-browser.js +29 -24
  67. package/lib/browser-electron/timing.d.ts +8 -0
  68. package/lib/browser-electron/timing.js +13 -0
  69. package/lib/browser-electron/windows-system.d.ts +3 -0
  70. package/lib/browser-electron/windows-system.js +19 -0
  71. package/lib/tool-browser/index.js +1045 -7
  72. package/lib/tool-browser/page-probe.d.ts +86 -0
  73. package/lib/tool-browser/page-probe.js +460 -0
  74. package/package.json +5 -3
  75. package/scripts/run-tests.mjs +32 -0
  76. package/scripts/verify-preview-route.mjs +19 -1
  77. package/scripts/verify-runtime-status.mjs +14 -0
  78. package/skills/dsh-builtin-browser/SKILL.md +64 -0
  79. package/skills/dsh-builtin-browser/references/batch.md +23 -0
  80. package/skills/dsh-builtin-browser/references/deliver.md +31 -0
  81. package/skills/dsh-builtin-browser/references/locate.md +11 -0
  82. package/skills/dsh-builtin-browser/references/recover.md +11 -0
  83. package/skills/dsh-builtin-browser/references/verify.md +13 -0
  84. package/src/browser/runtime.ts +11 -0
  85. package/src/browser/types.ts +19 -0
  86. package/src/browser-electron/authenticated-route.ts +56 -0
  87. package/src/browser-electron/automatic-maintenance.ts +414 -0
  88. package/src/browser-electron/bridge-auto.ts +158 -0
  89. package/src/browser-electron/bridge-connection.ts +2 -4
  90. package/src/browser-electron/bridge-endpoint.ts +8 -18
  91. package/src/browser-electron/bridge-install.ts +253 -0
  92. package/src/browser-electron/bridge-maintenance.ts +161 -0
  93. package/src/browser-electron/bridge-status.ts +76 -26
  94. package/src/browser-electron/desktop-bridge-host.ts +60 -26
  95. package/src/browser-electron/desktop-identity.ts +18 -9
  96. package/src/browser-electron/electron-provision.ts +35 -14
  97. package/src/browser-electron/entry.ts +152 -62
  98. package/src/browser-electron/ephemeral-profile.ts +65 -28
  99. package/src/browser-electron/history-store.ts +2 -2
  100. package/src/browser-electron/host-main.ts +40 -34
  101. package/src/browser-electron/http-body.ts +42 -0
  102. package/src/browser-electron/json-reply.ts +18 -3
  103. package/src/browser-electron/maintenance-broker.ts +142 -0
  104. package/src/browser-electron/maintenance-lifecycle.ts +86 -0
  105. package/src/browser-electron/maintenance-route.ts +64 -0
  106. package/src/browser-electron/paths.ts +21 -0
  107. package/src/browser-electron/process.ts +23 -0
  108. package/src/browser-electron/provider.ts +106 -22
  109. package/src/browser-electron/remote-host.ts +23 -23
  110. package/src/browser-electron/runtime-route.ts +3 -5
  111. package/src/browser-electron/runtime-status.ts +56 -19
  112. package/src/browser-electron/settings-route.ts +9 -32
  113. package/src/browser-electron/settings-store.ts +59 -3
  114. package/src/browser-electron/sidebar-only-host.ts +199 -0
  115. package/src/browser-electron/system-browser.ts +26 -23
  116. package/src/browser-electron/timing.ts +16 -0
  117. package/src/browser-electron/windows-system.ts +23 -0
  118. package/src/tool-browser/index.ts +995 -10
  119. 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.8",
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",
@@ -49,7 +50,7 @@
49
50
  },
50
51
  "scripts": {
51
52
  "build": "tsc -p tsconfig.json",
52
- "test": "tsc -p tsconfig.json && node --test \"tests/*.test.mjs\"",
53
+ "test": "node scripts/run-tests.mjs",
53
54
  "prepack": "npm run build"
54
55
  },
55
56
  "keywords": [
@@ -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
  }
@@ -0,0 +1,32 @@
1
+ #!/usr/bin/env node
2
+ /** Build and run tests inside an explicit, marked bridge-installer boundary. */
3
+ import { spawn } from 'node:child_process'
4
+ import { readdirSync } from 'node:fs'
5
+ import { createRequire } from 'node:module'
6
+ import { join } from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { createInstallerSandbox } from '../tests/helpers/installer-sandbox.mjs'
9
+
10
+ const repo = fileURLToPath(new URL('..', import.meta.url))
11
+ const require = createRequire(new URL('../package.json', import.meta.url))
12
+ const sandbox = createInstallerSandbox()
13
+ const environment = sandbox.env()
14
+ function run(argv) {
15
+ return new Promise(resolve => {
16
+ const child = spawn(process.execPath, argv, { cwd: repo, env: environment, stdio: 'inherit', windowsHide: true })
17
+ child.once('error', error => { console.error(error); resolve(1) })
18
+ child.once('close', code => resolve(code ?? 1))
19
+ })
20
+ }
21
+
22
+ let code = await run([require.resolve('typescript/bin/tsc'), '-p', join(repo, 'tsconfig.json')])
23
+ if (code === 0) {
24
+ const requested = process.argv.slice(2)
25
+ const files = requested.length === 0
26
+ ? readdirSync(join(repo, 'tests')).filter(name => name.endsWith('.test.mjs')).sort().map(name => join(repo, 'tests', name))
27
+ : requested
28
+ code = await run(['--test', ...files])
29
+ }
30
+ if (code === 0) sandbox.close()
31
+ else console.error(`Failed-test sandbox retained for diagnosis: ${sandbox.root}`)
32
+ process.exitCode = code
@@ -47,7 +47,25 @@ async function connect(wsUrl) {
47
47
  }
48
48
  }
49
49
 
50
- const CHROME = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
50
+ // No hard-coded browser path: this script ships in the package, and "C:/Program Files/..." is only
51
+ // right on one machine. DSH_BROWSER_CHROME_PATH wins; otherwise the usual Windows locations are probed
52
+ // and the script says so instead of failing to spawn a missing binary.
53
+ const CHROME = (() => {
54
+ const override = process.env.DSH_BROWSER_CHROME_PATH
55
+ if (override !== undefined && override !== '') return override
56
+ const roots = [process.env['PROGRAMFILES'], process.env['PROGRAMFILES(X86)'], process.env.LOCALAPPDATA]
57
+ .filter(root => typeof root === 'string' && root !== '')
58
+ const candidates = roots.flatMap(root => [
59
+ join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'),
60
+ join(root, 'Microsoft', 'Edge', 'Application', 'msedge.exe'),
61
+ ])
62
+ const found = candidates.find(candidate => existsSync(candidate))
63
+ if (found === undefined) {
64
+ console.error('verify-preview-route: no Chrome or Edge found; set DSH_BROWSER_CHROME_PATH to a Chromium binary')
65
+ process.exit(2)
66
+ }
67
+ return found
68
+ })()
51
69
  const profile = mkdtempSync(join(tmpdir(), 'dsh-e2e-preview-'))
52
70
  const portFile = join(profile, 'DevToolsActivePort')
53
71
  const child = spawn(CHROME, [
@@ -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)