| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447 |
- /**
- * 浏览器控制(Chrome / Edge DevTools 协议)
- * ------------------------------------------------
- * 引擎本身没有给模型"操作网页"的工具,右侧栏只是展示页面。这里自己连 CDP:
- * 启动一个独立的浏览器实例(独立 profile,不碰老师的日常浏览器)
- * → 用 HTTP 接口开页签 → 用 WebSocket 发命令(点击/输入/取文字/截图)。
- *
- * 为什么自己写 WebSocket:插件不在 dsh-runtime 的模块解析链上,裸 import 'ws' 会失败。
- * CDP 的帧结构简单(文本帧 + 长度前缀),自己实现比打进一份依赖更可控。
- *
- * 安全边界:只允许 http/https;file:// 与 chrome:// 一律拒绝,
- * 否则等于给对话开了一个任意读本地文件的口子。
- */
- import net from 'node:net'
- import crypto from 'node:crypto'
- import fs from 'node:fs'
- import path from 'node:path'
- import { spawn } from 'node:child_process'
- import { findBrowserExe } from './office.mjs'
- const MAX_TEXT = 20_000
- const CMD_TIMEOUT = 30_000
- // --------------------------------------------------------------- 最小 WebSocket
- class MiniWS {
- constructor (url) {
- const m = /^ws:\/\/([^/:]+)(?::(\d+))?(\/.*)?$/.exec(url)
- if (!m) throw new Error(`无法识别的 WebSocket 地址:${url}`)
- this.host = m[1]
- this.port = Number(m[2] || 80)
- this.path = m[3] || '/'
- this.buf = Buffer.alloc(0)
- this.frag = null
- this.closed = false
- this.handlers = { message: [], close: [] }
- }
- on (event, fn) { this.handlers[event].push(fn) }
- open () {
- return new Promise((resolve, reject) => {
- const key = crypto.randomBytes(16).toString('base64')
- this.socket = net.connect(this.port, this.host, () => {
- this.socket.write(
- `GET ${this.path} HTTP/1.1\r\nHost: ${this.host}:${this.port}\r\n` +
- 'Upgrade: websocket\r\nConnection: Upgrade\r\n' +
- `Sec-WebSocket-Key: ${key}\r\nSec-WebSocket-Version: 13\r\n\r\n`
- )
- })
- this.socket.setNoDelay(true)
- let handshook = false
- this.socket.on('data', (chunk) => {
- if (!handshook) {
- if (!chunk.includes('\r\n\r\n')) { this.buf = Buffer.concat([this.buf, chunk]); return }
- const text = chunk.toString('latin1')
- const idx = text.indexOf('\r\n\r\n')
- if (!/^HTTP\/1\.1 101/i.test(text)) {
- this.closed = true
- this.socket.destroy()
- return reject(new Error(`WebSocket 握手失败:${text.split('\r\n')[0]}`))
- }
- handshook = true
- this.buf = chunk.subarray(idx + 4)
- resolve()
- this._drain()
- return
- }
- this.buf = Buffer.concat([this.buf, chunk])
- this._drain()
- })
- this.socket.on('error', (err) => { if (!handshook) reject(err); this._emit('close') })
- this.socket.on('close', () => { this.closed = true; this._emit('close') })
- this.socket.setTimeout(0)
- })
- }
- _emit (event, arg) { for (const fn of this.handlers[event]) fn(arg) }
- _drain () {
- for (;;) {
- if (this.buf.length < 2) return
- const b0 = this.buf[0]
- const b1 = this.buf[1]
- const fin = (b0 & 0x80) !== 0
- const opcode = b0 & 0x0f
- const masked = (b1 & 0x80) !== 0
- let len = b1 & 0x7f
- let off = 2
- if (len === 126) {
- if (this.buf.length < 4) return
- len = this.buf.readUInt16BE(2); off = 4
- } else if (len === 127) {
- if (this.buf.length < 10) return
- len = Number(this.buf.readBigUInt64BE(2)); off = 10
- }
- let mask = null
- if (masked) {
- if (this.buf.length < off + 4) return
- mask = this.buf.subarray(off, off + 4); off += 4
- }
- if (this.buf.length < off + len) return
- let payload = this.buf.subarray(off, off + len)
- if (mask) {
- const copy = Buffer.allocUnsafe(len)
- for (let i = 0; i < len; i++) copy[i] = payload[i] ^ mask[i % 4]
- payload = copy
- }
- this.buf = this.buf.subarray(off + len)
- if (opcode === 0x1 || opcode === 0x0) {
- this.frag = this.frag ? Buffer.concat([this.frag, payload]) : payload
- if (fin) { const msg = this.frag.toString('utf8'); this.frag = null; this._emit('message', msg) }
- } else if (opcode === 0x8) {
- this.closed = true
- this.socket.end()
- this._emit('close')
- return
- } else if (opcode === 0x9) {
- this._frame(0x0a, payload)
- }
- }
- }
- _frame (opcode, payload) {
- const data = Buffer.isBuffer(payload) ? payload : Buffer.from(String(payload), 'utf8')
- const mask = crypto.randomBytes(4)
- let header
- if (data.length < 126) {
- header = Buffer.alloc(6)
- header[1] = 0x80 | data.length
- } else if (data.length < 65536) {
- header = Buffer.alloc(8)
- header[1] = 0x80 | 126
- header.writeUInt16BE(data.length, 2)
- } else {
- header = Buffer.alloc(14)
- header[1] = 0x80 | 127
- header.writeBigUInt64BE(BigInt(data.length), 2)
- }
- header[0] = 0x80 | opcode
- mask.copy(header, header.length - 4)
- const masked = Buffer.allocUnsafe(data.length)
- for (let i = 0; i < data.length; i++) masked[i] = data[i] ^ mask[i % 4]
- try { this.socket.write(Buffer.concat([header, masked])) } catch { /* 连接已断 */ }
- }
- send (text) { this._frame(0x1, text) }
- close () {
- if (this.closed) return
- this.closed = true
- try { this._frame(0x8, Buffer.alloc(0)) } catch { /* ignore */ }
- try { this.socket.end() } catch { /* ignore */ }
- }
- }
- // --------------------------------------------------------------- CDP 会话
- class CDP {
- constructor (wsUrl) {
- this.ws = new MiniWS(wsUrl)
- this.seq = 0
- this.pending = new Map()
- }
- async connect () {
- await this.ws.open()
- this.ws.on('message', (text) => {
- let msg
- try { msg = JSON.parse(text) } catch { return }
- if (msg.id && this.pending.has(msg.id)) {
- const { resolve, reject, timer } = this.pending.get(msg.id)
- clearTimeout(timer)
- this.pending.delete(msg.id)
- if (msg.error) reject(new Error(msg.error.message || '浏览器返回错误'))
- else resolve(msg.result)
- }
- })
- this.ws.on('close', () => {
- for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(new Error('浏览器连接已断开')) }
- this.pending.clear()
- })
- return this
- }
- send (method, params = {}) {
- const id = ++this.seq
- return new Promise((resolve, reject) => {
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`浏览器命令超时:${method}`)) }, CMD_TIMEOUT)
- this.pending.set(id, { resolve, reject, timer })
- this.ws.send(JSON.stringify({ id, method, params }))
- })
- }
- async evaluate (expression) {
- const res = await this.send('Runtime.evaluate', {
- expression, returnByValue: true, awaitPromise: true, userGesture: true
- })
- if (res.exceptionDetails) {
- throw new Error(res.exceptionDetails.exception?.description || res.exceptionDetails.text || '页面脚本执行失败')
- }
- return res.result?.value
- }
- close () { this.ws.close() }
- }
- // --------------------------------------------------------------- HTTP 小工具
- async function httpJson (url, method = 'GET') {
- const res = await fetch(url, { method })
- const text = await res.text()
- try { return JSON.parse(text) } catch { return { raw: text, status: res.status } }
- }
- async function waitFor (fn, { timeout = 20_000, interval = 250, what = '等待超时' } = {}) {
- const end = Date.now() + timeout
- let lastErr
- while (Date.now() < end) {
- try {
- const v = await fn()
- if (v) return v
- } catch (err) { lastErr = err }
- await new Promise((r) => setTimeout(r, interval))
- }
- throw new Error(lastErr ? `${what}:${lastErr.message}` : what)
- }
- // --------------------------------------------------------------- 浏览器实例
- export function createBrowserController ({ userDataDir, browserExe, headless = true } = {}) {
- const profileDir = userDataDir || path.join(process.env.TEMP || '.', 'cocobuddy-browser')
- let proc = null
- let port = 0
- const alive = async (p) => {
- try {
- const v = await httpJson(`http://127.0.0.1:${p}/json/version`, 'GET')
- return !!(v && v.webSocketDebuggerUrl)
- } catch { return false }
- }
- async function ensureRunning () {
- if (port && await alive(port)) return port
- const exe = findBrowserExe(browserExe)
- if (!exe) throw new Error('这台电脑上没有找到 Chrome 或 Edge,无法打开网页')
- fs.mkdirSync(profileDir, { recursive: true })
- // 端口随机挑,避免和老师自己开着的调试端口撞车
- const candidates = [0, 0, 0].map(() => 9300 + Math.floor(Math.random() * 400))
- for (const candidate of candidates) {
- if (await alive(candidate)) { port = candidate; return port }
- const args = [
- `--remote-debugging-port=${candidate}`,
- `--user-data-dir=${profileDir}`,
- '--no-first-run', '--no-default-browser-check', '--disable-extensions',
- '--disable-background-networking', '--disable-sync', '--disable-features=Translate'
- ]
- if (headless) args.push('--headless=new', '--disable-gpu')
- args.push('about:blank')
- proc = spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true })
- proc.unref()
- proc.on('error', () => {})
- try {
- await waitFor(() => alive(candidate), { timeout: 20_000, interval: 400, what: '浏览器启动超时' })
- port = candidate
- return port
- } catch {
- try { proc.kill() } catch { /* ignore */ }
- }
- }
- throw new Error('浏览器没能启动(可能被安全软件拦了),请重试一次')
- }
- async function listTabs () {
- const p = await ensureRunning()
- const list = await httpJson(`http://127.0.0.1:${p}/json/list`)
- return (Array.isArray(list) ? list : []).filter((t) => t.type === 'page')
- }
- async function newTab (url) {
- const p = await ensureRunning()
- const target = `http://127.0.0.1:${p}/json/new?${encodeURIComponent(url || 'about:blank')}`
- // Chrome 111+ 要求 PUT,老版本只认 GET,两种都试
- let tab
- try { tab = await httpJson(target, 'PUT') } catch { tab = await httpJson(target, 'GET') }
- if (!tab || !tab.id) throw new Error('没能新建浏览器页签')
- return tab
- }
- async function withTab (tabId, fn) {
- const tabs = await listTabs()
- if (!tabs.length) throw new Error('浏览器里还没有打开的页面')
- const tab = tabId ? tabs.find((t) => t.id === tabId) : tabs[tabs.length - 1]
- if (!tab) throw new Error(`找不到页签 ${tabId}(可能已关闭)`)
- const cdp = await new CDP(tab.webSocketDebuggerUrl).connect()
- try { return await fn(cdp, tab) } finally { cdp.close() }
- }
- function assertUrl (url) {
- const u = String(url || '').trim()
- if (!u) throw new Error('缺少网址')
- if (!/^https?:\/\//i.test(u)) throw new Error(`只支持 http/https 网址,收到的是 ${u}`)
- return u
- }
- async function waitLoaded (cdp, timeout = 20_000) {
- await waitFor(async () => {
- const state = await cdp.evaluate('document.readyState')
- return state === 'complete' || state === 'interactive'
- }, { timeout, interval: 300, what: '页面加载超时' })
- // 单页应用首屏数据还要一会儿,给一点缓冲,不能等太久让模型以为失败
- await new Promise((r) => setTimeout(r, 600))
- }
- async function open (url, { reuse = true } = {}) {
- const target = assertUrl(url)
- const tabs = await listTabs().catch(() => [])
- // 只有一个空白页时复用它,避免越开越多
- const blank = reuse ? tabs.find((t) => t.url === 'about:blank') : null
- const tab = blank || await newTab(target)
- return withTab(tab.id, async (cdp) => {
- if (blank) await cdp.send('Page.navigate', { url: target })
- await waitLoaded(cdp)
- return { tabId: tab.id, url: await cdp.evaluate('location.href'), title: await cdp.evaluate('document.title') }
- })
- }
- async function goto (url, tabId) {
- const target = assertUrl(url)
- return withTab(tabId, async (cdp) => {
- await cdp.send('Page.navigate', { url: target })
- await waitLoaded(cdp)
- return { url: await cdp.evaluate('location.href'), title: await cdp.evaluate('document.title') }
- })
- }
- async function pageText (tabId, { selector = 'body', limit = MAX_TEXT } = {}) {
- return withTab(tabId, async (cdp) => {
- const text = await cdp.evaluate(`(() => {
- const el = document.querySelector(${JSON.stringify(selector)});
- return el ? (el.innerText || el.textContent || '') : '';
- })()`)
- const clean = String(text || '').replace(/\n{3,}/g, '\n\n').trim()
- return {
- url: await cdp.evaluate('location.href'),
- title: await cdp.evaluate('document.title'),
- chars: clean.length,
- text: clean.slice(0, limit),
- truncated: clean.length > limit
- }
- })
- }
- async function click (tabId, { selector, text, index = 0 }) {
- return withTab(tabId, async (cdp) => {
- const result = await cdp.evaluate(`(() => {
- const idx = ${Number(index) || 0};
- let els = [];
- if (${JSON.stringify(selector || '')}) {
- els = [...document.querySelectorAll(${JSON.stringify(selector || '')})];
- } else {
- const needle = ${JSON.stringify(String(text || ''))};
- if (!needle) return { ok: false, error: 'no-target' };
- const all = [...document.querySelectorAll('a,button,[role=button],input[type=submit],li,span,div')];
- els = all.filter((el) => (el.innerText || el.value || '').trim().includes(needle) ||
- (el.getAttribute('aria-label') || '').includes(needle));
- // 命中多层时取最内层,避免点到外层容器
- els = els.filter((el) => !els.some((o) => o !== el && el.contains(o)));
- }
- const el = els[idx];
- if (!el) return { ok: false, error: 'not-found', found: els.length };
- el.scrollIntoView({ block: 'center' });
- el.click();
- return { ok: true, tag: el.tagName, label: (el.innerText || el.value || '').trim().slice(0, 60), found: els.length };
- })()`)
- if (!result || !result.ok) {
- throw new Error(result?.error === 'not-found'
- ? `页面上没找到「${text || selector}」,可以把页面文字取出来先确认按钮叫什么`
- : '点击失败,没有定位到元素')
- }
- await new Promise((r) => setTimeout(r, 800))
- return { ...result, url: await cdp.evaluate('location.href') }
- })
- }
- async function type (tabId, { selector, text, submit = false }) {
- return withTab(tabId, async (cdp) => {
- const value = String(text ?? '')
- const mode = await cdp.evaluate(`(() => {
- const el = document.querySelector(${JSON.stringify(selector)});
- if (!el) return 'missing';
- el.focus();
- const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
- const setter = Object.getOwnPropertyDescriptor(proto, 'value').set;
- setter.call(el, ${JSON.stringify(value)});
- el.dispatchEvent(new Event('input', { bubbles: true }));
- el.dispatchEvent(new Event('change', { bubbles: true }));
- if (!${submit ? 'true' : 'false'}) return 'ok';
- // 搜索框大多在 form 里:直接提交表单最可靠,回车事件经常被前端拦住
- const form = el.form;
- if (form && typeof form.requestSubmit === 'function') { form.requestSubmit(); return 'form'; }
- if (form && typeof form.submit === 'function') { form.submit(); return 'form'; }
- return 'key';
- })()`)
- if (mode === 'missing') throw new Error(`页面上没有 ${selector},先取一次页面文字确认输入框怎么定位`)
- if (submit && mode === 'key') {
- for (const type of ['keyDown', 'keyUp']) {
- await cdp.send('Input.dispatchKeyEvent', { type, key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 })
- }
- }
- if (submit) {
- // 提交后是跳转,等加载完成;超时不算失败(单页应用可能就地渲染)
- await waitLoaded(cdp).catch(() => {})
- }
- return { ok: true, selector, submitted: !!submit, url: await cdp.evaluate('location.href') }
- })
- }
- async function screenshot (tabId, file) {
- return withTab(tabId, async (cdp) => {
- const { data } = await cdp.send('Page.captureScreenshot', { format: 'png' })
- const target = path.resolve(file)
- fs.mkdirSync(path.dirname(target), { recursive: true })
- fs.writeFileSync(target, Buffer.from(data, 'base64'))
- return { file: target, bytes: fs.statSync(target).size }
- })
- }
- async function evaluate (tabId, expression) {
- return withTab(tabId, (cdp) => cdp.evaluate(String(expression || '')))
- }
- async function closeTab (tabId) {
- const p = await ensureRunning()
- await httpJson(`http://127.0.0.1:${p}/json/close/${encodeURIComponent(tabId)}`)
- return { closed: tabId }
- }
- async function quit () {
- const p = await ensureRunning().catch(() => 0)
- if (!p) return { quit: true }
- try { await httpJson(`http://127.0.0.1:${p}/json/close/` + (await listTabs())[0]?.id) } catch { /* ignore */ }
- try { proc?.kill() } catch { /* ignore */ }
- proc = null
- port = 0
- return { quit: true }
- }
- return { open, goto, pageText, click, type, screenshot, evaluate, closeTab, quit, listTabs }
- }
|