dsh-browser-cdp 0.0.1 → 0.17.0
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/LICENSE +27 -0
- package/README.md +279 -9
- package/THIRD_PARTY_NOTICES.md +62 -0
- package/bin/cdp-cast-worker.mjs +6960 -0
- package/bin/cdp-chrome-wrapper.sh +53 -0
- package/bin/cdp-render-worker.mjs +610 -0
- package/bin/record-normalize.d.mts +32 -0
- package/bin/record-normalize.mjs +156 -0
- package/cordis.patch.yml +17 -0
- package/dsh-plugin.json +148 -0
- package/lib/client.js +3235 -0
- package/lib/index.js +8865 -0
- package/lib/launcher-CQyI8-By.js +3 -0
- package/lib/launcher-DBaxfIsF.js +269 -0
- package/package.json +89 -14
- package/runtime/PATCHES.md +30 -0
- package/runtime/ego-browser/dist/out/index.js +7206 -0
- package/runtime/ego-browser/screenshot-clip.d.mts +22 -0
- package/runtime/ego-browser/screenshot-clip.mjs +45 -0
- package/runtime/ego-linux/bin/ego-browser.mjs +399 -0
- package/runtime/ego-linux/src/agent-identity.mjs +65 -0
- package/runtime/ego-linux/src/chrome.mjs +867 -0
- package/runtime/ego-linux/src/cursor.mjs +1292 -0
- package/runtime/ego-linux/src/desktop.mjs +73 -0
- package/runtime/ego-linux/src/paths.mjs +35 -0
- package/runtime/ego-linux/src/session.mjs +37 -0
- package/runtime/ego-linux/src/shim.mjs +145 -0
- package/runtime/ego-linux/src/snapshot.mjs +424 -0
- package/runtime/ego-linux/src/spaces-server.mjs +355 -0
- package/runtime/ego-linux/src/spaces-ui.mjs +456 -0
- package/runtime/ego-linux/src/tabs.mjs +109 -0
- package/runtime/ego-linux/src/task-spaces.mjs +671 -0
- package/runtime/ego-linux/src/transport.mjs +321 -0
- package/runtime/ego-linux/src/window-fit.mjs +107 -0
- package/runtime/skills/ego-browser/SKILL.md +209 -0
- package/runtime/skills/ego-browser/agents/openai.yaml +7 -0
- package/runtime/skills/ego-browser/assets/composer-icon.png +0 -0
- package/runtime/skills/ego-browser/assets/logo.png +0 -0
- package/runtime/skills/ego-browser/learnings/google/browser-tools/autocomplete.js +11 -0
- package/runtime/skills/ego-browser/learnings/google/manifest.json +40 -0
- package/runtime/skills/ego-browser/learnings/google/notes/overview.md +23 -0
- package/runtime/skills/ego-browser/learnings/google/tools/search-extract.js +35 -0
- package/runtime/skills/ego-browser/learnings/x-com/browser-tools/extract-post.js +9 -0
- package/runtime/skills/ego-browser/learnings/x-com/manifest.json +51 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/overview.md +18 -0
- package/runtime/skills/ego-browser/learnings/x-com/notes/timeline.md +19 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/search-users.js +33 -0
- package/runtime/skills/ego-browser/learnings/x-com/tools/timeline.js +32 -0
- package/runtime/skills/ego-browser/references/install.md +131 -0
- package/runtime/skills/ego-browser/references/task-spaces.md +122 -0
- package/runtime/skills/ego-browser/references/video.md +17 -0
- package/runtime/skills/ego-browser/scripts/install.sh +309 -0
- package/index.js +0 -11
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
#!/bin/sh
|
|
2
|
+
# ego-browser — bundled --no-sandbox Chrome wrapper.
|
|
3
|
+
#
|
|
4
|
+
# Shipped INSIDE this plugin so it requires no host-side setup: root / Docker /
|
|
5
|
+
# CI environments refuse to run Chrome without `--no-sandbox`, and that flag
|
|
6
|
+
# cannot be passed through EGO_LINUX_CHROME (which takes a bare binary path).
|
|
7
|
+
# This wrapper finds a usable Chrome binary and execs it with `--no-sandbox`,
|
|
8
|
+
# forwarding every other flag the ego-linux CLI passes.
|
|
9
|
+
#
|
|
10
|
+
# It only ever ADDS --no-sandbox (via the wrapper) and never changes any other
|
|
11
|
+
# launch argument, so behavior on non-root machines is identical to pointing
|
|
12
|
+
# EGO_LINUX_CHROME straight at the binary.
|
|
13
|
+
set -eu
|
|
14
|
+
|
|
15
|
+
# Frame-rate uncap is OPT-IN and OFF by default. Measured on Chromium:
|
|
16
|
+
# --disable-frame-rate-limit (and worse, --disable-gpu-vsync) makes the compositor
|
|
17
|
+
# spin ~250% CPU even on a static page — a bad trade. As a consequence the
|
|
18
|
+
# watch-panel screencast stays at Chromium's native (throttled) cadence unless
|
|
19
|
+
# EGO_FRAME_RATE_UNCAP=1 is explicitly set by someone who wants higher FPS even
|
|
20
|
+
# if the page is not repainting. The worker's EGO_CAST_FPS_CAP and the frontend's
|
|
21
|
+
# rAF-coalesced frame flush are the low-cost levers; use those first.
|
|
22
|
+
EXTRA=""
|
|
23
|
+
if [ "${EGO_FRAME_RATE_UNCAP:-0}" = "1" ]; then
|
|
24
|
+
EXTRA="--disable-frame-rate-limit"
|
|
25
|
+
fi
|
|
26
|
+
|
|
27
|
+
# Resolve our own absolute path so we can refuse to exec ourselves. On root
|
|
28
|
+
# hosts the plugin sets EGO_LINUX_CHROME to this very wrapper (see
|
|
29
|
+
# resolveEgoEnv in lib/index.js); without this guard the first candidate below
|
|
30
|
+
# would exec us again — re-appending --no-sandbox on every pass — and spin
|
|
31
|
+
# forever instead of ever reaching a real browser binary.
|
|
32
|
+
SELF="$(readlink -f "$0" 2>/dev/null || echo "$0")"
|
|
33
|
+
|
|
34
|
+
# Candidate Chrome binaries, in preference order. The first that exists wins.
|
|
35
|
+
for bin in \
|
|
36
|
+
"${EGO_LINUX_CHROME:-}" \
|
|
37
|
+
/usr/bin/google-chrome-stable \
|
|
38
|
+
/usr/bin/google-chrome \
|
|
39
|
+
/usr/bin/chromium \
|
|
40
|
+
/usr/bin/chromium-browser \
|
|
41
|
+
/opt/google/chrome/google-chrome \
|
|
42
|
+
/usr/local/bin/google-chrome-stable \
|
|
43
|
+
/snap/bin/chromium
|
|
44
|
+
do
|
|
45
|
+
if [ -n "${bin:-}" ] && [ -x "${bin}" ]; then
|
|
46
|
+
if [ "$(readlink -f "${bin}" 2>/dev/null || echo "${bin}")" != "${SELF}" ]; then
|
|
47
|
+
exec "${bin}" --no-sandbox ${EXTRA} "$@"
|
|
48
|
+
fi
|
|
49
|
+
fi
|
|
50
|
+
done
|
|
51
|
+
|
|
52
|
+
echo "ego-browser wrapper: no Chrome/Chromium binary found (searched common paths). Set EGO_LINUX_CHROME to an absolute path." >&2
|
|
53
|
+
exit 127
|
|
@@ -0,0 +1,610 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* bin/cdp-render-worker.mjs — standalone render worker (阶段 10 / R8 seed).
|
|
4
|
+
*
|
|
5
|
+
* WHY A SEPARATE PROCESS, NOT A NEW PATH INSIDE THE CAST WORKER.
|
|
6
|
+
*
|
|
7
|
+
* The cast worker reconnects with `setTimeout(3000)` and a `while (true)`
|
|
8
|
+
* loop; it is built for a screencast that should survive a browser restart.
|
|
9
|
+
* The render worker is the opposite kind of process: it opens ONE connection,
|
|
10
|
+
* serves ONE page, and dies with it. Sharing the cast worker would mean a
|
|
11
|
+
* budget/trace loop whose lifetime is coupled to a panel nobody asked to open.
|
|
12
|
+
*
|
|
13
|
+
* It also gives the call surface its own lifetime. The M0.x layer already
|
|
14
|
+
* learned this (M0.2 §"重连后重放 enable 序列"): a reset connection loses every
|
|
15
|
+
* enable and every binding. Keeping the render surface on a process that never
|
|
16
|
+
* silently reconnects means "the connection is gone" is a fact the caller can
|
|
17
|
+
* act on, not a state that lies.
|
|
18
|
+
*
|
|
19
|
+
* IPC: stdin is a JSON-RPC line stream, stdout is one JSON reply per line.
|
|
20
|
+
* {"id":1,"method":"capture","params":{"marks":true,"limit":20}}
|
|
21
|
+
* {"id":1,"ok":true,"result":{...}}
|
|
22
|
+
* Keeping IPC JSON-RPC-shaped (not a bespoke format) is deliberate: the host
|
|
23
|
+
* spawns it through `ctx.subprocess` exactly like the CLI heredoc, so nothing
|
|
24
|
+
* in this file may depend on being started by our own code.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { createInterface } from 'node:readline'
|
|
28
|
+
import { normalizeRecordedElement } from './record-normalize.mjs'
|
|
29
|
+
|
|
30
|
+
const VERSION = 1
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The CDP call surface, bound once per connection.
|
|
34
|
+
*
|
|
35
|
+
* `sessionId` is load-bearing, not a detail: a connection to `…/devtools/browser/<id>`
|
|
36
|
+
* is a BROWSER-level endpoint, and page domains answer `'Accessibility.getFullAXTree'
|
|
37
|
+
* wasn't found` there. Measured on the first run of this worker — the commands
|
|
38
|
+
* that work without a session (`Target.getTargets`, `Browser.getVersion`) are
|
|
39
|
+
* exactly the ones that made the omission easy to miss.
|
|
40
|
+
*/
|
|
41
|
+
let state = {
|
|
42
|
+
wsUrl: '',
|
|
43
|
+
ws: null,
|
|
44
|
+
nextId: 1,
|
|
45
|
+
pending: new Map(),
|
|
46
|
+
connectedAt: 0,
|
|
47
|
+
sessionId: '',
|
|
48
|
+
targetId: '',
|
|
49
|
+
targetUrl: '',
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function log(message) {
|
|
53
|
+
process.stderr.write(`[cdp-render] ${message}\n`)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function reply(id, ok, payload) {
|
|
57
|
+
process.stdout.write(`${JSON.stringify({ v: VERSION, id, ok, ...payload })}\n`)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** One CDP command over the single connection. Rejects on timeout or close. */
|
|
61
|
+
function call(method, params = {}, sessionId = state.sessionId, timeoutMs = 15000) {
|
|
62
|
+
return new Promise((resolve, reject) => {
|
|
63
|
+
if (!state.ws || state.ws.readyState !== 1) {
|
|
64
|
+
reject(new Error('the render worker has no live connection'))
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
const id = state.nextId++
|
|
68
|
+
const timer = setTimeout(() => {
|
|
69
|
+
state.pending.delete(id)
|
|
70
|
+
reject(new Error(`${method} timed out after ${timeoutMs}ms`))
|
|
71
|
+
}, timeoutMs)
|
|
72
|
+
state.pending.set(id, { resolve, reject, timer, method })
|
|
73
|
+
const message = { id, method, params }
|
|
74
|
+
if (sessionId) message.sessionId = sessionId
|
|
75
|
+
try {
|
|
76
|
+
state.ws.send(JSON.stringify(message))
|
|
77
|
+
} catch (error) {
|
|
78
|
+
clearTimeout(timer)
|
|
79
|
+
state.pending.delete(id)
|
|
80
|
+
reject(error instanceof Error ? error : new Error(String(error)))
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Pick the page to serve and attach to it.
|
|
87
|
+
*
|
|
88
|
+
* Prefer an http(s) page: `about:blank` and internal pages have no AX tree worth
|
|
89
|
+
* numbering, and a caller that asked for a capture meant a real page. The choice
|
|
90
|
+
* is REPORTED (`targetId`, `targetUrl`) rather than implied, because "which tab
|
|
91
|
+
* did this image come from" is the first question when a capture looks wrong.
|
|
92
|
+
*/
|
|
93
|
+
async function attachPage(params) {
|
|
94
|
+
const wanted = String(params.targetId || '')
|
|
95
|
+
const listed = await call('Target.getTargets', {}, '', 8000)
|
|
96
|
+
const pages = (listed?.targetInfos || []).filter((info) => info.type === 'page')
|
|
97
|
+
if (pages.length === 0) throw new Error('the browser has no page target to render')
|
|
98
|
+
const chosen = wanted
|
|
99
|
+
? pages.find((info) => info.targetId === wanted)
|
|
100
|
+
: (pages.find((info) => /^https?:/i.test(String(info.url))) ?? pages[0])
|
|
101
|
+
if (!chosen) throw new Error(`no page target matches targetId ${wanted}`)
|
|
102
|
+
|
|
103
|
+
const attached = await call('Target.attachToTarget', { targetId: chosen.targetId, flatten: true }, '', 8000)
|
|
104
|
+
const sessionId = String(attached?.sessionId || '')
|
|
105
|
+
if (sessionId === '') throw new Error('Target.attachToTarget returned no sessionId')
|
|
106
|
+
state.sessionId = sessionId
|
|
107
|
+
state.targetId = chosen.targetId
|
|
108
|
+
state.targetUrl = String(chosen.url || '')
|
|
109
|
+
|
|
110
|
+
// Enable order is the M0.3 contract (src/cdp/events.ts): DOM before Overlay,
|
|
111
|
+
// Accessibility before the AX-tree read. An enable failure is reported here
|
|
112
|
+
// rather than surfacing later as a confusing "method wasn't found".
|
|
113
|
+
for (const domain of ['Page', 'Runtime', 'DOM', 'Accessibility']) {
|
|
114
|
+
await call(`${domain}.enable`, {}, sessionId, 10000)
|
|
115
|
+
}
|
|
116
|
+
return { targetId: chosen.targetId, targetUrl: String(chosen.url || ''), sessionId }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function connect(wsUrl, timeoutMs) {
|
|
120
|
+
if (state.ws) {
|
|
121
|
+
try { state.ws.close() } catch { /* already gone */ }
|
|
122
|
+
state.ws = null
|
|
123
|
+
}
|
|
124
|
+
const ws = new WebSocket(wsUrl)
|
|
125
|
+
await new Promise((resolve, reject) => {
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
try { ws.close() } catch { /* not open */ }
|
|
128
|
+
reject(new Error(`connect timed out after ${timeoutMs}ms`))
|
|
129
|
+
}, timeoutMs)
|
|
130
|
+
ws.addEventListener('open', () => { clearTimeout(timer); resolve() }, { once: true })
|
|
131
|
+
ws.addEventListener('error', () => { clearTimeout(timer); reject(new Error('websocket error during connect')) }, { once: true })
|
|
132
|
+
})
|
|
133
|
+
ws.addEventListener('message', (event) => {
|
|
134
|
+
let message
|
|
135
|
+
try { message = JSON.parse(String(event.data)) } catch { return }
|
|
136
|
+
if (typeof message.id !== 'number') return // an event, not a reply
|
|
137
|
+
const entry = state.pending.get(message.id)
|
|
138
|
+
if (!entry) return
|
|
139
|
+
clearTimeout(entry.timer)
|
|
140
|
+
state.pending.delete(message.id)
|
|
141
|
+
if (message.error) entry.reject(new Error(`${entry.method}: ${message.error.message}`))
|
|
142
|
+
else entry.resolve(message.result)
|
|
143
|
+
})
|
|
144
|
+
ws.addEventListener('close', () => {
|
|
145
|
+
for (const [, entry] of state.pending) {
|
|
146
|
+
clearTimeout(entry.timer)
|
|
147
|
+
entry.reject(new Error('the connection closed while a command was in flight'))
|
|
148
|
+
}
|
|
149
|
+
state.pending.clear()
|
|
150
|
+
state.ws = null
|
|
151
|
+
state.sessionId = ''
|
|
152
|
+
state.targetId = ''
|
|
153
|
+
state.targetUrl = ''
|
|
154
|
+
})
|
|
155
|
+
state.ws = ws
|
|
156
|
+
state.wsUrl = wsUrl
|
|
157
|
+
state.connectedAt = Date.now()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Structural roles that make a good CHAPTER.
|
|
162
|
+
*
|
|
163
|
+
* "Chapter" is the answer to "which part of the page is this": a form, a nav, a
|
|
164
|
+
* dialog. Chosen so the set is small and each member is a place a human would
|
|
165
|
+
* name out loud. A generic `div` is deliberately NOT one — it would shatter a
|
|
166
|
+
* page into hundreds of meaningless chapters, which is worse than not chaptering.
|
|
167
|
+
*/
|
|
168
|
+
const CHAPTER_ROLES = new Set([
|
|
169
|
+
'form', 'search', 'navigation', 'main', 'complementary', 'banner', 'contentinfo',
|
|
170
|
+
'dialog', 'alertdialog', 'region', 'article', 'list', 'listbox', 'menu', 'menubar',
|
|
171
|
+
'tablist', 'toolbar', 'table', 'grid', 'radiogroup', 'group', 'section',
|
|
172
|
+
'tabpanel', 'tree', 'feed', 'figure', 'details',
|
|
173
|
+
])
|
|
174
|
+
|
|
175
|
+
/** Roles to number candidates from. Mirrors src/jev/frame.ts. */
|
|
176
|
+
const INTERACTIVE_ROLES = new Set([
|
|
177
|
+
'button', 'link', 'textbox', 'searchbox', 'combobox', 'checkbox', 'radio',
|
|
178
|
+
'menuitem', 'menuitemcheckbox', 'menuitemradio', 'tab', 'option', 'switch', 'slider',
|
|
179
|
+
])
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Parent links for every AX node, built from `childIds`.
|
|
183
|
+
*
|
|
184
|
+
* `getFullAXTree` returns a FLAT list; the hierarchy only exists through the
|
|
185
|
+
* child ids. `parentId` is also honoured when present, because which of the two
|
|
186
|
+
* a given Chrome build populates has changed before — and silently getting an
|
|
187
|
+
* empty parent map would make every candidate land in one chapter, which looks
|
|
188
|
+
* like "the page has one section" rather than like a bug.
|
|
189
|
+
*/
|
|
190
|
+
function parentMap(nodes) {
|
|
191
|
+
const parent = new Map()
|
|
192
|
+
for (const node of nodes) {
|
|
193
|
+
const id = String(node.nodeId ?? '')
|
|
194
|
+
if (id === '') continue
|
|
195
|
+
const children = Array.isArray(node.childIds) ? node.childIds : []
|
|
196
|
+
for (const child of children) parent.set(String(child), id)
|
|
197
|
+
if (node.parentId !== undefined && node.parentId !== null) parent.set(id, String(node.parentId))
|
|
198
|
+
}
|
|
199
|
+
return parent
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The nearest structural ancestor of a node, as a chapter descriptor.
|
|
204
|
+
*
|
|
205
|
+
* NEAREST, not outermost: a button inside a form inside main belongs to the
|
|
206
|
+
* form. Taking the outermost would put half the page in "main" and lose exactly
|
|
207
|
+
* the narrowing this exists to provide. Depth-capped so a pathological tree
|
|
208
|
+
* cannot spin here.
|
|
209
|
+
*/
|
|
210
|
+
function chapterOf(nodeId, byId, parent) {
|
|
211
|
+
let current = parent.get(String(nodeId))
|
|
212
|
+
let depth = 0
|
|
213
|
+
while (current !== undefined && depth < 64) {
|
|
214
|
+
const ancestor = byId.get(current)
|
|
215
|
+
if (ancestor !== undefined && ancestor.ignored !== true) {
|
|
216
|
+
const role = typeof ancestor.role?.value === 'string' ? ancestor.role.value : ''
|
|
217
|
+
if (CHAPTER_ROLES.has(role)) {
|
|
218
|
+
const name = typeof ancestor.name?.value === 'string' ? ancestor.name.value.trim() : ''
|
|
219
|
+
return { role, name, id: current }
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
current = parent.get(current)
|
|
223
|
+
depth += 1
|
|
224
|
+
}
|
|
225
|
+
return null
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Count the interactive candidates of a page, WITH each one's chapter.
|
|
230
|
+
*
|
|
231
|
+
* The whole point of the count is that it decides whether the caller must
|
|
232
|
+
* chunk; that decision must therefore not depend on a rendered image.
|
|
233
|
+
*
|
|
234
|
+
* `container` is a short stable KEY (`form#2`) because a `choice` key is returned
|
|
235
|
+
* verbatim by the model — a long key costs tokens on every round. `containerLabel`
|
|
236
|
+
* carries the readable form (`the form "Shipping"`) for the prompt's prose and the
|
|
237
|
+
* trace. Same-role chapters are numbered in document order, so a page with three
|
|
238
|
+
* forms yields form#1..#3 rather than three chapters all called "form".
|
|
239
|
+
*/
|
|
240
|
+
async function gatherInteractive(limit) {
|
|
241
|
+
const ax = await call('Accessibility.getFullAXTree', {})
|
|
242
|
+
const nodes = Array.isArray(ax?.nodes) ? ax.nodes : []
|
|
243
|
+
const byId = new Map()
|
|
244
|
+
for (const node of nodes) byId.set(String(node.nodeId ?? ''), node)
|
|
245
|
+
const parent = parentMap(nodes)
|
|
246
|
+
|
|
247
|
+
const out = []
|
|
248
|
+
const seen = new Set()
|
|
249
|
+
const roleCounts = new Map()
|
|
250
|
+
for (const node of nodes) {
|
|
251
|
+
if (out.length >= limit) break
|
|
252
|
+
if (node.ignored === true) continue
|
|
253
|
+
const role = typeof node.role?.value === 'string' ? node.role.value : ''
|
|
254
|
+
if (!INTERACTIVE_ROLES.has(role)) continue
|
|
255
|
+
const backendNodeId = Number.parseInt(String(node.nodeId ?? ''), 10)
|
|
256
|
+
if (!Number.isFinite(backendNodeId) || seen.has(backendNodeId)) continue
|
|
257
|
+
seen.add(backendNodeId)
|
|
258
|
+
|
|
259
|
+
const chapter = chapterOf(node.nodeId, byId, parent)
|
|
260
|
+
let key = 'page'
|
|
261
|
+
let label = 'the page itself (no enclosing section)'
|
|
262
|
+
if (chapter !== null) {
|
|
263
|
+
const seenSoFar = (roleCounts.get(chapter.role) ?? 0) + 1
|
|
264
|
+
roleCounts.set(chapter.role, seenSoFar)
|
|
265
|
+
key = `${chapter.role}#${seenSoFar}`
|
|
266
|
+
label = chapter.name === ''
|
|
267
|
+
? `the ${chapter.role} (${seenSoFar === 1 ? 'first' : `#${seenSoFar}`} on the page)`
|
|
268
|
+
: `the ${chapter.role} "${chapter.name}"`
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
out.push({
|
|
272
|
+
n: out.length + 1,
|
|
273
|
+
backendNodeId,
|
|
274
|
+
role,
|
|
275
|
+
name: typeof node.name?.value === 'string' ? node.name.value : '',
|
|
276
|
+
container: key,
|
|
277
|
+
containerLabel: label,
|
|
278
|
+
})
|
|
279
|
+
}
|
|
280
|
+
return out
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Act on a numbered candidate, re-measuring first — or reload the page.
|
|
285
|
+
*
|
|
286
|
+
* This mirrors `src/jev/act.ts`. That module declares the DISCIPLINE and is
|
|
287
|
+
* unit-tested plugin-side against a scripted fake; the actual CDP calls have to
|
|
288
|
+
* live here, because the plugin's Node process has no CDP channel (every
|
|
289
|
+
* `src/cdp/*` module runs inside a worker like this one).
|
|
290
|
+
*
|
|
291
|
+
* The discipline, unchanged: a rect from the frame is NEVER the click target.
|
|
292
|
+
* backendNodeId -> DOM.getBoxModel (fresh) -> DOM.getNodeForLocation (pre)
|
|
293
|
+
* -> click -> DOM.getNodeForLocation (post)
|
|
294
|
+
* The pre-check is what catches an overlay WITHOUT dispatching a stray click.
|
|
295
|
+
*/
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Best-effort faithful record of the element just acted on.
|
|
299
|
+
*
|
|
300
|
+
* One extra `DOM.getOuterHTML` call — only on the element we actually touched,
|
|
301
|
+
* never on every candidate. Recording is best-effort: a failure here must not
|
|
302
|
+
* turn a successful click into a failed one, so it returns null and the act
|
|
303
|
+
* result simply omits `recorded`.
|
|
304
|
+
*
|
|
305
|
+
* `normalizeRecordedElement` preserves locating features (class, id, role, …) and
|
|
306
|
+
* only prunes known inspector-chrome tokens — that is the locked rule.
|
|
307
|
+
*/
|
|
308
|
+
async function recordElement(backendNodeId) {
|
|
309
|
+
try {
|
|
310
|
+
const res = await call('DOM.getOuterHTML', { backendNodeId })
|
|
311
|
+
const html = typeof res?.outerHTML === 'string' ? res.outerHTML : ''
|
|
312
|
+
if (html === '') return null
|
|
313
|
+
return normalizeRecordedElement(html, backendNodeId)
|
|
314
|
+
} catch {
|
|
315
|
+
return null
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async function actOnCandidate(params) {
|
|
320
|
+
const backendNodeId = Number(params.backendNodeId)
|
|
321
|
+
const action = String(params.action || 'click')
|
|
322
|
+
if (state.sessionId === '') await attachPage(params)
|
|
323
|
+
|
|
324
|
+
// `reload` is checked BEFORE the candidate check on purpose: it is a page-level
|
|
325
|
+
// action with no target, and requiring a backendNodeId would make the one
|
|
326
|
+
// recovery most likely to help the one that cannot be requested.
|
|
327
|
+
if (action === 'reload') {
|
|
328
|
+
await call('Page.reload', { ignoreCache: true }, undefined, 25000)
|
|
329
|
+
// A reload must settle before the next capture, or the frame shows a
|
|
330
|
+
// half-built page and the judgement that follows is about nothing. Waited
|
|
331
|
+
// here rather than in the caller because only this process sees the document.
|
|
332
|
+
const settled = await waitForLoad(25000)
|
|
333
|
+
return {
|
|
334
|
+
ok: true,
|
|
335
|
+
code: 'ok',
|
|
336
|
+
action: 'reload',
|
|
337
|
+
backendNodeId: 0,
|
|
338
|
+
point: { x: 0, y: 0 },
|
|
339
|
+
measured: null,
|
|
340
|
+
drift: 0,
|
|
341
|
+
settled,
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (!Number.isFinite(backendNodeId) || backendNodeId <= 0) {
|
|
346
|
+
return { ok: false, code: 'no-candidate', message: 'act needs a positive backendNodeId' }
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (action === 'scroll') {
|
|
350
|
+
const deltaY = Number(params.deltaY)
|
|
351
|
+
if (!Number.isFinite(deltaY) || deltaY === 0) {
|
|
352
|
+
return { ok: false, code: 'bad-delta', message: 'scroll needs a non-zero deltaY' }
|
|
353
|
+
}
|
|
354
|
+
// A wheel event needs a point; the viewport centre is neutral and needs no
|
|
355
|
+
// measurement.
|
|
356
|
+
const centre = await viewportCentre()
|
|
357
|
+
await call('Input.dispatchMouseEvent', {
|
|
358
|
+
type: 'mouseWheel', x: centre.x, y: centre.y, deltaX: 0, deltaY, button: 'none', buttons: 0, clickCount: 0,
|
|
359
|
+
})
|
|
360
|
+
return { ok: true, code: 'ok', action: 'scroll', backendNodeId: 0, point: centre, measured: null, drift: 0 }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (action === 'fill') {
|
|
364
|
+
const text = String(params.text ?? '')
|
|
365
|
+
if (text === '') return { ok: false, code: 'empty-text', message: 'fill needs non-empty text' }
|
|
366
|
+
const measured = await measure(backendNodeId)
|
|
367
|
+
if (!measured.ok) return measured
|
|
368
|
+
// Focus then insert. NEVER assign `.value`: a controlled input re-renders
|
|
369
|
+
// from its own state and would wipe it, and no input/change event fires, so
|
|
370
|
+
// the page believes the field is empty while a screenshot shows text.
|
|
371
|
+
await call('DOM.focus', { backendNodeId })
|
|
372
|
+
await call('Input.insertText', { text })
|
|
373
|
+
const recorded = await recordElement(backendNodeId)
|
|
374
|
+
return { ok: true, code: 'ok', action: 'fill', backendNodeId, point: measured.centre, measured: measured.rect, drift: measured.drift, ...(recorded === null ? {} : { recorded }) }
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
const measured = await measure(backendNodeId)
|
|
378
|
+
if (!measured.ok) return measured
|
|
379
|
+
|
|
380
|
+
// PRE-check: is this node still the topmost thing at the measured point? Run
|
|
381
|
+
// before dispatching, so an overlay costs nothing instead of costing a click.
|
|
382
|
+
const hit = await call('DOM.getNodeForLocation', {
|
|
383
|
+
x: Math.round(measured.centre.x), y: Math.round(measured.centre.y), includeUserAgentShadowDOM: false,
|
|
384
|
+
})
|
|
385
|
+
if (Number(hit?.backendNodeId) !== backendNodeId) {
|
|
386
|
+
const at = Math.round(measured.centre.x) + ',' + Math.round(measured.centre.y)
|
|
387
|
+
return {
|
|
388
|
+
ok: false,
|
|
389
|
+
code: 'click-missed',
|
|
390
|
+
message: 'candidate measured to ' + at + ' but that point resolves to backendNodeId ' +
|
|
391
|
+
String(hit?.backendNodeId) + ' - something is on top of it or the page moved',
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) {
|
|
396
|
+
await call('Input.dispatchMouseEvent', {
|
|
397
|
+
type,
|
|
398
|
+
x: Math.round(measured.centre.x),
|
|
399
|
+
y: Math.round(measured.centre.y),
|
|
400
|
+
button: 'left',
|
|
401
|
+
buttons: type === 'mousePressed' ? 1 : 0,
|
|
402
|
+
clickCount: type === 'mouseMoved' ? 0 : 1,
|
|
403
|
+
})
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// POST-check: a mid-flight re-layout is reported, not hidden.
|
|
407
|
+
const after = await call('DOM.getNodeForLocation', {
|
|
408
|
+
x: Math.round(measured.centre.x), y: Math.round(measured.centre.y), includeUserAgentShadowDOM: false,
|
|
409
|
+
})
|
|
410
|
+
if (Number(after?.backendNodeId) !== backendNodeId) {
|
|
411
|
+
return { ok: false, code: 'click-missed', message: 'the click dispatched but the point now resolves to a different node' }
|
|
412
|
+
}
|
|
413
|
+
const recorded = await recordElement(backendNodeId)
|
|
414
|
+
return { ok: true, code: 'ok', action: 'click', backendNodeId, point: measured.centre, measured: measured.rect, drift: measured.drift, ...(recorded === null ? {} : { recorded }) }
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** A current box model plus the point to act on, for one node. */
|
|
418
|
+
async function measure(backendNodeId) {
|
|
419
|
+
let model
|
|
420
|
+
try {
|
|
421
|
+
model = await call('DOM.getBoxModel', { backendNodeId })
|
|
422
|
+
} catch (error) {
|
|
423
|
+
return { ok: false, code: 'no-box-model', message: error instanceof Error ? error.message : String(error) }
|
|
424
|
+
}
|
|
425
|
+
const rect = quadToRect(model?.model?.content)
|
|
426
|
+
if (rect === null) return { ok: false, code: 'no-box-model', message: 'DOM.getBoxModel returned no usable content quad' }
|
|
427
|
+
// CDP boxes are DOCUMENT space; input coordinates are VIEWPORT space. Adding
|
|
428
|
+
// the scroll offset back is what keeps a click on the right element after the
|
|
429
|
+
// page has scrolled - the bug that only shows up on scrolled pages, i.e.
|
|
430
|
+
// never during a smoke test.
|
|
431
|
+
const scroll = await readScroll()
|
|
432
|
+
const viewportRect = { ...rect, x: rect.x - scroll.x, y: rect.y - scroll.y }
|
|
433
|
+
return {
|
|
434
|
+
ok: true,
|
|
435
|
+
rect: viewportRect,
|
|
436
|
+
centre: { x: viewportRect.x + viewportRect.width / 2, y: viewportRect.y + viewportRect.height / 2 },
|
|
437
|
+
drift: 0,
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** The page's scroll offset; zero when it cannot be read. */
|
|
442
|
+
async function readScroll() {
|
|
443
|
+
try {
|
|
444
|
+
const result = await call('Runtime.evaluate', { expression: '[window.scrollX, window.scrollY]', returnByValue: true })
|
|
445
|
+
const value = result?.result?.value
|
|
446
|
+
if (Array.isArray(value) && value.length >= 2) return { x: Number(value[0]) || 0, y: Number(value[1]) || 0 }
|
|
447
|
+
} catch { /* a missing scroll offset must not fail the action */ }
|
|
448
|
+
return { x: 0, y: 0 }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** The viewport centre, for an action that needs a point but no target. */
|
|
452
|
+
async function viewportCentre() {
|
|
453
|
+
try {
|
|
454
|
+
const metrics = await call('Page.getLayoutMetrics', {})
|
|
455
|
+
const visual = metrics?.cssVisualViewport || metrics?.visualViewport
|
|
456
|
+
const w = Number(visual?.clientWidth) || 0
|
|
457
|
+
const h = Number(visual?.clientHeight) || 0
|
|
458
|
+
if (w > 0 && h > 0) return { x: Math.round(w / 2), y: Math.round(h / 2) }
|
|
459
|
+
} catch { /* fall through to the origin */ }
|
|
460
|
+
return { x: 0, y: 0 }
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* Wait for the document to finish loading, bounded.
|
|
465
|
+
*
|
|
466
|
+
* Polls `document.readyState` rather than subscribing to `Page.loadEventFired`,
|
|
467
|
+
* because the event may already have fired between the reload ack and this call,
|
|
468
|
+
* and a listener added after the fact waits forever. Bounded because a page that
|
|
469
|
+
* never reaches `complete` (a hanging resource) must not hang the worker.
|
|
470
|
+
*/
|
|
471
|
+
async function waitForLoad(timeoutMs) {
|
|
472
|
+
const deadline = Date.now() + timeoutMs
|
|
473
|
+
while (Date.now() < deadline) {
|
|
474
|
+
try {
|
|
475
|
+
const result = await call('Runtime.evaluate', { expression: 'document.readyState', returnByValue: true }, undefined, 5000)
|
|
476
|
+
const readyState = result?.result?.value
|
|
477
|
+
if (readyState === 'complete' || readyState === 'interactive') return true
|
|
478
|
+
} catch { /* keep polling until the deadline */ }
|
|
479
|
+
await new Promise((resolve) => setTimeout(resolve, 150))
|
|
480
|
+
}
|
|
481
|
+
return false
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** A CDP quad is 8 numbers: x1,y1 .. x4,y4. */
|
|
485
|
+
function quadToRect(quad) {
|
|
486
|
+
if (!Array.isArray(quad) || quad.length < 8) return null
|
|
487
|
+
const xs = [Number(quad[0]), Number(quad[2]), Number(quad[4]), Number(quad[6])]
|
|
488
|
+
const ys = [Number(quad[1]), Number(quad[3]), Number(quad[5]), Number(quad[7])]
|
|
489
|
+
if ([...xs, ...ys].some((value) => !Number.isFinite(value))) return null
|
|
490
|
+
const x = Math.min(...xs)
|
|
491
|
+
const y = Math.min(...ys)
|
|
492
|
+
return { x, y, width: Math.max(...xs) - x, height: Math.max(...ys) - y }
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async function viewportInfo() {
|
|
496
|
+
const fallback = { width: 0, height: 0, scrollX: 0, scrollY: 0, devicePixelRatio: 1 }
|
|
497
|
+
try {
|
|
498
|
+
const metrics = await call('Page.getLayoutMetrics', {})
|
|
499
|
+
const visual = metrics?.cssVisualViewport || metrics?.visualViewport
|
|
500
|
+
const css = Number(visual?.clientWidth) || 0
|
|
501
|
+
const physical = Number(metrics?.contentSize?.width) || 0
|
|
502
|
+
const devicePixelRatio = css > 0 && physical > 0 ? Math.max(1, Math.round((physical / css) * 100) / 100) : 1
|
|
503
|
+
const pageX = Number(visual?.pageX) || 0
|
|
504
|
+
const pageY = Number(visual?.pageY) || 0
|
|
505
|
+
return {
|
|
506
|
+
width: css || 0,
|
|
507
|
+
height: Number(visual?.clientHeight) || 0,
|
|
508
|
+
// `pageX/pageY` is what CDP calls the scroll offset; `scrollX` is not a
|
|
509
|
+
// field on this reply, and inventing a runtime evaluate round trip for it
|
|
510
|
+
// would make a capture cost one more command for no new information.
|
|
511
|
+
scrollX: pageX,
|
|
512
|
+
scrollY: pageY,
|
|
513
|
+
devicePixelRatio,
|
|
514
|
+
}
|
|
515
|
+
} catch {
|
|
516
|
+
return fallback
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
async function handle(method, params) {
|
|
521
|
+
switch (method) {
|
|
522
|
+
case 'hello':
|
|
523
|
+
return { version: VERSION, connected: state.ws !== null, wsUrl: state.wsUrl, sessionId: state.sessionId }
|
|
524
|
+
case 'connect': {
|
|
525
|
+
await connect(String(params.wsUrl || ''), Number(params.timeoutMs) || 8000)
|
|
526
|
+
const attached = await attachPage(params)
|
|
527
|
+
return { wsUrl: state.wsUrl, ...attached }
|
|
528
|
+
}
|
|
529
|
+
case 'interactive':
|
|
530
|
+
return { candidates: await gatherInteractive(Number(params.limit) || 20) }
|
|
531
|
+
case 'capture': {
|
|
532
|
+
if (params.attach !== false && state.sessionId === '') await attachPage(params)
|
|
533
|
+
const shot = await captureWithinBudget({
|
|
534
|
+
format: params.format === 'png' ? 'png' : 'jpeg',
|
|
535
|
+
quality: Number(params.quality) || 72,
|
|
536
|
+
maxBytes: Number(params.maxBytes) || 0,
|
|
537
|
+
scale: params.scale || {},
|
|
538
|
+
marks: params.marks !== false,
|
|
539
|
+
limit: Number(params.limit) || 20,
|
|
540
|
+
measureRects: params.measureRects !== false,
|
|
541
|
+
})
|
|
542
|
+
// The marks are gathered AFTER the shot on purpose: the numbering the
|
|
543
|
+
// caller receives must describe the page the image shows, and a gather
|
|
544
|
+
// that runs first can drift on a page that renders asynchronously.
|
|
545
|
+
const candidates = params.marks === false ? [] : await gatherInteractive(Number(params.limit) || 20)
|
|
546
|
+
const viewport = await viewportInfo()
|
|
547
|
+
return {
|
|
548
|
+
...shot,
|
|
549
|
+
marks: candidates,
|
|
550
|
+
viewport,
|
|
551
|
+
pixelRatio: viewport.devicePixelRatio,
|
|
552
|
+
targetId: state.targetId,
|
|
553
|
+
targetUrl: state.targetUrl,
|
|
554
|
+
sessionId: state.sessionId,
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
case 'act':
|
|
558
|
+
return actOnCandidate(params)
|
|
559
|
+
case 'navigate': {
|
|
560
|
+
if (state.sessionId === '') await attachPage(params)
|
|
561
|
+
const url = String(params.url || '')
|
|
562
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
563
|
+
throw new Error(`navigate needs an absolute http(s) URL, got "${url}"`)
|
|
564
|
+
}
|
|
565
|
+
await call('Page.navigate', { url }, undefined, 25000)
|
|
566
|
+
const loaded = await waitForLoad(Number(params.timeoutMs) || 25000)
|
|
567
|
+
// `state.targetUrl` is written once at attach and nothing else updates
|
|
568
|
+
// it, so a post-navigation capture would label the frame with the OLD
|
|
569
|
+
// address. Read the page's own location — the FINAL url after redirects,
|
|
570
|
+
// not the requested one — and keep it for later captures.
|
|
571
|
+
let finalUrl = url
|
|
572
|
+
try {
|
|
573
|
+
const loc = await call('Runtime.evaluate', { expression: 'location.href', returnByValue: true }, undefined, 5000)
|
|
574
|
+
if (typeof loc?.result?.value === 'string' && loc.result.value !== '') {
|
|
575
|
+
finalUrl = loc.result.value
|
|
576
|
+
state.targetUrl = finalUrl
|
|
577
|
+
}
|
|
578
|
+
} catch { /* keep the requested URL as the label */ }
|
|
579
|
+
return { ok: true, url: finalUrl, loaded }
|
|
580
|
+
}
|
|
581
|
+
case 'ping':
|
|
582
|
+
return { pong: true, connected: state.ws !== null, uptimeMs: state.connectedAt ? Date.now() - state.connectedAt : 0 }
|
|
583
|
+
default:
|
|
584
|
+
throw new Error(`unknown method "${method}"`)
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const rl = createInterface({ input: process.stdin, terminal: false })
|
|
589
|
+
let chain = Promise.resolve()
|
|
590
|
+
rl.on('line', (line) => {
|
|
591
|
+
const text = line.trim()
|
|
592
|
+
if (text === '') return
|
|
593
|
+
chain = chain.then(async () => {
|
|
594
|
+
let request
|
|
595
|
+
try { request = JSON.parse(text) } catch { reply(null, false, { error: { code: 'bad-json', message: 'request was not JSON' } }); return }
|
|
596
|
+
const id = request.id ?? null
|
|
597
|
+
try {
|
|
598
|
+
const result = await handle(String(request.method || ''), request.params || {})
|
|
599
|
+
reply(id, true, { result })
|
|
600
|
+
} catch (error) {
|
|
601
|
+
reply(id, false, { error: { code: 'call-failed', message: error instanceof Error ? error.message : String(error) } })
|
|
602
|
+
}
|
|
603
|
+
})
|
|
604
|
+
})
|
|
605
|
+
rl.on('close', () => {
|
|
606
|
+
if (state.ws) { try { state.ws.close() } catch { /* already gone */ } }
|
|
607
|
+
process.exit(0)
|
|
608
|
+
})
|
|
609
|
+
|
|
610
|
+
log(`ready (pid ${process.pid}, node ${process.version})`)
|