@capyclaw/browser-workbench 0.0.0-stage → 0.1.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.
Files changed (52) hide show
  1. package/README.md +66 -2
  2. package/contract/browser-contract.json +890 -0
  3. package/cordis.patch.yml +25 -0
  4. package/demo/form.html +85 -0
  5. package/lib/host.mjs +68 -0
  6. package/package.json +61 -4
  7. package/server/constants.mjs +16 -0
  8. package/server/contract-snapshots.mjs +81 -0
  9. package/server/contract.mjs +24 -0
  10. package/server/engine.mjs +675 -0
  11. package/server/http-utils.mjs +2 -0
  12. package/server/infra/http.mjs +113 -0
  13. package/server/infra/tuning.mjs +82 -0
  14. package/server/mcp/handler.mjs +2 -0
  15. package/server/mcp/instructions.mjs +28 -0
  16. package/server/relay.mjs +226 -0
  17. package/server/routes/api.mjs +120 -0
  18. package/server/routes/assets.mjs +2 -0
  19. package/server/routes/mcp.mjs +17 -0
  20. package/server/routes/workbench.mjs +33 -0
  21. package/server/shared/SHARED_MANIFEST.json +47 -0
  22. package/server/shared/asset-service.mjs +217 -0
  23. package/server/shared/editor-host.mjs +125 -0
  24. package/server/shared/kit/editor/lease.mjs +139 -0
  25. package/server/shared/kit/service/api.mjs +45 -0
  26. package/server/shared/kit/service/http.mjs +113 -0
  27. package/server/shared/kit/service/mcp-http.mjs +142 -0
  28. package/server/shared/kit/tools/validate.mjs +115 -0
  29. package/server/shared/kit/tuning.mjs +82 -0
  30. package/server/shared/kit/util/fs-lock.mjs +132 -0
  31. package/server/shared/service-host.mjs +511 -0
  32. package/server/shared/state-service.mjs +249 -0
  33. package/server/shared/tool-host.mjs +341 -0
  34. package/server/shared/tuning.mjs +63 -0
  35. package/server/tools/capabilities/contract.mjs +35 -0
  36. package/server/tools/capabilities/evaluate.mjs +36 -0
  37. package/server/tools/capabilities/index.mjs +26 -0
  38. package/server/tools/capabilities/interaction.mjs +111 -0
  39. package/server/tools/capabilities/navigation.mjs +32 -0
  40. package/server/tools/capabilities/screenshot.mjs +33 -0
  41. package/server/tools/capabilities/session.mjs +75 -0
  42. package/server/tools/capabilities/snapshot.mjs +30 -0
  43. package/server/tools/capabilities/tabs.mjs +35 -0
  44. package/server/tools/index.mjs +12 -0
  45. package/server/tools/kernel/define.mjs +5 -0
  46. package/server/tools/kernel/output.mjs +22 -0
  47. package/server/tools/kernel/ports.mjs +54 -0
  48. package/server/tools/kernel/registry.mjs +17 -0
  49. package/server/tools.mjs +3 -0
  50. package/ui/app.js +157 -0
  51. package/ui/index.html +56 -0
  52. package/ui/style.css +76 -0
