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.
- package/CHANGELOG.md +82 -0
- package/README.en.md +67 -99
- package/README.md +67 -100
- package/client.js +381 -322
- package/desktop-bridge/install.mjs +122 -33
- package/desktop-bridge/plugin-browser-bridge.js +9 -4
- package/docs/tool-reference.md +20 -1
- package/lib/browser/runtime.d.ts +3 -1
- package/lib/browser/runtime.js +9 -0
- package/lib/browser/types.d.ts +42 -0
- package/lib/browser-electron/authenticated-route.d.ts +27 -0
- package/lib/browser-electron/authenticated-route.js +39 -0
- package/lib/browser-electron/bridge-endpoint.js +7 -0
- package/lib/browser-electron/bridge-install.d.ts +48 -0
- package/lib/browser-electron/bridge-install.js +98 -0
- package/lib/browser-electron/bridge-status.js +21 -2
- package/lib/browser-electron/desktop-bridge-host.d.ts +7 -4
- package/lib/browser-electron/desktop-bridge-host.js +36 -15
- package/lib/browser-electron/electron-provision.d.ts +1 -1
- package/lib/browser-electron/electron-provision.js +31 -11
- package/lib/browser-electron/entry.js +84 -8
- package/lib/browser-electron/host-main.js +48 -27
- package/lib/browser-electron/provider.d.ts +9 -2
- package/lib/browser-electron/provider.js +76 -6
- package/lib/browser-electron/remote-host.js +4 -4
- package/lib/browser-electron/runtime-route.d.ts +3 -5
- package/lib/browser-electron/runtime-status.js +4 -2
- package/lib/browser-electron/settings-route.d.ts +5 -18
- package/lib/browser-electron/settings-route.js +4 -14
- package/lib/browser-electron/settings-store.d.ts +17 -0
- package/lib/browser-electron/settings-store.js +24 -0
- package/lib/browser-electron/system-browser.d.ts +5 -2
- package/lib/browser-electron/system-browser.js +12 -4
- package/lib/tool-browser/index.js +1041 -4
- package/lib/tool-browser/page-probe.d.ts +86 -0
- package/lib/tool-browser/page-probe.js +460 -0
- package/package.json +4 -2
- package/scripts/verify-runtime-status.mjs +14 -0
- package/skills/dsh-builtin-browser/SKILL.md +64 -0
- package/skills/dsh-builtin-browser/references/batch.md +23 -0
- package/skills/dsh-builtin-browser/references/deliver.md +31 -0
- package/skills/dsh-builtin-browser/references/locate.md +11 -0
- package/skills/dsh-builtin-browser/references/recover.md +11 -0
- package/skills/dsh-builtin-browser/references/verify.md +13 -0
- package/src/browser/runtime.ts +11 -0
- package/src/browser/types.ts +19 -0
- package/src/browser-electron/authenticated-route.ts +56 -0
- package/src/browser-electron/bridge-endpoint.ts +7 -0
- package/src/browser-electron/bridge-install.ts +122 -0
- package/src/browser-electron/bridge-status.ts +22 -2
- package/src/browser-electron/desktop-bridge-host.ts +33 -15
- package/src/browser-electron/electron-provision.ts +30 -12
- package/src/browser-electron/entry.ts +76 -8
- package/src/browser-electron/host-main.ts +41 -22
- package/src/browser-electron/provider.ts +90 -6
- package/src/browser-electron/remote-host.ts +4 -4
- package/src/browser-electron/runtime-route.ts +3 -5
- package/src/browser-electron/runtime-status.ts +4 -2
- package/src/browser-electron/settings-route.ts +9 -32
- package/src/browser-electron/settings-store.ts +39 -0
- package/src/browser-electron/system-browser.ts +9 -3
- package/src/tool-browser/index.ts +991 -7
- package/src/tool-browser/page-probe.ts +474 -0
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
*/
|
|
69
69
|
import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
70
70
|
import { execFileSync, spawn } from 'node:child_process'
|
|
71
|
-
import { dirname, join } from 'node:path'
|
|
71
|
+
import { dirname, join, resolve } from 'node:path'
|
|
72
72
|
|
|
73
73
|
const DEFAULT_INSTALL = findDefaultInstall()
|
|
74
74
|
/**
|
|
@@ -118,30 +118,63 @@ function withoutOurSnippet(text) {
|
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
/**
|
|
121
|
-
*
|
|
122
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
125
|
-
*
|
|
126
|
-
*
|
|
127
|
-
|
|
128
|
-
|
|
121
|
+
* Select only the GUI processes owned by this installation.
|
|
122
|
+
* Native DSH CLI processes share the same executable but run JavaScript in Node mode.
|
|
123
|
+
* @param rows - the process table, including parent ids for the installer's ancestry.
|
|
124
|
+
* @param root - verified Desktop installation directory.
|
|
125
|
+
* @param selfPid - the installer process.
|
|
126
|
+
* @returns GUI and Chromium helper process ids.
|
|
127
|
+
*/
|
|
128
|
+
function selectShellProcesses(rows, root, selfPid) {
|
|
129
|
+
const byPid = new Map(rows.map(row => [row.ProcessId, row]))
|
|
130
|
+
const ancestors = new Set()
|
|
131
|
+
let cursor = selfPid
|
|
132
|
+
while (typeof cursor === 'number' && cursor > 0 && !ancestors.has(cursor)) {
|
|
133
|
+
ancestors.add(cursor)
|
|
134
|
+
cursor = byPid.get(cursor)?.ParentProcessId
|
|
135
|
+
}
|
|
136
|
+
const expectedExe = resolve(root, 'DeepSeek Harness.exe').toLowerCase()
|
|
137
|
+
const selected = []
|
|
138
|
+
for (const row of rows) {
|
|
139
|
+
if (String(row.Name ?? '').toLowerCase() !== 'deepseek harness.exe') continue
|
|
140
|
+
if (typeof row.ExecutablePath !== 'string' || row.ExecutablePath === '') {
|
|
141
|
+
throw new Error('could not identify a running DeepSeek Harness process; refusing to close or patch the application')
|
|
142
|
+
}
|
|
143
|
+
if (resolve(row.ExecutablePath).toLowerCase() !== expectedExe) continue
|
|
144
|
+
if (!Number.isSafeInteger(row.ProcessId) || row.ProcessId <= 0 || typeof row.CommandLine !== 'string') {
|
|
145
|
+
throw new Error('the Desktop process table is incomplete; refusing to close or patch the application')
|
|
146
|
+
}
|
|
147
|
+
if (row.ProcessId === selfPid) continue
|
|
148
|
+
const nodeMode = /(?:^|\s)--expose-internals(?:\s|$)|\.[cm]?js(?:"|\s|$)|(?:^|\s)(?:--eval|--print|--input-type)(?:=|\s|$)|(?:^|\s)-(?:e|p)(?:\s|$)/i.test(row.CommandLine)
|
|
149
|
+
if (nodeMode) continue
|
|
150
|
+
if (ancestors.has(row.ProcessId)) {
|
|
151
|
+
throw new Error('the installer is a child of DSH Desktop; run this command from a separate terminal with Node.js')
|
|
152
|
+
}
|
|
153
|
+
selected.push(row.ProcessId)
|
|
154
|
+
}
|
|
155
|
+
return selected
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Read the complete process table so ancestry is available before any process is closed.
|
|
160
|
+
* Enumeration failure refuses the install rather than treating the shell as stopped.
|
|
161
|
+
* @param root - verified Desktop installation directory.
|
|
162
|
+
* @returns GUI and Chromium helper process ids.
|
|
129
163
|
*/
|
|
130
164
|
function shellProcesses(root) {
|
|
131
165
|
const text = runCapture('powershell.exe', [
|
|
132
166
|
'-NoProfile', '-NonInteractive', '-Command',
|
|
133
|
-
'Get-CimInstance Win32_Process -
|
|
134
|
-
+ 'Select-Object ProcessId,ExecutablePath | ConvertTo-Json -Compress',
|
|
167
|
+
'Get-CimInstance Win32_Process -ErrorAction Stop | '
|
|
168
|
+
+ 'Select-Object ProcessId,ParentProcessId,Name,ExecutablePath,CommandLine | ConvertTo-Json -Compress',
|
|
135
169
|
])
|
|
136
|
-
if (text === undefined || text.trim() === '')
|
|
170
|
+
if (text === undefined || text.trim() === '') throw new Error('could not enumerate Desktop processes')
|
|
137
171
|
let parsed
|
|
138
|
-
try { parsed = JSON.parse(text) } catch {
|
|
172
|
+
try { parsed = JSON.parse(text) } catch { throw new Error('could not parse the Desktop process table') }
|
|
139
173
|
const rows = Array.isArray(parsed) ? parsed : [parsed]
|
|
140
|
-
|
|
141
|
-
.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
.map(row => row.ProcessId)
|
|
174
|
+
if (rows.length === 0 || rows.some(row => row === null || typeof row !== 'object'
|
|
175
|
+
|| !Number.isSafeInteger(row.ProcessId) || !Number.isSafeInteger(row.ParentProcessId)
|
|
176
|
+
|| typeof row.Name !== 'string')) throw new Error('the Desktop process table is invalid')
|
|
177
|
+
return selectShellProcesses(rows, root, process.pid)
|
|
145
178
|
}
|
|
146
179
|
|
|
147
180
|
/**
|
|
@@ -173,7 +206,7 @@ async function stopShell(root, graceMs) {
|
|
|
173
206
|
if (before.length === 0) return true
|
|
174
207
|
console.log(` closing DSH Desktop (${before.length} process(es))…`)
|
|
175
208
|
// No /F: this is a normal window close, so the shell can flush and prompt.
|
|
176
|
-
runCapture('taskkill.exe', ['/PID',
|
|
209
|
+
runCapture('taskkill.exe', before.flatMap(pid => ['/PID', String(pid)]))
|
|
177
210
|
const deadline = Date.now() + graceMs
|
|
178
211
|
while (Date.now() < deadline) {
|
|
179
212
|
if (shellProcesses(root).length === 0) return true
|
|
@@ -182,7 +215,7 @@ async function stopShell(root, graceMs) {
|
|
|
182
215
|
const left = shellProcesses(root)
|
|
183
216
|
if (left.length > 0) {
|
|
184
217
|
console.log(` ${left.length} process(es) still running after ${String(graceMs)} ms; forcing`)
|
|
185
|
-
runCapture('taskkill.exe', ['/
|
|
218
|
+
runCapture('taskkill.exe', [...left.flatMap(pid => ['/PID', String(pid)]), '/F'])
|
|
186
219
|
const forcedBy = Date.now() + 15_000
|
|
187
220
|
while (Date.now() < forcedBy) {
|
|
188
221
|
if (shellProcesses(root).length === 0) return true
|
|
@@ -207,7 +240,13 @@ function startShell(root) {
|
|
|
207
240
|
return false
|
|
208
241
|
}
|
|
209
242
|
try {
|
|
210
|
-
const
|
|
243
|
+
const env = { ...process.env }
|
|
244
|
+
for (const key of Object.keys(env)) {
|
|
245
|
+
if (key.toUpperCase() === 'ELECTRON_RUN_AS_NODE') delete env[key]
|
|
246
|
+
}
|
|
247
|
+
const child = spawn(exe, [], { detached: true, stdio: 'ignore', cwd: root, env })
|
|
248
|
+
child.on('error', error => { console.error('could not start DSH Desktop: ' + String(error)) })
|
|
249
|
+
if (child.pid === undefined) return false
|
|
211
250
|
child.unref()
|
|
212
251
|
console.log(` started ${exe}`)
|
|
213
252
|
return true
|
|
@@ -218,6 +257,14 @@ function startShell(root) {
|
|
|
218
257
|
}
|
|
219
258
|
|
|
220
259
|
const args = process.argv.slice(2)
|
|
260
|
+
// Identity only, no side effects: the panel and a human both need a way to ask "would this work"
|
|
261
|
+
// without closing the shell first.
|
|
262
|
+
if (args.includes('--preflight')) {
|
|
263
|
+
const target = args.find(part => !part.startsWith('--')) || ''
|
|
264
|
+
const verdict = verifyDesktopIdentity(target)
|
|
265
|
+
console.log(JSON.stringify({ target, ...verdict }))
|
|
266
|
+
process.exit(verdict.ok ? 0 : 1)
|
|
267
|
+
}
|
|
221
268
|
const revert = args.includes('--revert')
|
|
222
269
|
/**
|
|
223
270
|
* Close DSH, install, then start it again — all in THIS process.
|
|
@@ -594,9 +641,40 @@ function verifyDesktopIdentity(root) {
|
|
|
594
641
|
|
|
595
642
|
let manifestText
|
|
596
643
|
if (archivePresent) {
|
|
597
|
-
|
|
644
|
+
let bytes = readAsarEntry(archive, 'package.json')
|
|
645
|
+
if (bytes === undefined) {
|
|
646
|
+
// Some builds ship package.json OUTSIDE the archive (marked `unpacked`): the real file is
|
|
647
|
+
// then beside it, and reading it there is the honest answer rather than "cannot be read".
|
|
648
|
+
try { bytes = readFileSync(join(resources, 'app.asar.unpacked', 'package.json')) } catch { bytes = undefined }
|
|
649
|
+
}
|
|
598
650
|
if (bytes === undefined) {
|
|
599
|
-
|
|
651
|
+
// Evidence that does not need to read the archive at all. Inside Electron, `fs` treats a
|
|
652
|
+
// `.asar` path as a virtual directory, so a raw read of it returns the wrong thing and finds
|
|
653
|
+
// nothing — measured when the panel's button ran this file under the desktop shell. The
|
|
654
|
+
// product's own executable beside the archive is proof enough that this is DSH Desktop.
|
|
655
|
+
const exeNames = ['DeepSeek Harness.exe', 'DSH Desktop.exe']
|
|
656
|
+
const exeFound = exeNames.find(name => existsSync(join(root, name)))
|
|
657
|
+
if (exeFound !== undefined) {
|
|
658
|
+
return { ok: true, layout: 'packed', packageName: String(rule.packageNames?.[0] ?? ''), version: 'unknown' }
|
|
659
|
+
}
|
|
660
|
+
// Last resort, for a plain node run: the archive header could not be parsed. The rule is a name,
|
|
661
|
+
// and a name that appears in the archive is evidence enough to proceed — the alternative is
|
|
662
|
+
// refusing an install that is obviously there.
|
|
663
|
+
const names = Array.isArray(rule.packageNames) ? rule.packageNames.map(String) : []
|
|
664
|
+
let probe = ''
|
|
665
|
+
try {
|
|
666
|
+
const fd = openSync(archive, 'r')
|
|
667
|
+
const size = 8 * 1024 * 1024
|
|
668
|
+
const buf = Buffer.alloc(size)
|
|
669
|
+
const read = readSync(fd, buf, 0, size, 0)
|
|
670
|
+
closeSync(fd)
|
|
671
|
+
probe = buf.subarray(0, read).toString('latin1')
|
|
672
|
+
} catch { probe = '' }
|
|
673
|
+
const found = names.find(name => name !== '' && probe.includes(name))
|
|
674
|
+
if (found === undefined) {
|
|
675
|
+
return { ok: false, reason: `${archive} could not be read and does not name ${names.join(' / ')}` }
|
|
676
|
+
}
|
|
677
|
+
return { ok: true, layout: 'packed', packageName: found, version: 'unknown' }
|
|
600
678
|
}
|
|
601
679
|
manifestText = bytes.toString('utf8')
|
|
602
680
|
} else {
|
|
@@ -649,10 +727,17 @@ if (!identity.ok) {
|
|
|
649
727
|
// both arrangements measured in issue #36 died at that moment. Doing it here keeps the whole
|
|
650
728
|
// sequence inside one front-facing process.
|
|
651
729
|
let shellStopped = false
|
|
652
|
-
if (
|
|
730
|
+
if (!revert && existsSync(asarPath)) {
|
|
731
|
+
const checked = validateArchive(asarPath)
|
|
732
|
+
if (!checked.ok) {
|
|
733
|
+
console.error(`refusing to rebuild from an archive that cannot be verified: ${checked.reason}`)
|
|
734
|
+
process.exit(1)
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
if (restart) {
|
|
653
738
|
if (!assumeYes) {
|
|
654
739
|
console.log('')
|
|
655
|
-
console.log(
|
|
740
|
+
console.log(`--restart will close DSH Desktop, ${revert ? 'remove' : 'install'} the bridge, and start it again.`)
|
|
656
741
|
console.log('Any unsaved work in a conversation is lost. Re-run with --yes to skip this notice.')
|
|
657
742
|
console.log('')
|
|
658
743
|
try {
|
|
@@ -667,13 +752,23 @@ if (restart && !revert) {
|
|
|
667
752
|
process.exit(1)
|
|
668
753
|
}
|
|
669
754
|
}
|
|
670
|
-
|
|
755
|
+
try {
|
|
756
|
+
shellStopped = await stopShell(installRoot, 20_000)
|
|
757
|
+
} catch (error) {
|
|
758
|
+
console.error('could not safely stop DSH Desktop: ' + String(error))
|
|
759
|
+
process.exit(1)
|
|
760
|
+
}
|
|
671
761
|
if (!shellStopped) {
|
|
672
762
|
console.error('DSH Desktop did not exit, so the archive cannot be replaced.')
|
|
673
763
|
console.error('Close it yourself and run this again without --restart.')
|
|
674
764
|
process.exit(1)
|
|
675
765
|
}
|
|
676
766
|
}
|
|
767
|
+
process.once('exit', () => {
|
|
768
|
+
if (restart && shellStopped && startShell(installRoot)) {
|
|
769
|
+
console.log('DSH Desktop was restarted.')
|
|
770
|
+
}
|
|
771
|
+
})
|
|
677
772
|
|
|
678
773
|
// The archive wins whenever it exists, so ITS presence — not the absence of the
|
|
679
774
|
// directory — decides the layout. After a desktop update the archive is back
|
|
@@ -849,12 +944,6 @@ console.log(`installed bridge into ${appDir}`)
|
|
|
849
944
|
console.log(` module: ${bridgeTarget}`)
|
|
850
945
|
console.log(` patch: ${mainPath} (+${SNIPPET.split('\n').length} lines)`)
|
|
851
946
|
installCliCompatibility()
|
|
852
|
-
if (restart
|
|
853
|
-
// Started detached and unref'd: this process exits on the next line, and a child that died with
|
|
854
|
-
// its parent would leave the user with nothing running — the trap the wait-for-exit daemons hit.
|
|
855
|
-
if (startShell(installRoot)) {
|
|
856
|
-
console.log('DSH Desktop was restarted; the bridge is active.')
|
|
857
|
-
}
|
|
858
|
-
} else {
|
|
947
|
+
if (!restart) {
|
|
859
948
|
console.log('restart DSH Desktop to activate it.')
|
|
860
949
|
}
|
|
@@ -38,6 +38,7 @@ import { app, webContents } from 'electron'
|
|
|
38
38
|
* conversation would have brought the page back.
|
|
39
39
|
*/
|
|
40
40
|
const PANEL_NOT_DISPLAYED = 'panel-not-displayed'
|
|
41
|
+
const PANEL_INITIALIZING = 'panel-initializing'
|
|
41
42
|
|
|
42
43
|
/**
|
|
43
44
|
* An Error carrying a stable code, so the code survives the socket as a field rather than as text a
|
|
@@ -265,7 +266,7 @@ async function sendCdp(id, method, params) {
|
|
|
265
266
|
* @param url - address to load when a panel has to be opened; `null` to only READ.
|
|
266
267
|
* @returns the renderer's verdict, normalized so a malformed answer is a named failure.
|
|
267
268
|
*/
|
|
268
|
-
async function evaluatePanelService(shellId, sessionId, url) {
|
|
269
|
+
async function evaluatePanelService(shellId, sessionId, url, tabId) {
|
|
269
270
|
// `null` means read-only. This distinction is not cosmetic: `openPanel` CREATES a tab when the
|
|
270
271
|
// conversation has none, so polling with it turned a 20-second wait into one empty tab every
|
|
271
272
|
// 250ms — the "it opens a pile of blank pages at once" report. A wait must never be a write.
|
|
@@ -273,7 +274,7 @@ async function evaluatePanelService(shellId, sessionId, url) {
|
|
|
273
274
|
const call = reading
|
|
274
275
|
// `panelGuest` reports state, not success, so the read form supplies the verdict itself: a
|
|
275
276
|
// conversation with no panel yet is a legitimate answer to "what do you have", not a failure.
|
|
276
|
-
? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}) })`
|
|
277
|
+
? `JSON.stringify({ ok: true, ...api.panelGuest(${JSON.stringify(String(sessionId))}, ${JSON.stringify(tabId ?? null)}) })`
|
|
277
278
|
: `JSON.stringify(api.openPanel(${JSON.stringify(String(sessionId))}, ${JSON.stringify(String(url ?? ''))}))`
|
|
278
279
|
const expression = `(() => {
|
|
279
280
|
const api = globalThis.__dshBuiltinBrowser;
|
|
@@ -321,6 +322,7 @@ async function evaluatePanelService(shellId, sessionId, url) {
|
|
|
321
322
|
panel: parsed?.panel === true,
|
|
322
323
|
created: parsed?.created === true,
|
|
323
324
|
guestId: typeof parsed?.guestId === 'number' && Number.isFinite(parsed.guestId) ? parsed.guestId : null,
|
|
325
|
+
...typeof parsed?.tabId === 'string' ? { tabId: parsed.tabId } : {},
|
|
324
326
|
url: typeof parsed?.url === 'string' ? parsed.url : '',
|
|
325
327
|
// A refusal carries what the renderer found, so the reason is actionable rather than a guess.
|
|
326
328
|
found: parsed?.found === undefined ? undefined : parsed.found,
|
|
@@ -492,10 +494,11 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
492
494
|
throw new Error('this host supplied no conversation id, so its own panel cannot be identified')
|
|
493
495
|
}
|
|
494
496
|
|
|
497
|
+
let tabId
|
|
495
498
|
const ask = async (withUrl) => {
|
|
496
499
|
// `null` reads, a string places or navigates. Every round of the wait below uses the READ
|
|
497
500
|
// form, because a wait must never create anything.
|
|
498
|
-
const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null)
|
|
501
|
+
const answer = await evaluatePanelService(shell.id, owner, withUrl ? url : null, tabId)
|
|
499
502
|
if (answer.ok !== true) {
|
|
500
503
|
// Carry the renderer's own findings into the failure: it is the side that can see why the
|
|
501
504
|
// lookup missed, and a bare "not mounted" leaves the next reader guessing between a real
|
|
@@ -513,6 +516,7 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
513
516
|
// me the page" and "let me look at it", and keeping the preview off this path is what stops a
|
|
514
517
|
// read-only action from moving the reader's layout.
|
|
515
518
|
const first = await ask(url !== '')
|
|
519
|
+
tabId = first.tabId
|
|
516
520
|
if (first.guestId !== null) {
|
|
517
521
|
claims.set(first.guestId, owner)
|
|
518
522
|
if (!guestShows(first.guestId, url)) {
|
|
@@ -555,7 +559,8 @@ async function handle(request) { const op = String(request?.op ?? '')
|
|
|
555
559
|
}
|
|
556
560
|
return { ok: true, created: true, id: polled.guestId, via: 'panel', owner }
|
|
557
561
|
}
|
|
558
|
-
throw
|
|
562
|
+
throw codedError(
|
|
563
|
+
PANEL_INITIALIZING,
|
|
559
564
|
'this conversation\'s browser panel produced no page within its budget '
|
|
560
565
|
+ '(the shell placed no guest in this conversation\'s own sidebar)',
|
|
561
566
|
)
|
package/docs/tool-reference.md
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
# 工具参考
|
|
2
2
|
|
|
3
|
-
全部
|
|
3
|
+
全部 48 个 `dsh_browser_*` 工具。守卫列:✅ 表示该动作受 `dsh_browser_restrict` 白名单约束;**「– 豁免」表示无论白名单怎么写都不拦截**(豁免集合为 `READ_ONLY_TOOLS`,`src/tool-browser/index.ts` 导出:**只观察的工具** —— `snapshot`/`a11y`/`content`/`scrape`/`screenshot`/`get_value`/`wait`/`challenge`/`list_tabs`/`session`/`history`/`visited` —— 加上 **解除限制 / 从坏状态恢复的工具** `restrict`/`reset_session`/`reset`;`restrict` 在其中,否则限制到空的任务再也解不开);**「–」表示该工具只观察、不做动作**,故没有可拦的东西。两者之外的工具都受白名单约束 —— 例如 `dsh_browser_close_tab`、`dsh_browser_auth` 都不属于豁免集合(`dsh_browser_auth` 的 `restore` 会向任意域写 cookie,是动作,不是观察)。
|
|
4
|
+
|
|
5
|
+
## 批量、观测与断言(待发布)
|
|
6
|
+
|
|
7
|
+
页面探针收集控制台、网络和页面脚本弹窗记录,拖拽与悬停通过浏览器的 CDP 输入通道执行。`fetch` 和 `XHR` 记录包含状态码,资源计时记录的状态码为 0。
|
|
8
|
+
|
|
9
|
+
| 工具 | 参数 | 输出 | 守卫 | 说明 |
|
|
10
|
+
| --- | --- | --- | --- | --- |
|
|
11
|
+
| `dsh_browser_do` | `steps`(必填,最多 40), `timeoutMs?`, `autoDismiss?` | `{ ok, completed, total, stoppedAt?, reason?, log[] }` | ✅ | **一次调用跑一串步骤**,失败即停并指出第几步。步骤键(每步恰好一个):`open{url}` `tap{target}` `field{target,text}` `type{text}` `key{key}` `scroll{deltaY}` `sleep_ms{ms}` `wait_text{text}` `wait_gone{text}` `wait_url{url}` `wait_idle{}` `eval{script}` `check{selector|text|url|js}`。等待基于条件而不是睡眠;`tap` 的目标被 cookie 横幅/弹窗盖住时先把它关掉 |
|
|
12
|
+
| `dsh_browser_console` | `limit?`(默认 20,上限 100), `filter?`, `clear?` | `{ entries[] }` | – 豁免 | 页面控制台最新若干行(含 level);先 `clear:true` 可只看之后发生的事 |
|
|
13
|
+
| `dsh_browser_network` | `limit?`, `filter?`, `onlyFailures?`, `clear?` | `{ entries[] }` | – 豁免 | fetch/XHR/资源计时行:方法、状态、类型、地址、耗时;`onlyFailures` 保留 0 与 >=400 |
|
|
14
|
+
| `dsh_browser_wait_for_response` | `urlContains`(必填), `status?`, `timeoutMs?` | `{ matched, reason, entry? }` | – 豁免 | 等**本次调用之后**到达的响应(可按状态过滤);回答"提交到底有没有到服务器",截图答不了这个 |
|
|
15
|
+
| `dsh_browser_assert` | `selector?` `text?` `url?` `js?`(至少一个) | `{ pass, checks[] }` | – 豁免 | 一次断言多件事,逐条给证据;"点到了"和"表单接受了"是两回事,重试前应先断言 |
|
|
16
|
+
| `dsh_browser_dialog` | `policy?`(native/accept/dismiss), `limit?` | `{ policy, dialogs[] }` | ✅ | 默认保留网页原生弹窗;显式选择 accept 或 dismiss 后记录并自动应答 alert/confirm/prompt,选择 native 恢复原生处理 |
|
|
17
|
+
| `dsh_browser_drag` | `fromX` `fromY` `toX` `toY`(必填), `steps?` | `{ ok, reason }` | ✅ | 通过 CDP 按下鼠标、按住移动并释放,操作滑块、排序列表、HTML5 拖放和画布。坐标使用当前视口的 CSS 像素,操作后可用 `assert` 核对控件值、顺序或页面结果 |
|
|
18
|
+
| `dsh_browser_hover` | `target`(必填), `settleMs?` | `{ hovered, at }` | ✅ | 将浏览器指针移到目标中心,触发 CSS 悬停样式及鼠标事件。目标支持 `{by, value}`,可按 css、text 或 xpath 定位 |
|
|
19
|
+
| `dsh_browser_doctor` | – | `{ report }` | – 豁免 | 自检:URL、进行中的请求数、静默时长、探针已装、三类缓冲各多少条、本任务被限制掉哪些工具 |
|
|
20
|
+
| `dsh_browser_help` | `topic?` | `{ text }` | – 豁免 | 主题索引(locate/wait/batch/dialogs/network/verify/recovery/limits)或单篇正文 |
|
|
21
|
+
|
|
22
|
+
`tap` 的 `target` 与 `click` 相同:一个字符串按可见文本匹配,或 `{by, value}`(`css`/`text`/`xpath`)。
|
|
4
23
|
|
|
5
24
|
## 页面与导航
|
|
6
25
|
|
package/lib/browser/runtime.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { Context, Service } from '@deepseek-ai/cordis';
|
|
10
10
|
import z from '@deepseek-ai/schemastery';
|
|
11
|
-
import type { BrowserA11yRequest, BrowserA11yResult, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserElementTarget, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserChallenge, ExportedCookie, VisitedPage } from './types.js';
|
|
11
|
+
import type { BrowserA11yRequest, BrowserA11yResult, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserElementTarget, BrowserExecuteRequest, BrowserPageOperationRequest, BrowserExecuteResult, BrowserFillRequest, BrowserFillResult, BrowserGetValueRequest, BrowserGetValueResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScrapeRequest, BrowserScrapeResult, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSelectRequest, BrowserSelectResult, BrowserSessionId, BrowserSetValueRequest, BrowserSetValueResult, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserChallenge, ExportedCookie, VisitedPage } from './types.js';
|
|
12
12
|
export { BrowserError, } from './types.js';
|
|
13
13
|
export type { BrowserA11yNode, BrowserA11yRequest, BrowserA11yResult, BrowserChallenge, BrowserCheckRequest, BrowserClearRequest, BrowserClickRequest, BrowserClickSequenceRequest, BrowserClickSequenceResult, BrowserContentFormat, BrowserElementTarget, BrowserGetValueRequest, BrowserGetValueResult, BrowserScrapeField, BrowserScrapeRequest, BrowserScrapeResult, BrowserSelectRequest, BrowserSelectResult, BrowserSetValueRequest, BrowserSetValueResult, BrowserWaitRequest, BrowserWaitResult, BrowserScrollRequest, BrowserKeyRequest, BrowserContentRequest, BrowserContentResult, BrowserDownloadRequest, BrowserExecuteRequest, BrowserExecuteResult, BrowserFillField, BrowserFillRequest, BrowserFillResult, BrowserHistoryEntry, BrowserNavigateRequest, BrowserOpenRequest, BrowserPreviewFrame, BrowserProvider, BrowserScreenshotRequest, BrowserScreenshotResult, BrowserSessionId, BrowserSnapshotElement, BrowserSnapshotResult, BrowserTab, BrowserTypeRequest, ExportedCookie, } from './types.js';
|
|
14
14
|
declare module '@deepseek-ai/cordis' {
|
|
@@ -68,6 +68,8 @@ export declare class BrowserRuntime extends Service {
|
|
|
68
68
|
navigate(session: BrowserSessionId, request: BrowserNavigateRequest, signal?: AbortSignal): Promise<void>;
|
|
69
69
|
/** Execute JS in the session's page context through the selected provider. */
|
|
70
70
|
execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
|
|
71
|
+
/** Execute one provider-owned page operation with validated operation names. */
|
|
72
|
+
pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
|
|
71
73
|
/** Wait until the session's page is ready (and optional URL/selector match). */
|
|
72
74
|
waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult>;
|
|
73
75
|
/** Produce an AI-friendly snapshot of the session's page. */
|
package/lib/browser/runtime.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* so selection never depends on registration order.
|
|
7
7
|
* @module dsh-browser/browser
|
|
8
8
|
*/
|
|
9
|
+
import { pageOperationScript } from '../tool-browser/page-probe.js';
|
|
9
10
|
import { Service } from '@deepseek-ai/cordis';
|
|
10
11
|
import z from '@deepseek-ai/schemastery';
|
|
11
12
|
import { BrowserError } from './types.js';
|
|
@@ -118,6 +119,14 @@ export class BrowserRuntime extends Service {
|
|
|
118
119
|
async execute(session, request, signal) {
|
|
119
120
|
return this.resolveProvider().execute(session, request, signal);
|
|
120
121
|
}
|
|
122
|
+
/** Execute one provider-owned page operation with validated operation names. */
|
|
123
|
+
async pageOperation(session, request, signal) {
|
|
124
|
+
const provider = this.resolveProvider();
|
|
125
|
+
// Legacy providers retain their execute permission checks.
|
|
126
|
+
return provider.pageOperation
|
|
127
|
+
? provider.pageOperation(session, request, signal)
|
|
128
|
+
: provider.execute(session, { script: pageOperationScript(request) }, signal);
|
|
129
|
+
}
|
|
121
130
|
/** Wait until the session's page is ready (and optional URL/selector match). */
|
|
122
131
|
async waitFor(session, request, signal) {
|
|
123
132
|
return this.resolveProvider().waitFor(session, request, signal);
|
package/lib/browser/types.d.ts
CHANGED
|
@@ -329,6 +329,46 @@ export interface BrowserExecuteRequest {
|
|
|
329
329
|
/** Evaluation budget in ms; a wedged page rejects with a timeout. Default 30000. */
|
|
330
330
|
readonly timeoutMs?: number;
|
|
331
331
|
}
|
|
332
|
+
/**
|
|
333
|
+
* Fixed page operations implemented by the provider. Strings are serialized as data.
|
|
334
|
+
* Arbitrary JavaScript is handled only by BrowserExecuteRequest.
|
|
335
|
+
*/
|
|
336
|
+
export type BrowserPageOperationRequest = {
|
|
337
|
+
readonly operation: 'install';
|
|
338
|
+
} | {
|
|
339
|
+
readonly operation: 'probe';
|
|
340
|
+
readonly method: BrowserProbeMethod;
|
|
341
|
+
readonly args?: readonly unknown[];
|
|
342
|
+
} | {
|
|
343
|
+
readonly operation: 'text';
|
|
344
|
+
readonly text: string;
|
|
345
|
+
} | {
|
|
346
|
+
readonly operation: 'url';
|
|
347
|
+
} | {
|
|
348
|
+
readonly operation: 'drag';
|
|
349
|
+
readonly from: {
|
|
350
|
+
x: number;
|
|
351
|
+
y: number;
|
|
352
|
+
};
|
|
353
|
+
readonly to: {
|
|
354
|
+
x: number;
|
|
355
|
+
y: number;
|
|
356
|
+
};
|
|
357
|
+
readonly steps: number;
|
|
358
|
+
} | {
|
|
359
|
+
readonly operation: 'upload';
|
|
360
|
+
readonly target: {
|
|
361
|
+
by: 'css' | 'text' | 'xpath';
|
|
362
|
+
value: string;
|
|
363
|
+
};
|
|
364
|
+
readonly file: {
|
|
365
|
+
name: string;
|
|
366
|
+
mime: string;
|
|
367
|
+
base64: string;
|
|
368
|
+
};
|
|
369
|
+
};
|
|
370
|
+
/** Provider-owned probe operations; JavaScript properties such as constructor are excluded. */
|
|
371
|
+
export type BrowserProbeMethod = 'read' | 'clear' | 'settle' | 'find' | 'overlayAt' | 'summary' | 'findText' | 'hoverAt' | 'setDialogPolicy' | 'dialogStatus' | 'networkCursor';
|
|
332
372
|
/**
|
|
333
373
|
* Result of an execute. Mirrors CDP `Runtime.evaluate` semantics: either a
|
|
334
374
|
* value (by value, not by reference) or the exception thrown.
|
|
@@ -591,6 +631,8 @@ export interface BrowserProvider {
|
|
|
591
631
|
navigate(session: BrowserSessionId, request: BrowserNavigateRequest, signal?: AbortSignal): Promise<void>;
|
|
592
632
|
/** Execute JS in the active tab's page context. */
|
|
593
633
|
execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
|
|
634
|
+
/** Execute one fixed browser operation without granting arbitrary page scripting. */
|
|
635
|
+
pageOperation?(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>;
|
|
594
636
|
/** Wait until the page is ready (and optional URL/selector match). Honor `signal` for cancellation. */
|
|
595
637
|
waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult>;
|
|
596
638
|
/** Produce an AI-friendly snapshot of the active tab. */
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authenticate plugin HTTP routes with the browser session owned by DSH.
|
|
3
|
+
* The connection service verifies its signed cookie and completes denied responses.
|
|
4
|
+
* @module dsh-browser/browser-electron/authenticated-route
|
|
5
|
+
*/
|
|
6
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
7
|
+
/** The host authentication method shared with its application and inspector routes. */
|
|
8
|
+
export interface BrowserConnection {
|
|
9
|
+
authorizeIndex(request: IncomingMessage, response: ServerResponse): boolean;
|
|
10
|
+
}
|
|
11
|
+
/** An exact HTTP route registered with the DSH web server. */
|
|
12
|
+
export type BrowserHttpHandler = (request: IncomingMessage, response: ServerResponse) => void | Promise<void>;
|
|
13
|
+
/**
|
|
14
|
+
* Check the current host credential on every request before reading settings, capturing a frame,
|
|
15
|
+
* or starting a write. Origin checks remain inside the handler as an additional browser boundary.
|
|
16
|
+
* @param connection - resolves the host's current connection service.
|
|
17
|
+
* @param handler - the operation to run after authentication.
|
|
18
|
+
* @returns an authenticated route handler.
|
|
19
|
+
*/
|
|
20
|
+
export declare function authenticatedRoute(connection: () => BrowserConnection | undefined, handler: BrowserHttpHandler): BrowserHttpHandler;
|
|
21
|
+
/**
|
|
22
|
+
* Admit machine-wide installation changes from a direct loopback connection.
|
|
23
|
+
* Forwarded requests belong to their remote operator even when the last hop is loopback.
|
|
24
|
+
* @param request - request received by the host.
|
|
25
|
+
* @returns true for direct loopback requests.
|
|
26
|
+
*/
|
|
27
|
+
export declare function isDirectLoopback(request: IncomingMessage): boolean;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { replyJson } from './json-reply.js';
|
|
2
|
+
/**
|
|
3
|
+
* Check the current host credential on every request before reading settings, capturing a frame,
|
|
4
|
+
* or starting a write. Origin checks remain inside the handler as an additional browser boundary.
|
|
5
|
+
* @param connection - resolves the host's current connection service.
|
|
6
|
+
* @param handler - the operation to run after authentication.
|
|
7
|
+
* @returns an authenticated route handler.
|
|
8
|
+
*/
|
|
9
|
+
export function authenticatedRoute(connection, handler) {
|
|
10
|
+
return (request, response) => {
|
|
11
|
+
let host;
|
|
12
|
+
try {
|
|
13
|
+
host = connection();
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// A disposed host cannot authorize new work.
|
|
17
|
+
}
|
|
18
|
+
if (typeof host?.authorizeIndex !== 'function') {
|
|
19
|
+
replyJson(response, 503, { error: 'browser-auth-unavailable' });
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
// A false result owns the response. Preserving it also preserves host-specific login behavior.
|
|
23
|
+
if (!host.authorizeIndex(request, response))
|
|
24
|
+
return;
|
|
25
|
+
return handler(request, response);
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Admit machine-wide installation changes from a direct loopback connection.
|
|
30
|
+
* Forwarded requests belong to their remote operator even when the last hop is loopback.
|
|
31
|
+
* @param request - request received by the host.
|
|
32
|
+
* @returns true for direct loopback requests.
|
|
33
|
+
*/
|
|
34
|
+
export function isDirectLoopback(request) {
|
|
35
|
+
const address = request.socket.remoteAddress;
|
|
36
|
+
const local = address === '::1' || address === '127.0.0.1' || address === '::ffff:127.0.0.1';
|
|
37
|
+
return local && !['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-real-ip']
|
|
38
|
+
.some(name => request.headers[name] !== undefined);
|
|
39
|
+
}
|
|
@@ -62,6 +62,13 @@ export function readBridgeEndpoint(path = bridgeEndpointPath(), now = Date.now()
|
|
|
62
62
|
let raw;
|
|
63
63
|
try {
|
|
64
64
|
raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
65
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
|
|
66
|
+
|| !Number.isInteger(raw.port) || Number(raw.port) < 1 || Number(raw.port) > 65535
|
|
67
|
+
|| typeof raw.token !== 'string' || raw.token.trim() === ''
|
|
68
|
+
|| !Number.isSafeInteger(raw.pid) || Number(raw.pid) <= 0
|
|
69
|
+
|| (raw.updatedAt !== undefined && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt))))) {
|
|
70
|
+
throw new Error('expected a port, a nonempty token, a positive pid and an optional timestamp');
|
|
71
|
+
}
|
|
65
72
|
}
|
|
66
73
|
catch (error) {
|
|
67
74
|
return {
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** What the panel may ask for. */
|
|
2
|
+
export type BridgeAction = 'install' | 'uninstall';
|
|
3
|
+
/** Everything this module touches from outside, so a test can drive it without spawning. */
|
|
4
|
+
export interface BridgeActionDeps {
|
|
5
|
+
/** Runs the installer; resolves with an exit code and the tail of its output. */
|
|
6
|
+
readonly run: (command: string, argv: readonly string[]) => Promise<{
|
|
7
|
+
readonly code: number | null;
|
|
8
|
+
readonly output: string;
|
|
9
|
+
}>;
|
|
10
|
+
/** Absolute path of the packaged installer. */
|
|
11
|
+
readonly installer: () => string;
|
|
12
|
+
/** Node executable used to run it (the host's own, so no PATH surprises). */
|
|
13
|
+
readonly node: () => string;
|
|
14
|
+
}
|
|
15
|
+
/** What the panel is told. */
|
|
16
|
+
export interface BridgeActionResult {
|
|
17
|
+
/** Whether the installer exited 0. */
|
|
18
|
+
readonly ok: boolean;
|
|
19
|
+
/** Its exit code, or null when it was killed. */
|
|
20
|
+
readonly code: number | null;
|
|
21
|
+
/** The tail of its output, for the one line the panel shows. */
|
|
22
|
+
readonly output: string;
|
|
23
|
+
/** The exact command line, so a failure can be reproduced by hand. */
|
|
24
|
+
readonly command: string;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* The argv the installer expects, in one place so the panel and a human run the same thing.
|
|
28
|
+
*
|
|
29
|
+
* `--restart --yes` is not a convenience: the shell holds `app.asar` open, so an install with the
|
|
30
|
+
* app running fails with EBUSY, and a prompt would block an unattended click.
|
|
31
|
+
* @param action - install/repair, or restore the pre-bridge state.
|
|
32
|
+
* @param installRoot - the desktop install directory that was discovered.
|
|
33
|
+
* @returns argv for the installer.
|
|
34
|
+
*/
|
|
35
|
+
export declare function bridgeActionArgv(action: BridgeAction, installRoot: string): string[];
|
|
36
|
+
/** The packaged installer, resolved from this module rather than from a build-time path. */
|
|
37
|
+
export declare function defaultInstallerPath(): string;
|
|
38
|
+
/**
|
|
39
|
+
* Run one bridge action.
|
|
40
|
+
*
|
|
41
|
+
* Never throws for an installer failure: the panel needs the exit code and the line that explains it,
|
|
42
|
+
* and an exception would lose both.
|
|
43
|
+
* @param action - install/repair or uninstall.
|
|
44
|
+
* @param installRoot - the desktop install directory.
|
|
45
|
+
* @param deps - effects; defaulted to this process's.
|
|
46
|
+
* @returns the outcome, with the command line for reproduction.
|
|
47
|
+
*/
|
|
48
|
+
export declare function runBridgeAction(action: BridgeAction, installRoot: string, deps?: BridgeActionDeps): Promise<BridgeActionResult>;
|