dsh-builtin-browser 0.5.5 → 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 +143 -1
- package/README.en.md +67 -97
- package/README.md +67 -98
- package/client.js +618 -263
- package/desktop-bridge/install.mjs +122 -33
- package/desktop-bridge/plugin-browser-bridge.js +9 -4
- package/docs/development.md +10 -0
- package/docs/tool-reference.md +20 -1
- package/docs/user-guide.md +16 -4
- 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-connection.d.ts +8 -0
- package/lib/browser-electron/bridge-connection.js +8 -0
- package/lib/browser-electron/bridge-endpoint.d.ts +30 -0
- package/lib/browser-electron/bridge-endpoint.js +130 -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 +30 -27
- package/lib/browser-electron/desktop-bridge-host.js +71 -50
- package/lib/browser-electron/electron-provision.d.ts +35 -2
- package/lib/browser-electron/electron-provision.js +83 -20
- package/lib/browser-electron/entry.js +144 -7
- package/lib/browser-electron/host-main.js +48 -27
- package/lib/browser-electron/json-reply.d.ts +21 -0
- package/lib/browser-electron/json-reply.js +17 -0
- package/lib/browser-electron/preview-route.js +1 -12
- package/lib/browser-electron/provider.d.ts +9 -2
- package/lib/browser-electron/provider.js +76 -6
- package/lib/browser-electron/remote-host.js +10 -9
- package/lib/browser-electron/runtime-route.d.ts +55 -0
- package/lib/browser-electron/runtime-route.js +66 -0
- package/lib/browser-electron/runtime-status.d.ts +102 -0
- package/lib/browser-electron/runtime-status.js +88 -0
- 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 +5 -3
- package/scripts/consumer-install-check.mjs +72 -0
- package/scripts/verify-runtime-status.mjs +179 -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-connection.ts +9 -0
- package/src/browser-electron/bridge-endpoint.ts +146 -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 +68 -50
- package/src/browser-electron/electron-provision.ts +103 -20
- package/src/browser-electron/entry.ts +141 -7
- package/src/browser-electron/host-main.ts +41 -22
- package/src/browser-electron/json-reply.ts +32 -0
- package/src/browser-electron/preview-route.ts +1 -12
- package/src/browser-electron/provider.ts +90 -6
- package/src/browser-electron/remote-host.ts +10 -9
- package/src/browser-electron/runtime-route.ts +104 -0
- package/src/browser-electron/runtime-status.ts +188 -0
- 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
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Readiness-route probe: do the two endpoints the settings panel reads actually get registered,
|
|
4
|
+
* and does the report they serve describe this machine?
|
|
5
|
+
*
|
|
6
|
+
* The unit tests cover the handlers and the report in isolation. What they cannot cover is the
|
|
7
|
+
* WIRING between them — `ctx.inject(['webServer'])`, the two `webServer.register` calls, and the
|
|
8
|
+
* deps that read the settings document and the install tree. That glue is exactly where this plugin
|
|
9
|
+
* has lost a surface before (a route that was never registered because a dependency name was wrong
|
|
10
|
+
* looks identical to a route that returned nothing), so it is checked here against the real host
|
|
11
|
+
* packages, over real HTTP, with no browser and no DSH restart.
|
|
12
|
+
*
|
|
13
|
+
* Usage:
|
|
14
|
+
* node scripts/verify-runtime-status.mjs # profile named by DSH_PROFILE, else the first
|
|
15
|
+
* DSH_PROFILE=desktop node scripts/verify-runtime-status.mjs
|
|
16
|
+
*
|
|
17
|
+
* It writes into a throwaway DSH_HOME, never the real one, and pins
|
|
18
|
+
* ELECTRON_SKIP_BINARY_DOWNLOAD so a probe can never start a 100 MB download.
|
|
19
|
+
*/
|
|
20
|
+
import { createRequire } from 'node:module'
|
|
21
|
+
import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
22
|
+
import { createServer } from 'node:http'
|
|
23
|
+
import { tmpdir } from 'node:os'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { pathToFileURL } from 'node:url'
|
|
26
|
+
|
|
27
|
+
const REPO = new URL('..', import.meta.url)
|
|
28
|
+
const failures = []
|
|
29
|
+
const ok = (label, condition, detail = '') => {
|
|
30
|
+
console.log(` ${condition ? 'OK ' : 'FAIL'} ${label}${detail === '' ? '' : ` — ${detail}`}`)
|
|
31
|
+
if (!condition) failures.push(label)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The profile whose node_modules resolve the host packages. */
|
|
35
|
+
function findProfileRoot() {
|
|
36
|
+
const home = process.env.DSH_HOME ?? join(process.env.USERPROFILE ?? process.env.HOME ?? '', '.dsh')
|
|
37
|
+
const profiles = join(home, 'profiles')
|
|
38
|
+
if (!existsSync(profiles)) return undefined
|
|
39
|
+
const named = process.env.DSH_PROFILE
|
|
40
|
+
const candidates = named !== undefined && named !== ''
|
|
41
|
+
? [named]
|
|
42
|
+
: readdirSync(profiles).filter(entry => existsSync(join(profiles, entry, 'package.json')))
|
|
43
|
+
for (const candidate of candidates) {
|
|
44
|
+
const manifest = join(profiles, candidate, 'package.json')
|
|
45
|
+
if (existsSync(manifest)) return { name: candidate, manifest }
|
|
46
|
+
}
|
|
47
|
+
return undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const profile = findProfileRoot()
|
|
51
|
+
if (profile === undefined) {
|
|
52
|
+
console.log('No DSH profile found under $DSH_HOME/profiles; nothing to verify.')
|
|
53
|
+
process.exit(0)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// A settings document of our own, so the probe can name a channel without touching the user's file.
|
|
57
|
+
const sandboxHome = mkdtempSync(join(tmpdir(), 'dsh-runtime-probe-'))
|
|
58
|
+
process.env.DSH_HOME = sandboxHome
|
|
59
|
+
// The whole point is that a probe never downloads: this reports `skipped`, which is also a state the
|
|
60
|
+
// panel has to render.
|
|
61
|
+
process.env.ELECTRON_SKIP_BINARY_DOWNLOAD = '1'
|
|
62
|
+
|
|
63
|
+
const require = createRequire(profile.manifest)
|
|
64
|
+
const load = async spec => import(pathToFileURL(require.resolve(spec)).href)
|
|
65
|
+
const cordis = await load('@deepseek-ai/cordis')
|
|
66
|
+
|
|
67
|
+
console.log(`Host: profile "${profile.name}" · sandbox DSH_HOME ${sandboxHome}`)
|
|
68
|
+
console.log('')
|
|
69
|
+
|
|
70
|
+
/** The host's web-server shape: exact paths, a handler, and an unsubscribe. */
|
|
71
|
+
class StubWebServer extends cordis.Service {
|
|
72
|
+
constructor(ctx) {
|
|
73
|
+
super(ctx, 'webServer')
|
|
74
|
+
this.routes = new Map()
|
|
75
|
+
}
|
|
76
|
+
register(spec, label) {
|
|
77
|
+
this.routes.set(spec.path, { handler: spec.handler, label })
|
|
78
|
+
return () => this.routes.delete(spec.path)
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
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
|
+
|
|
96
|
+
new StubWebServer(root)
|
|
97
|
+
new StubConnection(root)
|
|
98
|
+
|
|
99
|
+
const seam = await import(new URL('lib/browser/runtime.js', REPO).href)
|
|
100
|
+
new seam.default(root)
|
|
101
|
+
const entry = await import(new URL('lib/browser-electron/entry.js', REPO).href)
|
|
102
|
+
entry.apply(root, {})
|
|
103
|
+
|
|
104
|
+
const server = root.get('webServer')
|
|
105
|
+
// `ctx.inject([...], cb)` defers the callback until the dependency is available, which is a later
|
|
106
|
+
// turn of the loop — so the first read can legitimately see an empty route table. Poll briefly
|
|
107
|
+
// instead of asserting on a race; this is the difference between "not wired" and "not yet".
|
|
108
|
+
for (let waited = 0; waited < 2_000 && server.routes.size === 0; waited += 50) {
|
|
109
|
+
await new Promise(resolve => setTimeout(resolve, 50))
|
|
110
|
+
}
|
|
111
|
+
ok('the readiness routes are registered', server.routes.has('/dsh-builtin-browser/runtime-status')
|
|
112
|
+
&& server.routes.has('/dsh-builtin-browser/runtime-provision'),
|
|
113
|
+
[...server.routes.keys()].join(', '))
|
|
114
|
+
|
|
115
|
+
// Serve exactly the handlers the plugin registered — no re-implementation in the probe.
|
|
116
|
+
const listener = createServer((req, res) => {
|
|
117
|
+
const route = server.routes.get(new URL(req.url, 'http://localhost').pathname)
|
|
118
|
+
if (route === undefined) { res.writeHead(404); res.end(); return }
|
|
119
|
+
void route.handler(req, res)
|
|
120
|
+
})
|
|
121
|
+
await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
|
|
122
|
+
const base = `http://127.0.0.1:${listener.address().port}`
|
|
123
|
+
|
|
124
|
+
/** Headers a browser sends and a plain script does not — the admission rule keys off exactly these. */
|
|
125
|
+
const panelHeaders = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', 'accept-language': 'zh-CN' }
|
|
126
|
+
|
|
127
|
+
try {
|
|
128
|
+
const read = await fetch(`${base}/dsh-builtin-browser/runtime-status`, { headers: panelHeaders })
|
|
129
|
+
const body = await read.json()
|
|
130
|
+
ok('GET answers 200', read.status === 200, String(read.status))
|
|
131
|
+
ok('the report names the channel the settings document holds', body.runtime?.channel === 'bundled', String(body.runtime?.channel))
|
|
132
|
+
ok('the report resolves it to a carrier', body.runtime?.carrier === 'bundled', String(body.runtime?.carrier))
|
|
133
|
+
ok('the runtime state is a state the panel can localize',
|
|
134
|
+
['idle', 'preparing', 'present', 'ready', 'skipped', 'failed'].includes(body.runtime?.electron?.state),
|
|
135
|
+
String(body.runtime?.electron?.state))
|
|
136
|
+
ok('the download opt-out is honoured, or a runtime is already there',
|
|
137
|
+
body.runtime?.electron?.state !== 'preparing' && (body.runtime?.electron?.detail ?? '') !== '',
|
|
138
|
+
`${String(body.runtime?.electron?.state)}: ${body.runtime?.electron?.detail ?? ''}`)
|
|
139
|
+
ok('the bridge reading is one of the four states the panel knows',
|
|
140
|
+
['installed', 'missing', 'stale', 'absent'].includes(body.runtime?.bridge?.state),
|
|
141
|
+
String(body.runtime?.bridge?.state))
|
|
142
|
+
ok('installed and running are reported separately',
|
|
143
|
+
typeof body.runtime?.bridge?.running === 'boolean' && typeof body.runtime?.bridge?.runningDetail === 'string',
|
|
144
|
+
`running=${String(body.runtime?.bridge?.running)} — ${body.runtime?.bridge?.runningDetail ?? ''}`)
|
|
145
|
+
ok('a runtime on disk is not described as "not asked for yet"',
|
|
146
|
+
body.runtime?.electron?.state !== 'present' || !/not been asked/.test(body.runtime?.electron?.detail ?? ''),
|
|
147
|
+
String(body.runtime?.electron?.detail ?? ''))
|
|
148
|
+
ok('readiness is one of ready/blocked/unknown',
|
|
149
|
+
['ready', 'blocked', 'unknown'].includes(body.runtime?.readiness), String(body.runtime?.readiness))
|
|
150
|
+
ok('readiness agrees with the two readings it is derived from',
|
|
151
|
+
body.runtime?.readiness !== 'ready'
|
|
152
|
+
|| (body.runtime?.carrier === 'sidebar'
|
|
153
|
+
? body.runtime?.bridge?.state === 'installed' && body.runtime?.bridge?.running === true
|
|
154
|
+
: body.runtime?.electron?.state === 'present' || body.runtime?.electron?.state === 'ready'),
|
|
155
|
+
`carrier=${String(body.runtime?.carrier)} readiness=${String(body.runtime?.readiness)}`)
|
|
156
|
+
|
|
157
|
+
const scripted = await fetch(`${base}/dsh-builtin-browser/runtime-provision`, { method: 'POST' })
|
|
158
|
+
ok('a POST without browser headers is refused', scripted.status === 403, String(scripted.status))
|
|
159
|
+
|
|
160
|
+
const started = await fetch(`${base}/dsh-builtin-browser/runtime-provision`, { method: 'POST', headers: panelHeaders })
|
|
161
|
+
const startedBody = await started.json()
|
|
162
|
+
ok('the panel may start it and gets a state back', started.status === 200 && startedBody.provision !== undefined,
|
|
163
|
+
JSON.stringify(startedBody.provision ?? startedBody).slice(0, 120))
|
|
164
|
+
} catch (error) {
|
|
165
|
+
ok('the routes answer over HTTP', false, String(error && error.message))
|
|
166
|
+
} finally {
|
|
167
|
+
await new Promise(resolve => listener.close(resolve))
|
|
168
|
+
await root.stop?.()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
console.log('')
|
|
172
|
+
if (failures.length === 0) {
|
|
173
|
+
console.log('VERDICT: the readiness routes are wired and answer on this host.')
|
|
174
|
+
} else {
|
|
175
|
+
console.log(`VERDICT: ${failures.length} failure(s):`)
|
|
176
|
+
for (const failure of failures) console.log(` - ${failure}`)
|
|
177
|
+
process.exitCode = 1
|
|
178
|
+
}
|
|
179
|
+
process.exit(process.exitCode ?? 0)
|
|
@@ -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.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Batching with dsh_browser_do
|
|
2
|
+
|
|
3
|
+
One call, one result, and it stops at the first step that cannot proceed:
|
|
4
|
+
|
|
5
|
+
```json
|
|
6
|
+
{"steps": [
|
|
7
|
+
{"open": "https://example.com/search"},
|
|
8
|
+
{"field": {"target": {"by": "css", "value": "#q"}, "text": "invoice"}},
|
|
9
|
+
{"key": "Enter"},
|
|
10
|
+
{"wait_idle": {}},
|
|
11
|
+
{"check": {"text": "3 results"}}
|
|
12
|
+
]}
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Rules that keep a batch honest:
|
|
16
|
+
|
|
17
|
+
- Give each step exactly one key; anything else is refused before the first action runs.
|
|
18
|
+
- Put a `check` after the steps that change server state — the batch then fails at the step where
|
|
19
|
+
the outcome was already wrong, not three steps later.
|
|
20
|
+
- `wait_idle` waits for in-flight requests to drain and the page to go quiet for 300 ms; use it
|
|
21
|
+
instead of `sleep_ms` unless the page genuinely needs wall-clock time.
|
|
22
|
+
- A failed batch reports `stoppedAt`, `completed` and a per-step log, so re-running only the
|
|
23
|
+
remainder is a deliberate choice, and it starts with a fresh `state`.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# Delivering a file somewhere else
|
|
2
|
+
|
|
3
|
+
The browser's job ends with a file on disk. Sending it to Feishu (Lark) drive, Baidu Netdisk or any
|
|
4
|
+
other storage is a separate capability the user connects as an MCP server — both platforms ship an
|
|
5
|
+
official one (`lark_drive_upload`, `baidu-netdisk/mcp`'s upload tool). The plugin does not hold
|
|
6
|
+
their credentials and should not.
|
|
7
|
+
|
|
8
|
+
## The path
|
|
9
|
+
|
|
10
|
+
1. `dsh_browser_download` saves the URL through the directory admission gate and returns an
|
|
11
|
+
**absolute path**. It never overwrites an existing file; if the name is taken, ask for another.
|
|
12
|
+
2. Hand that exact path to the upload tool the user connected, e.g.
|
|
13
|
+
`lark_drive_upload({ file_path: "<returned path>", folder_token: "<the user's folder>" })`.
|
|
14
|
+
3. Report both facts: where the file now sits locally, and what the upload tool answered.
|
|
15
|
+
|
|
16
|
+
## Rules
|
|
17
|
+
|
|
18
|
+
- **Never** report "saved to Feishu" from the download alone. The download proves a local file; only
|
|
19
|
+
the upload tool's reply proves the remote copy.
|
|
20
|
+
- If the upload tool fails or is not connected, say so plainly and leave the local path — the file
|
|
21
|
+
is still usable and the human can move it by hand. Do not silently retry somewhere else.
|
|
22
|
+
- A folder id / token belongs to the user's workspace: ask for it, or read it from the tool's own
|
|
23
|
+
documentation, instead of guessing a default.
|
|
24
|
+
- Before uploading something sensitive (an invoice, a screenshot with an account name), say what is
|
|
25
|
+
about to leave the machine.
|
|
26
|
+
|
|
27
|
+
## When the user wants this to happen automatically
|
|
28
|
+
|
|
29
|
+
A per-call handoff (`dsh_browser_download` with a `handoff` argument) and a settings field for the
|
|
30
|
+
default tool are planned; until they exist, the two-step form above is the supported path and it
|
|
31
|
+
keeps the human in control of where their files go.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Locating things
|
|
2
|
+
|
|
3
|
+
- Prefer roles and names (`dsh_browser_a11y`) over CSS when the page is a normal app: a label
|
|
4
|
+
survives a re-render, a generated class does not.
|
|
5
|
+
- `dsh_browser_snapshot` numbers every interactive element and appends `{#id}` / `{[name=x]}`
|
|
6
|
+
when it can derive one — copy that straight into `{by:"css", value:"#id"}`.
|
|
7
|
+
- Text targets match the element's own visible text or aria-label; if two match, pass `index`.
|
|
8
|
+
- `dsh_browser_find` searches the page text and returns viewport points — use it to find a table
|
|
9
|
+
row or a sentence, then click at the point or scroll the element into view.
|
|
10
|
+
- An element inside an iframe or shadow root is reachable, but only when same-origin; a
|
|
11
|
+
cross-origin frame is a wall — report it instead of guessing coordinates at random.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Recovering
|
|
2
|
+
|
|
3
|
+
- Page stuck or a script half-applied: `dsh_browser_refresh`.
|
|
4
|
+
- Session wedged after a carrier loss: `dsh_browser_reset_session` (this task only), then re-open
|
|
5
|
+
and re-read the page. A lost carrier means the page context is gone — nothing you knew about it
|
|
6
|
+
still holds.
|
|
7
|
+
- A call fails with a reason you cannot place: `dsh_browser_doctor` (session, page state, probe
|
|
8
|
+
buffers, which tools this task restricted away), then `dsh_browser_help` for the topic.
|
|
9
|
+
- Everything is refused with "restricted": the task restricted its own tools. `dsh_browser_restrict`
|
|
10
|
+
with the needed names lifts it; observation tools are never blocked.
|
|
11
|
+
- Do not retry a state-changing call blindly after an error. Read first, decide second.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
# Verifying
|
|
2
|
+
|
|
3
|
+
| Question | Tool |
|
|
4
|
+
| --- | --- |
|
|
5
|
+
| Is the element there / the text there / the URL changed? | `dsh_browser_assert` |
|
|
6
|
+
| Did a request reach the server? | `dsh_browser_wait_for_response` |
|
|
7
|
+
| What did the page log or fetch? | `dsh_browser_console`, `dsh_browser_network` |
|
|
8
|
+
| Did a field take the value? | `dsh_browser_get_value` |
|
|
9
|
+
|
|
10
|
+
A submit is the dangerous case. After clicking submit: wait for the response, assert the visible
|
|
11
|
+
outcome, and if the call died before either answer arrived, **read the site's own record** (the
|
|
12
|
+
list page, the order history) before acting again. "Result unknown" is an acceptable answer to
|
|
13
|
+
report; a second submit is not.
|
package/src/browser/runtime.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* @module dsh-browser/browser
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
+
import { pageOperationScript } from '../tool-browser/page-probe.js'
|
|
10
11
|
import { Context, Service } from '@deepseek-ai/cordis'
|
|
11
12
|
import z from '@deepseek-ai/schemastery'
|
|
12
13
|
import type {
|
|
@@ -22,6 +23,7 @@ import type {
|
|
|
22
23
|
BrowserDownloadRequest,
|
|
23
24
|
BrowserElementTarget,
|
|
24
25
|
BrowserExecuteRequest,
|
|
26
|
+
BrowserPageOperationRequest,
|
|
25
27
|
BrowserExecuteResult,
|
|
26
28
|
BrowserFillRequest,
|
|
27
29
|
BrowserFillResult,
|
|
@@ -247,6 +249,15 @@ export class BrowserRuntime extends Service {
|
|
|
247
249
|
return this.resolveProvider().execute(session, request, signal)
|
|
248
250
|
}
|
|
249
251
|
|
|
252
|
+
/** Execute one provider-owned page operation with validated operation names. */
|
|
253
|
+
async pageOperation(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult> {
|
|
254
|
+
const provider = this.resolveProvider()
|
|
255
|
+
// Legacy providers retain their execute permission checks.
|
|
256
|
+
return provider.pageOperation
|
|
257
|
+
? provider.pageOperation(session, request, signal)
|
|
258
|
+
: provider.execute(session, { script: pageOperationScript(request) }, signal)
|
|
259
|
+
}
|
|
260
|
+
|
|
250
261
|
/** Wait until the session's page is ready (and optional URL/selector match). */
|
|
251
262
|
async waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult> {
|
|
252
263
|
return this.resolveProvider().waitFor(session, request, signal)
|
package/src/browser/types.ts
CHANGED
|
@@ -359,6 +359,22 @@ export interface BrowserExecuteRequest {
|
|
|
359
359
|
readonly timeoutMs?: number
|
|
360
360
|
}
|
|
361
361
|
|
|
362
|
+
/**
|
|
363
|
+
* Fixed page operations implemented by the provider. Strings are serialized as data.
|
|
364
|
+
* Arbitrary JavaScript is handled only by BrowserExecuteRequest.
|
|
365
|
+
*/
|
|
366
|
+
export type BrowserPageOperationRequest =
|
|
367
|
+
| { readonly operation: 'install' }
|
|
368
|
+
| { readonly operation: 'probe'; readonly method: BrowserProbeMethod; readonly args?: readonly unknown[] }
|
|
369
|
+
| { readonly operation: 'text'; readonly text: string }
|
|
370
|
+
| { readonly operation: 'url' }
|
|
371
|
+
| { readonly operation: 'drag'; readonly from: { x: number; y: number }; readonly to: { x: number; y: number }; readonly steps: number }
|
|
372
|
+
| { readonly operation: 'upload'; readonly target: { by: 'css' | 'text' | 'xpath'; value: string }; readonly file: { name: string; mime: string; base64: string } }
|
|
373
|
+
|
|
374
|
+
/** Provider-owned probe operations; JavaScript properties such as constructor are excluded. */
|
|
375
|
+
export type BrowserProbeMethod = 'read' | 'clear' | 'settle' | 'find' | 'overlayAt' | 'summary'
|
|
376
|
+
| 'findText' | 'hoverAt' | 'setDialogPolicy' | 'dialogStatus' | 'networkCursor'
|
|
377
|
+
|
|
362
378
|
/**
|
|
363
379
|
* Result of an execute. Mirrors CDP `Runtime.evaluate` semantics: either a
|
|
364
380
|
* value (by value, not by reference) or the exception thrown.
|
|
@@ -632,6 +648,9 @@ export interface BrowserProvider {
|
|
|
632
648
|
navigate(session: BrowserSessionId, request: BrowserNavigateRequest, signal?: AbortSignal): Promise<void>
|
|
633
649
|
/** Execute JS in the active tab's page context. */
|
|
634
650
|
execute(session: BrowserSessionId, request: BrowserExecuteRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>
|
|
651
|
+
|
|
652
|
+
/** Execute one fixed browser operation without granting arbitrary page scripting. */
|
|
653
|
+
pageOperation?(session: BrowserSessionId, request: BrowserPageOperationRequest, signal?: AbortSignal): Promise<BrowserExecuteResult>
|
|
635
654
|
/** Wait until the page is ready (and optional URL/selector match). Honor `signal` for cancellation. */
|
|
636
655
|
waitFor(session: BrowserSessionId, request: BrowserWaitRequest, signal?: AbortSignal): Promise<BrowserWaitResult>
|
|
637
656
|
/** Produce an AI-friendly snapshot of the active tab. */
|
|
@@ -0,0 +1,56 @@
|
|
|
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
|
+
import { replyJson } from './json-reply.js'
|
|
8
|
+
|
|
9
|
+
/** The host authentication method shared with its application and inspector routes. */
|
|
10
|
+
export interface BrowserConnection {
|
|
11
|
+
authorizeIndex(request: IncomingMessage, response: ServerResponse): boolean
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** An exact HTTP route registered with the DSH web server. */
|
|
15
|
+
export type BrowserHttpHandler = (request: IncomingMessage, response: ServerResponse) => void | Promise<void>
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Check the current host credential on every request before reading settings, capturing a frame,
|
|
19
|
+
* or starting a write. Origin checks remain inside the handler as an additional browser boundary.
|
|
20
|
+
* @param connection - resolves the host's current connection service.
|
|
21
|
+
* @param handler - the operation to run after authentication.
|
|
22
|
+
* @returns an authenticated route handler.
|
|
23
|
+
*/
|
|
24
|
+
export function authenticatedRoute(
|
|
25
|
+
connection: () => BrowserConnection | undefined,
|
|
26
|
+
handler: BrowserHttpHandler,
|
|
27
|
+
): BrowserHttpHandler {
|
|
28
|
+
return (request, response) => {
|
|
29
|
+
let host: BrowserConnection | undefined
|
|
30
|
+
try {
|
|
31
|
+
host = connection()
|
|
32
|
+
} catch {
|
|
33
|
+
// A disposed host cannot authorize new work.
|
|
34
|
+
}
|
|
35
|
+
if (typeof host?.authorizeIndex !== 'function') {
|
|
36
|
+
replyJson(response, 503, { error: 'browser-auth-unavailable' })
|
|
37
|
+
return
|
|
38
|
+
}
|
|
39
|
+
// A false result owns the response. Preserving it also preserves host-specific login behavior.
|
|
40
|
+
if (!host.authorizeIndex(request, response)) return
|
|
41
|
+
return handler(request, response)
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Admit machine-wide installation changes from a direct loopback connection.
|
|
47
|
+
* Forwarded requests belong to their remote operator even when the last hop is loopback.
|
|
48
|
+
* @param request - request received by the host.
|
|
49
|
+
* @returns true for direct loopback requests.
|
|
50
|
+
*/
|
|
51
|
+
export function isDirectLoopback(request: IncomingMessage): boolean {
|
|
52
|
+
const address = request.socket.remoteAddress
|
|
53
|
+
const local = address === '::1' || address === '127.0.0.1' || address === '::ffff:127.0.0.1'
|
|
54
|
+
return local && !['forwarded', 'x-forwarded-for', 'x-forwarded-host', 'x-real-ip']
|
|
55
|
+
.some(name => request.headers[name] !== undefined)
|
|
56
|
+
}
|
|
@@ -61,6 +61,15 @@ const REQUEST_ID_FIELD = 'bridgeRequestId'
|
|
|
61
61
|
*/
|
|
62
62
|
const ENDPOINT_TTL_MS = 60_000
|
|
63
63
|
|
|
64
|
+
/**
|
|
65
|
+
* The same window, for the readiness report.
|
|
66
|
+
*
|
|
67
|
+
* Exported rather than re-stated: "the shell is gone" must mean one thing in this plugin. A second
|
|
68
|
+
* copy of the number would drift, and the drift would show up as a panel that says ready while every
|
|
69
|
+
* call times out — the exact failure this constant exists to prevent.
|
|
70
|
+
*/
|
|
71
|
+
export const ENDPOINT_STALE_AFTER_MS = ENDPOINT_TTL_MS
|
|
72
|
+
|
|
64
73
|
/**
|
|
65
74
|
* A reusable connection to the bridge.
|
|
66
75
|
*
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether the desktop shell is RUNNING, as opposed to whether its bridge is installed.
|
|
3
|
+
*
|
|
4
|
+
* The two questions are constantly confused, and the confusion is the reason a user on
|
|
5
|
+
* `channel: sidebar` sees "another window opened instead" and cannot tell why:
|
|
6
|
+
*
|
|
7
|
+
* - `bridge-status.ts` reads the INSTALL TREE: does the shell's main entry carry our patch, and is
|
|
8
|
+
* the archive out of the way. It survives a reboot; it says nothing about a process.
|
|
9
|
+
* - This module reads the ENDPOINT the shell publishes while it runs: a port, a token, a pid and a
|
|
10
|
+
* refresh stamp. It says nothing about the install tree.
|
|
11
|
+
*
|
|
12
|
+
* "Installed" plus "not running" is the single most common broken state (the desktop app is simply
|
|
13
|
+
* closed), and a readiness report that stops at the install tree calls it ready — then every call
|
|
14
|
+
* dials a port nobody owns. So both readings are taken, and the sidebar carrier is only ready when
|
|
15
|
+
* BOTH are true.
|
|
16
|
+
*
|
|
17
|
+
* Two independent signals, because each alone has a false-positive:
|
|
18
|
+
* - the refresh stamp (the shell rewrites the file every ~15 s, so a stale stamp means a shell that
|
|
19
|
+
* exited and left its last write behind — a tombstone naming a dead port);
|
|
20
|
+
* - the pid, checked with signal 0 (kills nothing, and works across platforms).
|
|
21
|
+
* @module dsh-browser/browser-electron/bridge-endpoint
|
|
22
|
+
*/
|
|
23
|
+
import { existsSync, readFileSync, statSync } from 'node:fs'
|
|
24
|
+
|
|
25
|
+
import { ENDPOINT_STALE_AFTER_MS } from './bridge-connection.js'
|
|
26
|
+
import { bridgeEndpointPath } from './desktop-bridge-host.js'
|
|
27
|
+
|
|
28
|
+
/** What the panel needs to know about the running shell. */
|
|
29
|
+
export interface BridgeEndpointState {
|
|
30
|
+
/** Whether a published endpoint file exists at all. */
|
|
31
|
+
readonly present: boolean
|
|
32
|
+
/** Whether the shell behind it looks alive right now: a fresh stamp AND a live pid. */
|
|
33
|
+
readonly alive: boolean
|
|
34
|
+
/** One line, already user-facing. */
|
|
35
|
+
readonly detail: string
|
|
36
|
+
/** When the shell said it last refreshed the file, ISO, when the file carries a stamp. */
|
|
37
|
+
readonly updatedAt?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Whether a pid is alive, without signalling it.
|
|
42
|
+
*
|
|
43
|
+
* Signal 0 performs the permission and existence checks and delivers nothing. `EPERM` means the
|
|
44
|
+
* process exists and belongs to someone else, which is still "alive" for this purpose.
|
|
45
|
+
* @param pid - the process id from the endpoint file.
|
|
46
|
+
* @returns whether that process exists.
|
|
47
|
+
*/
|
|
48
|
+
function pidAlive(pid: number): boolean {
|
|
49
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
50
|
+
try {
|
|
51
|
+
process.kill(pid, 0)
|
|
52
|
+
return true
|
|
53
|
+
} catch (error) {
|
|
54
|
+
return (error as NodeJS.ErrnoException)?.code === 'EPERM'
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Read the endpoint the shell publishes.
|
|
60
|
+
*
|
|
61
|
+
* Never throws: a settings panel must get an answer even when the file is mid-write, unreadable, or
|
|
62
|
+
* belongs to a shell that exited an hour ago.
|
|
63
|
+
* @param path - the endpoint file; defaults to the one location the shell writes.
|
|
64
|
+
* @param now - the clock, injected so a test can age a stamp without sleeping.
|
|
65
|
+
* @returns what the panel shows.
|
|
66
|
+
*/
|
|
67
|
+
export function readBridgeEndpoint(
|
|
68
|
+
path: string = bridgeEndpointPath(),
|
|
69
|
+
now: number = Date.now(),
|
|
70
|
+
): BridgeEndpointState {
|
|
71
|
+
if (!existsSync(path)) {
|
|
72
|
+
return {
|
|
73
|
+
present: false,
|
|
74
|
+
alive: false,
|
|
75
|
+
detail: 'no desktop shell has published a bridge endpoint',
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
let raw: { port?: unknown; token?: unknown; pid?: unknown; updatedAt?: unknown }
|
|
79
|
+
try {
|
|
80
|
+
raw = JSON.parse(readFileSync(path, 'utf8')) as typeof raw
|
|
81
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)
|
|
82
|
+
|| !Number.isInteger(raw.port) || Number(raw.port) < 1 || Number(raw.port) > 65535
|
|
83
|
+
|| typeof raw.token !== 'string' || raw.token.trim() === ''
|
|
84
|
+
|| !Number.isSafeInteger(raw.pid) || Number(raw.pid) <= 0
|
|
85
|
+
|| (raw.updatedAt !== undefined && (typeof raw.updatedAt !== 'string' || !Number.isFinite(Date.parse(raw.updatedAt))))) {
|
|
86
|
+
throw new Error('expected a port, a nonempty token, a positive pid and an optional timestamp')
|
|
87
|
+
}
|
|
88
|
+
} catch (error) {
|
|
89
|
+
return {
|
|
90
|
+
present: true,
|
|
91
|
+
alive: false,
|
|
92
|
+
detail: `the published endpoint is unreadable: ${String(error)}`,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
const updatedAt = typeof raw.updatedAt === 'string' ? raw.updatedAt : undefined
|
|
96
|
+
const pid = typeof raw.pid === 'number' ? raw.pid : undefined
|
|
97
|
+
|
|
98
|
+
// A stamp older than the refresh window is a tombstone, not a slow shell (see
|
|
99
|
+
// ENDPOINT_STALE_AFTER_MS). An ABSENT stamp is not expired on purpose: an older bridge never wrote
|
|
100
|
+
// one, and that shell deserves to be checked by its pid instead of being declared gone.
|
|
101
|
+
if (updatedAt !== undefined) {
|
|
102
|
+
const at = Date.parse(updatedAt)
|
|
103
|
+
if (Number.isFinite(at)) {
|
|
104
|
+
const ageMs = now - at
|
|
105
|
+
if (ageMs > ENDPOINT_STALE_AFTER_MS) {
|
|
106
|
+
return {
|
|
107
|
+
present: true,
|
|
108
|
+
alive: false,
|
|
109
|
+
updatedAt,
|
|
110
|
+
detail: `the published endpoint has not been refreshed for ${Math.round(ageMs / 1000)}s, `
|
|
111
|
+
+ 'so the shell that wrote it has most likely exited',
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
if (pid !== undefined && !pidAlive(pid)) {
|
|
117
|
+
return {
|
|
118
|
+
present: true,
|
|
119
|
+
alive: false,
|
|
120
|
+
...updatedAt === undefined ? {} : { updatedAt },
|
|
121
|
+
detail: `the shell that published the endpoint (pid ${pid}) is not running`,
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
present: true,
|
|
126
|
+
alive: true,
|
|
127
|
+
...updatedAt === undefined ? {} : { updatedAt },
|
|
128
|
+
detail: 'a desktop shell is running and answering on its published endpoint',
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The endpoint file's mtime, for diagnostics that want to say "written at".
|
|
134
|
+
*
|
|
135
|
+
* Separate and optional: the readiness report does not need it, and a caller that does can fail
|
|
136
|
+
* without disturbing anything else.
|
|
137
|
+
* @param path - the endpoint file.
|
|
138
|
+
* @returns the mtime as ISO, or undefined.
|
|
139
|
+
*/
|
|
140
|
+
export function bridgeEndpointWrittenAt(path: string = bridgeEndpointPath()): string | undefined {
|
|
141
|
+
try {
|
|
142
|
+
return statSync(path).mtime.toISOString()
|
|
143
|
+
} catch {
|
|
144
|
+
return undefined
|
|
145
|
+
}
|
|
146
|
+
}
|