@@ -0,0 +1,675 @@
1
+ /**
2
+ * 浏览器引擎控制器:Playwright 持久化上下文 + ref 快照交互。
3
+ *
4
+ * 设计口径(借鉴 Playwright MCP / dsh-playwright-browser,能力自建):
5
+ * - 懒启动:第一次导航才拉起浏览器;探测链 playwright chromium 缓存
6
+ * → msedge → chrome,全失败给结构化错误与安装提示。
7
+ * - 有头默认(headless:false):看得见它在互联网上点击/打字;
8
+ * 登录态持久化(userDataDir 落 hostDir/profile,跨重启保留 cookie)。
9
+ * - snapshot + ref:快照是「可交互元素 + 结构节点」的缩进文本树,每个
10
+ * 元素带 ref=eN;动作引用 ref,不猜 CSS 选择器;ref 过期报
11
+ * STALE_SNAPSHOT,重新 browser_snapshot 即可。
12
+ * - 动作串行化:浏览器单线程语义,所有动作走互斥队列。
13
+ * - 安全默认:仅 http(s)、拒绝带凭据 URL、browser_evaluate 默认关闭
14
+ * (allowEvaluate 开启),页面内容视为不可信数据。
15
+ *
16
+ * 本模块只依赖 playwright 与 node 内置模块,可独立单测(纯函数)与注入测试。
17
+ */
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+
21
+ /* --------------------------------------------------------------------------
22
+ * 配置解析(纯函数,可单测)
23
+ * ------------------------------------------------------------------------ */
24
+
25
+ export const ENGINE_CONFIG_DEFAULTS = Object.freeze({
26
+ headless: false,
27
+ allowEvaluate: false,
28
+ channel: '',
29
+ executablePath: '',
30
+ navigationTimeoutMs: 30000,
31
+ actionTimeoutMs: 15000,
32
+ maxSnapshotChars: 40000,
33
+ viewportWidth: 1280,
34
+ viewportHeight: 800,
35
+ })
36
+
37
+ const ENV_FIELDS = [
38
+ ['DSH_BROWSER_HEADLESS', 'headless', 'boolean'],
39
+ ['DSH_BROWSER_ALLOW_EVALUATE', 'allowEvaluate', 'boolean'],
40
+ ['DSH_BROWSER_CHANNEL', 'channel', 'string'],
41
+ ['DSH_BROWSER_EXECUTABLE_PATH', 'executablePath', 'string'],
42
+ ['DSH_BROWSER_NAV_TIMEOUT_MS', 'navigationTimeoutMs', 'number'],
43
+ ['DSH_BROWSER_ACTION_TIMEOUT_MS', 'actionTimeoutMs', 'number'],
44
+ ['DSH_BROWSER_MAX_SNAPSHOT_CHARS', 'maxSnapshotChars', 'number'],
45
+ ['DSH_BROWSER_VIEWPORT_W', 'viewportWidth', 'number'],
46
+ ['DSH_BROWSER_VIEWPORT_H', 'viewportHeight', 'number'],
47
+ ]
48
+
49
+ /** 环境变量 + 显式覆盖 → 引擎配置(默认值兜底)。 */
50
+ export function resolveEngineConfig(env = process.env, overrides = {}) {
51
+ const cfg = { ...ENGINE_CONFIG_DEFAULTS }
52
+ for (const [key, field, type] of ENV_FIELDS) {
53
+ const raw = env[key]
54
+ if (raw === undefined || raw === '') continue
55
+ if (type === 'boolean') cfg[field] = /^(1|true|yes)$/i.test(String(raw))
56
+ else if (type === 'number') {
57
+ const num = Number(raw)
58
+ if (Number.isFinite(num) && num > 0) cfg[field] = Math.floor(num)
59
+ } else cfg[field] = String(raw)
60
+ }
61
+ for (const [field, value] of Object.entries(overrides || {})) {
62
+ if (value === undefined || value === null || value === '') continue
63
+ cfg[field] = value
64
+ }
65
+ return cfg
66
+ }
67
+
68
+ /* --------------------------------------------------------------------------
69
+ * URL 安全校验(纯函数,可单测)
70
+ * ------------------------------------------------------------------------ */
71
+
72
+ function urlError(code, message, hint) {
73
+ return Object.assign(new Error(message), { code, hint })
74
+ }
75
+
76
+ /** 仅 http(s)、拒绝内嵌凭据;其余协议一律拒绝(file:/javascript:/data: 等)。 */
77
+ export function assertSafeUrl(raw) {
78
+ let parsed
79
+ try {
80
+ parsed = new URL(String(raw))
81
+ } catch {
82
+ throw urlError('URL_INVALID', `不是合法 URL: ${String(raw).slice(0, 200)}`, '提供完整地址,如 https://example.com/path')
83
+ }
84
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
85
+ throw urlError('URL_SCHEME_DENIED',
86
+ `仅支持 http/https,收到 ${parsed.protocol}`,
87
+ '浏览器工具只访问网页;本地文件与其他协议被拒绝。')
88
+ }
89
+ if (parsed.username || parsed.password) {
90
+ throw urlError('URL_CREDENTIALS_DENIED',
91
+ 'URL 内嵌了用户名/密码,已拒绝',
92
+ '凭据不要放进 URL;先打开登录页,再用 browser_fill 填表登录。')
93
+ }
94
+ return parsed.href
95
+ }
96
+
97
+ /* --------------------------------------------------------------------------
98
+ * 页内快照脚本(在浏览器里执行;自包含,不引用外部标识符)
99
+ * ------------------------------------------------------------------------ */
100
+
101
+ /**
102
+ * 收集可交互元素 + 结构节点(标题/图片),返回扁平条目 + 缩进文本行。
103
+ * 只走主框架(iframe/shadow DOM 不入快照,README 如实标注)。
104
+ */
105
+ function pageSnapshotFunction() {
106
+ const INTERACTIVE = 'a, button, input, select, textarea, summary, [role], [contenteditable="true"], [onclick], [tabindex]'
107
+ const skipHidden = (el, style) => el.getClientRects().length === 0
108
+ || style.visibility === 'hidden' || style.display === 'none'
109
+ || el.getAttribute('aria-hidden') === 'true'
110
+
111
+ function implicitRole(el) {
112
+ const tag = el.tagName.toLowerCase()
113
+ if (tag === 'a') return 'link'
114
+ if (tag === 'button' || tag === 'summary') return 'button'
115
+ if (tag === 'select') return 'combobox'
116
+ if (tag === 'textarea' || el.isContentEditable) return 'textbox'
117
+ if (tag === 'input') {
118
+ const type = (el.getAttribute('type') || 'text').toLowerCase()
119
+ if (type === 'checkbox') return 'checkbox'
120
+ if (type === 'radio') return 'radio'
121
+ if (type === 'submit' || type === 'button' || type === 'reset') return 'button'
122
+ return 'textbox'
123
+ }
124
+ if (/^h[1-6]$/.test(tag)) return 'heading'
125
+ if (tag === 'img') return 'img'
126
+ if (tag === 'form') return 'form'
127
+ return 'generic'
128
+ }
129
+
130
+ function nameOf(el) {
131
+ const aria = el.getAttribute('aria-label') || el.getAttribute('title')
132
+ if (aria) return aria.trim()
133
+ if (el.id) {
134
+ const label = document.querySelector(`label[for="${CSS.escape(el.id)}"]`)
135
+ if (label && label.textContent.trim()) return label.textContent.trim().slice(0, 80)
136
+ }
137
+ const closest = el.closest('label')
138
+ if (closest && closest.textContent.trim()) return closest.textContent.trim().slice(0, 80)
139
+ const alt = el.getAttribute('alt')
140
+ if (alt) return alt.trim().slice(0, 80)
141
+ const placeholder = el.getAttribute('placeholder')
142
+ if (placeholder) return placeholder.trim().slice(0, 80)
143
+ const text = (el.innerText || el.textContent || '').trim()
144
+ if (text) return text.replace(/\s+/g, ' ').slice(0, 80)
145
+ if (el.tagName.toLowerCase() === 'select') {
146
+ const opt = el.selectedOptions && el.selectedOptions[0]
147
+ if (opt) return (opt.textContent || '').trim().slice(0, 80)
148
+ }
149
+ return ''
150
+ }
151
+
152
+ function valueOf(el, role) {
153
+ const tag = el.tagName.toLowerCase()
154
+ if (tag === 'input') {
155
+ const type = (el.getAttribute('type') || 'text').toLowerCase()
156
+ if (type === 'password') return '••••'
157
+ if (type === 'checkbox' || type === 'radio') return el.checked ? '[checked]' : ''
158
+ const value = el.value
159
+ return value ? `"${String(value).slice(0, 60)}"` : ''
160
+ }
161
+ if (tag === 'select') {
162
+ const opt = el.selectedOptions && el.selectedOptions[0]
163
+ return opt ? `"${(opt.textContent || opt.value || '').trim().slice(0, 60)}"` : ''
164
+ }
165
+ if (role === 'textbox' && !el.isContentEditable) {
166
+ const value = el.value
167
+ return value ? `"${String(value).slice(0, 60)}"` : ''
168
+ }
169
+ return ''
170
+ }
171
+
172
+ function cssPath(el) {
173
+ const unique = (sel) => { try { return document.querySelectorAll(sel).length === 1 } catch { return false } }
174
+ if (el.id) {
175
+ const byId = `#${CSS.escape(el.id)}`
176
+ if (unique(byId)) return byId
177
+ }
178
+ for (const attr of ['data-testid', 'data-test', 'data-qa']) {
179
+ const val = el.getAttribute(attr)
180
+ if (val) {
181
+ const byAttr = `[${attr}="${val.replace(/"/g, '\\"')}"]`
182
+ if (unique(byAttr)) return byAttr
183
+ }
184
+ }
185
+ const parts = []
186
+ let cur = el
187
+ let depth = 0
188
+ while (cur && cur !== document.body && cur !== document.documentElement && depth < 16) {
189
+ let part = cur.tagName.toLowerCase()
190
+ const parent = cur.parentElement
191
+ if (parent) {
192
+ let same = 0
193
+ let idx = 0
194
+ for (const child of parent.children) {
195
+ if (child.tagName === cur.tagName) {
196
+ same += 1
197
+ if (child === cur) idx = same
198
+ }
199
+ }
200
+ if (same > 1) part += `:nth-of-type(${idx})`
201
+ }
202
+ parts.unshift(part)
203
+ if (parts.length >= 2 && unique(parts.join(' > '))) break
204
+ cur = cur.parentElement
205
+ depth += 1
206
+ }
207
+ return parts.join(' > ')
208
+ }
209
+
210
+ const entries = []
211
+ const lines = []
212
+ let ref = 0
213
+ const nodes = document.querySelectorAll(`${INTERACTIVE}, h1, h2, h3, h4, h5, h6, img`)
214
+ const bodyDepth = (() => { let d = 0; let n = document.body; while (n && n.parentElement) { d += 1; n = n.parentElement } return d })()
215
+ for (const el of nodes) {
216
+ const style = window.getComputedStyle(el)
217
+ if (skipHidden(el, style)) continue
218
+ const tag = el.tagName.toLowerCase()
219
+ if (tag === 'input' && (el.getAttribute('type') || '').toLowerCase() === 'hidden') continue
220
+ if (tag === 'img' && !el.getAttribute('alt')) continue
221
+ const role = el.getAttribute('role') || implicitRole(el)
222
+ if (role === 'generic' || role === 'presentation' || role === 'none') continue
223
+ ref += 1
224
+ const name = nameOf(el)
225
+ const value = valueOf(el, role)
226
+ let node = el.parentElement
227
+ let depth = 0
228
+ while (node && node !== document.body) { depth += 1; node = node.parentElement }
229
+ const id = `e${ref}`
230
+ entries.push({ ref: id, role, name, css: cssPath(el), tag, depth: Math.max(depth - bodyDepth + 1, 1) })
231
+ const label = `${role}${name ? ` "${name}"` : ''}${value ? ` ${value}` : ''}`
232
+ lines.push(`${' '.repeat(Math.max(depth - bodyDepth + 1, 0))}- ${label} [ref=${id}]`)
233
+ }
234
+ return {
235
+ url: location.href,
236
+ title: document.title || '',
237
+ lines,
238
+ entries,
239
+ total: entries.length,
240
+ }
241
+ }
242
+
243
+ /* --------------------------------------------------------------------------
244
+ * 引擎本体
245
+ * ------------------------------------------------------------------------ */
246
+
247
+ function engineError(code, message, hint) {
248
+ return Object.assign(new Error(message), { code, hint: hint || '' })
249
+ }
250
+
251
+ const ACTION_LOG_LIMIT = 50
252
+
253
+ /**
254
+ * @param {object} options
255
+ * @param {string} options.hostDir 宿主数据目录(profile/ 与 screenshots/ 落这里)
256
+ * @param {object} [options.config] resolveEngineConfig 的产物(默认再解析一次环境变量)
257
+ * @param {object} [options.playwright] 注入的 playwright 模块(测试用;缺省动态 import)
258
+ */
259
+ export async function createBrowserEngine({ hostDir, config, playwright } = {}) {
260
+ if (!hostDir) throw new Error('createBrowserEngine: 缺少 hostDir')
261
+ const cfg = config || resolveEngineConfig()
262
+ const pw = playwright || await import('playwright')
263
+
264
+ const profileDir = path.join(hostDir, 'profile')
265
+ const screenshotsDir = path.join(hostDir, 'screenshots')
266
+ fs.mkdirSync(profileDir, { recursive: true })
267
+ fs.mkdirSync(screenshotsDir, { recursive: true })
268
+
269
+ /* ---- 运行态 ---- */
270
+ let context = null
271
+ let launching = null
272
+ let channelUsed = ''
273
+ let activeTabId = null
274
+ let tabCounter = 0
275
+ const tabs = new Map() // id → page
276
+ const tabIds = new Map() // page → id
277
+ const refRegistries = new Map() // tabId → Map(ref → entry)
278
+ const snapshotChars = new Map() // tabId → 最后一次快照字符数
279
+ const counters = { actions: 0, errors: 0, snapshots: 0 }
280
+ const actionLog = []
281
+
282
+ /* ---- 动作互斥(浏览器单线程语义) ---- */
283
+ let chain = Promise.resolve()
284
+ function enqueue(task) {
285
+ const run = chain.then(task, task)
286
+ chain = run.then(() => {}, () => {})
287
+ return run
288
+ }
289
+
290
+ function logAction(tool, detail, ms, ok, error) {
291
+ actionLog.unshift({ tool, detail, ms: Math.round(ms), ok, error: error ? String(error.message || error).slice(0, 160) : '', at: new Date().toISOString() })
292
+ if (actionLog.length > ACTION_LOG_LIMIT) actionLog.length = ACTION_LOG_LIMIT
293
+ }
294
+
295
+ async function track(tool, detail, task) {
296
+ const started = Date.now()
297
+ counters.actions += 1
298
+ try {
299
+ const out = await task()
300
+ logAction(tool, detail, Date.now() - started, true)
301
+ return out
302
+ } catch (error) {
303
+ counters.errors += 1
304
+ logAction(tool, detail, Date.now() - started, false, error)
305
+ throw error
306
+ }
307
+ }
308
+
309
+ /* ---- 懒启动与探测链 ---- */
310
+ function registerPage(page) {
311
+ if (tabIds.has(page)) return tabIds.get(page)
312
+ tabCounter += 1
313
+ const id = `T${tabCounter}`
314
+ tabs.set(id, page)
315
+ tabIds.set(page, id)
316
+ refRegistries.set(id, new Map())
317
+ page.on('close', () => {
318
+ tabs.delete(id)
319
+ tabIds.delete(page)
320
+ refRegistries.delete(id)
321
+ snapshotChars.delete(id)
322
+ if (activeTabId === id) {
323
+ const rest = [...tabs.keys()]
324
+ activeTabId = rest.length ? rest[rest.length - 1] : null
325
+ }
326
+ })
327
+ return id
328
+ }
329
+
330
+ async function launch() {
331
+ if (context) return context
332
+ if (launching) return launching
333
+ launching = (async () => {
334
+ const attempts = []
335
+ const candidates = []
336
+ if (cfg.executablePath) candidates.push({ label: `executablePath(${cfg.executablePath})`, options: { executablePath: cfg.executablePath } })
337
+ if (cfg.channel) candidates.push({ label: `channel:${cfg.channel}`, options: { channel: cfg.channel } })
338
+ candidates.push({ label: 'chromium', options: {} })
339
+ if (process.platform === 'win32') {
340
+ candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
341
+ candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
342
+ } else {
343
+ candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
344
+ candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
345
+ }
346
+ const seen = new Set()
347
+ for (const candidate of candidates) {
348
+ const key = candidate.label
349
+ if (seen.has(key)) continue
350
+ seen.add(key)
351
+ try {
352
+ const ctx = await pw.chromium.launchPersistentContext(profileDir, {
353
+ headless: cfg.headless,
354
+ viewport: { width: cfg.viewportWidth, height: cfg.viewportHeight },
355
+ ...candidate.options,
356
+ })
357
+ context = ctx
358
+ channelUsed = candidate.label
359
+ for (const page of ctx.pages()) registerPage(page)
360
+ ctx.on('page', (page) => { registerPage(page); activeTabId = tabIds.get(page) })
361
+ if (!activeTabId && tabs.size) activeTabId = [...tabs.keys()][0]
362
+ return ctx
363
+ } catch (error) {
364
+ attempts.push(`${candidate.label}: ${String(error && error.message || error).split('\n')[0].slice(0, 200)}`)
365
+ }
366
+ }
367
+ throw engineError('ENGINE_LAUNCH_FAILED',
368
+ `浏览器启动失败(已尝试 ${attempts.length} 种方式)`,
369
+ `安装 Playwright Chromium(npx playwright install chromium)或系统 Chrome/Edge 后重试。尝试明细:${attempts.join(';')}`)
370
+ })()
371
+ try {
372
+ return await launching
373
+ } finally {
374
+ launching = null
375
+ }
376
+ }
377
+
378
+ async function ensureTab(tabId) {
379
+ await launch()
380
+ let id = tabId || activeTabId
381
+ if (id && !tabs.has(id)) {
382
+ throw engineError('TAB_UNKNOWN', `标签页 ${id} 不存在`, '用 browser_tabs(action=list) 查看现有标签页。')
383
+ }
384
+ if (!id) {
385
+ const page = await context.newPage()
386
+ id = registerPage(page)
387
+ activeTabId = id
388
+ }
389
+ if (!activeTabId) activeTabId = id
390
+ return { id, page: tabs.get(id) }
391
+ }
392
+
393
+ /* ---- 快照 ---- */
394
+ /**
395
+ * 动作后落定:Playwright 的 click/press 只等到导航「提交」,不等新文档 DOM 就绪,
396
+ * 立刻 evaluate 会拍到空页(真实站点上很常见)。这里补一次 domcontentloaded
397
+ * 等待 + 极短渲染让位,拿不到就按当前状态拍(不阻塞超时站点)。
398
+ */
399
+ async function settle(page) {
400
+ try {
401
+ await page.waitForLoadState('domcontentloaded', { timeout: 5000 })
402
+ } catch { /* 未发生导航 / 站点慢:继续拍当前状态 */ }
403
+ try {
404
+ await page.waitForTimeout(80)
405
+ } catch { /* 页面已关闭 */ }
406
+ }
407
+
408
+ async function takeSnapshot(page, tabId) {
409
+ const raw = await page.evaluate(pageSnapshotFunction)
410
+ counters.snapshots += 1
411
+ const registry = new Map()
412
+ for (const entry of raw.entries) registry.set(entry.ref, entry)
413
+ refRegistries.set(tabId, registry)
414
+ let text = raw.lines.join('\n')
415
+ let truncated = false
416
+ if (text.length > cfg.maxSnapshotChars) {
417
+ truncated = true
418
+ text = text.slice(0, cfg.maxSnapshotChars) + `\n…(已截断:完整快照 ${raw.lines.join('\n').length} 字符;已列出的 ref 仍可使用)`
419
+ }
420
+ snapshotChars.set(tabId, text.length)
421
+ return {
422
+ url: raw.url,
423
+ title: raw.title,
424
+ elements: raw.total,
425
+ truncated,
426
+ text,
427
+ }
428
+ }
429
+
430
+ /* ---- ref 解析 ---- */
431
+ function resolveRef(tabId, ref) {
432
+ const registry = refRegistries.get(tabId)
433
+ const entry = registry && registry.get(String(ref))
434
+ if (!entry) {
435
+ throw engineError('STALE_SNAPSHOT',
436
+ `ref=${ref} 不在当前标签页最近的快照里`,
437
+ '页面可能已变化或引用了别的标签页;先 browser_snapshot 重新观察,再用新 ref。')
438
+ }
439
+ return entry
440
+ }
441
+
442
+ async function locatorFor(page, tabId, ref) {
443
+ const entry = resolveRef(tabId, ref)
444
+ const locator = page.locator(entry.css)
445
+ const count = await locator.count()
446
+ if (count !== 1) {
447
+ throw engineError('STALE_SNAPSHOT',
448
+ `ref=${ref}(${entry.role}${entry.name ? ` "${entry.name}"` : ''})定位到 ${count} 个元素`,
449
+ '快照已过期;重新 browser_snapshot 后用新 ref。')
450
+ }
451
+ return { locator, entry }
452
+ }
453
+
454
+ /* ---- 公开 API ---- */
455
+ const engine = {
456
+ config: cfg,
457
+ profileDir,
458
+ screenshotsDir,
459
+
460
+ /** 结构化状态(health/metrics/工具共用;不触发浏览器启动)。 */
461
+ status() {
462
+ const tabList = [...tabs.entries()].map(([id, page]) => {
463
+ let url = ''
464
+ try { url = page.url() || '' } catch { /* 已关闭 */ }
465
+ return { id, url, active: id === activeTabId }
466
+ })
467
+ return {
468
+ running: !!context,
469
+ launching: !!launching,
470
+ headless: cfg.headless,
471
+ channel: channelUsed,
472
+ tabs: tabList,
473
+ activeTab: activeTabId,
474
+ counters: { ...counters },
475
+ evaluateEnabled: !!cfg.allowEvaluate,
476
+ }
477
+ },
478
+
479
+ actionLog() {
480
+ return actionLog.slice()
481
+ },
482
+
483
+ async navigate({ url, tab } = {}) {
484
+ const safe = assertSafeUrl(url)
485
+ return enqueue(() => track('browser_navigate', safe.slice(0, 120), async () => {
486
+ const { id, page } = await ensureTab(tab)
487
+ activeTabId = id
488
+ await page.goto(safe, { timeout: cfg.navigationTimeoutMs, waitUntil: 'domcontentloaded' })
489
+ const snapshot = await takeSnapshot(page, id)
490
+ return { tab: id, url: page.url(), title: snapshot.title, snapshot }
491
+ }))
492
+ },
493
+
494
+ async snapshot({ tab } = {}) {
495
+ return enqueue(() => track('browser_snapshot', tab ? `tab=${tab}` : 'active', async () => {
496
+ const { id, page } = await ensureTab(tab)
497
+ const snapshot = await takeSnapshot(page, id)
498
+ return { tab: id, ...snapshot }
499
+ }))
500
+ },
501
+
502
+ async click({ ref, tab } = {}) {
503
+ return enqueue(() => track('browser_click', `ref=${ref}`, async () => {
504
+ const { id, page } = await ensureTab(tab)
505
+ const { locator, entry } = await locatorFor(page, id, ref)
506
+ await locator.click({ timeout: cfg.actionTimeoutMs })
507
+ await settle(page)
508
+ const snapshot = await takeSnapshot(page, id)
509
+ return { clicked: `${entry.role}${entry.name ? ` "${entry.name}"` : ''}`, tab: id, snapshot }
510
+ }))
511
+ },
512
+
513
+ async fill({ ref, text, submit = false, tab } = {}) {
514
+ return enqueue(() => track('browser_fill', `ref=${ref}`, async () => {
515
+ const { id, page } = await ensureTab(tab)
516
+ const { locator, entry } = await locatorFor(page, id, ref)
517
+ await locator.fill(String(text ?? ''), { timeout: cfg.actionTimeoutMs })
518
+ if (submit) {
519
+ await locator.press('Enter', { timeout: cfg.actionTimeoutMs })
520
+ await settle(page)
521
+ }
522
+ const snapshot = await takeSnapshot(page, id)
523
+ return { filled: `${entry.role}${entry.name ? ` "${entry.name}"` : ''}`, submit: !!submit, tab: id, snapshot }
524
+ }))
525
+ },
526
+
527
+ async press({ key, ref, tab } = {}) {
528
+ return enqueue(() => track('browser_press', `${ref ? `ref=${ref} ` : ''}${key}`, async () => {
529
+ const { id, page } = await ensureTab(tab)
530
+ if (ref) {
531
+ const { locator } = await locatorFor(page, id, ref)
532
+ await locator.press(String(key), { timeout: cfg.actionTimeoutMs })
533
+ } else {
534
+ await page.keyboard.press(String(key))
535
+ }
536
+ await settle(page)
537
+ const snapshot = await takeSnapshot(page, id)
538
+ return { key, tab: id, snapshot }
539
+ }))
540
+ },
541
+
542
+ async select({ ref, value, tab } = {}) {
543
+ return enqueue(() => track('browser_select', `ref=${ref}`, async () => {
544
+ const { id, page } = await ensureTab(tab)
545
+ const { locator, entry } = await locatorFor(page, id, ref)
546
+ let applied = ''
547
+ try {
548
+ await locator.selectOption({ value: String(value) }, { timeout: cfg.actionTimeoutMs })
549
+ applied = String(value)
550
+ } catch {
551
+ /* 值匹配失败 → 按 label 再试一次(真实页面两种写法都常见)。 */
552
+ await locator.selectOption({ label: String(value) }, { timeout: cfg.actionTimeoutMs })
553
+ applied = String(value)
554
+ }
555
+ await settle(page)
556
+ const snapshot = await takeSnapshot(page, id)
557
+ return { selected: `${entry.name || entry.role} → ${applied}`, tab: id, snapshot }
558
+ }))
559
+ },
560
+
561
+ async scroll({ direction = 'down', amount = 600, tab } = {}) {
562
+ return enqueue(() => track('browser_scroll', `${direction} ${amount}px`, async () => {
563
+ const { id, page } = await ensureTab(tab)
564
+ const delta = direction === 'up' ? -Number(amount) : Number(amount)
565
+ await page.evaluate((dy) => window.scrollBy(0, dy), delta)
566
+ const snapshot = await takeSnapshot(page, id)
567
+ return { scrolled: `${direction} ${Math.abs(delta)}px`, tab: id, snapshot }
568
+ }))
569
+ },
570
+
571
+ async wait({ ms, selector, tab } = {}) {
572
+ return enqueue(() => track('browser_wait', ms ? `${ms}ms` : selector ? selector.slice(0, 80) : 'load', async () => {
573
+ const { id, page } = await ensureTab(tab)
574
+ if (selector) {
575
+ await page.waitForSelector(String(selector), { timeout: Math.min(Number(ms) || cfg.actionTimeoutMs, cfg.actionTimeoutMs) })
576
+ } else if (ms) {
577
+ await page.waitForTimeout(Math.min(Number(ms), 30000))
578
+ } else {
579
+ await page.waitForLoadState('load', { timeout: cfg.navigationTimeoutMs })
580
+ }
581
+ return { waited: true, tab: id }
582
+ }))
583
+ },
584
+
585
+ async history({ action = 'back', tab } = {}) {
586
+ return enqueue(() => track('browser_history', action, async () => {
587
+ const { id, page } = await ensureTab(tab)
588
+ if (action === 'back') await page.goBack({ timeout: cfg.navigationTimeoutMs })
589
+ else if (action === 'forward') await page.goForward({ timeout: cfg.navigationTimeoutMs })
590
+ else if (action === 'reload') await page.reload({ timeout: cfg.navigationTimeoutMs })
591
+ else throw engineError('ARG_INVALID', `history 不支持 ${action}`, '可用:back / forward / reload')
592
+ const snapshot = await takeSnapshot(page, id)
593
+ return { action, url: page.url(), tab: id, snapshot }
594
+ }))
595
+ },
596
+
597
+ async tabsAction({ action = 'list', url, tab } = {}) {
598
+ return enqueue(() => track('browser_tabs', action, async () => {
599
+ if (action === 'list') {
600
+ return { tabs: engine.status().tabs, activeTab: activeTabId }
601
+ }
602
+ if (action === 'new') {
603
+ await launch()
604
+ const page = await context.newPage()
605
+ const id = registerPage(page)
606
+ activeTabId = id
607
+ if (url) {
608
+ const safe = assertSafeUrl(url)
609
+ await page.goto(safe, { timeout: cfg.navigationTimeoutMs, waitUntil: 'domcontentloaded' })
610
+ }
611
+ const snapshot = await takeSnapshot(page, id)
612
+ return { tab: id, url: page.url(), snapshot }
613
+ }
614
+ if (action === 'select') {
615
+ if (!tab || !tabs.has(tab)) throw engineError('TAB_UNKNOWN', `标签页 ${tab || '(空)'} 不存在`, '先 browser_tabs(action=list)。')
616
+ activeTabId = tab
617
+ const snapshot = await takeSnapshot(tabs.get(tab), tab)
618
+ return { tab, snapshot }
619
+ }
620
+ if (action === 'close') {
621
+ if (!tab || !tabs.has(tab)) throw engineError('TAB_UNKNOWN', `标签页 ${tab || '(空)'} 不存在`, '先 browser_tabs(action=list)。')
622
+ await tabs.get(tab).close()
623
+ return { closed: tab, tabs: engine.status().tabs }
624
+ }
625
+ throw engineError('ARG_INVALID', `tabs 不支持 ${action}`, '可用:list / new / select / close')
626
+ }))
627
+ },
628
+
629
+ /** 截图落盘(工具面:返回绝对路径)。 */
630
+ async screenshot({ fullPage = false, tab } = {}) {
631
+ return enqueue(() => track('browser_screenshot', fullPage ? 'fullPage' : 'viewport', async () => {
632
+ const { page } = await ensureTab(tab)
633
+ const buffer = await page.screenshot({ fullPage: !!fullPage })
634
+ const file = path.join(screenshotsDir, `shot-${Date.now()}-${Math.floor(Math.random() * 1e4)}.png`)
635
+ fs.writeFileSync(file, buffer)
636
+ return { path: file, bytes: buffer.length, tab: activeTabId }
637
+ }))
638
+ },
639
+
640
+ /** 实时画面(工作台 /api/screenshot 用:不落盘,直接返回 PNG Buffer)。 */
641
+ async screenshotBuffer({ tab } = {}) {
642
+ const { page } = await ensureTab(tab)
643
+ return page.screenshot({ fullPage: false })
644
+ },
645
+
646
+ /** 任意 JS 执行:默认关闭,如实返回 NOT_IMPLEMENTED(不伪造结果)。 */
647
+ async evaluate({ script, tab } = {}) {
648
+ if (!cfg.allowEvaluate) {
649
+ throw engineError('NOT_IMPLEMENTED',
650
+ 'browser_evaluate 默认关闭(安全默认:页面脚本面不向模型开放)',
651
+ '确有需要时在 cordis 配置 allowEvaluate: true 或环境变量 DSH_BROWSER_ALLOW_EVALUATE=true,重启服务后生效。')
652
+ }
653
+ return enqueue(() => track('browser_evaluate', String(script).slice(0, 80), async () => {
654
+ const { id, page } = await ensureTab(tab)
655
+ const out = await page.evaluate(String(script))
656
+ return { tab: id, result: out === undefined ? null : out }
657
+ }))
658
+ },
659
+
660
+ async close() {
661
+ return enqueue(() => track('browser_close', '', async () => {
662
+ if (!context) return { closed: false }
663
+ const ctx = context
664
+ context = null
665
+ activeTabId = null
666
+ try {
667
+ await ctx.close()
668
+ } catch { /* 浏览器已退出时忽略 */ }
669
+ return { closed: true }
670
+ }))
671
+ },
672
+ }
673
+
674
+ return engine
675
+ }
@@ -0,0 +1,2 @@
1
+ /** 兼容入口:HTTP 传输实现统一来自 @capyclaw/plugin-kit 的构建快照。 */
2
+ export * from './infra/http.mjs'