@capyclaw/browser-workbench 0.1.21 → 0.1.23
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/contract/browser-contract.json +1 -1
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/asset-service/package.json +1 -1
- package/node_modules/@capyclaw/document-workbench/package.json +1 -1
- package/node_modules/@capyclaw/foundation/package.json +1 -1
- package/node_modules/@capyclaw/plugin-kit/package.json +2 -1
- package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/service-host/package.json +2 -2
- package/node_modules/@capyclaw/service-host/src/index.mjs +32 -5
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +1 -1
- package/node_modules/@capyclaw/tool-host/package.json +1 -1
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +21 -1
- package/package.json +7 -7
- package/server/contract.mjs +1 -1
- package/server/engine.mjs +153 -118
- package/server/ensure-browser.mjs +100 -0
- package/server/shared/SHARED_MANIFEST.json +4 -4
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/plugin-kit",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.11",
|
|
4
4
|
"description": "DSH 插件基础设施标准件:HTTP/MCP、单实例锁、参数校验、技能 provider、journal 存储、编辑器传输与租约。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"./tuning": "./src/tuning.mjs",
|
|
33
33
|
"./util/fs-lock": "./src/util/fs-lock.mjs",
|
|
34
34
|
"./util/http": "./src/util/http.mjs",
|
|
35
|
+
"./ledger": "./src/ledger.mjs",
|
|
35
36
|
"./editor/heartbeat-worker": "./src/editor/heartbeat-worker.js"
|
|
36
37
|
},
|
|
37
38
|
"bin": {
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/plugin-kit/ledger —— capyclaw 全插件统一操作/状态台账(append-only JSONL)。
|
|
3
|
+
*
|
|
4
|
+
* 设计目标(2026-11-25 用户要求「统一管理、是否工作/工作状态如何都记录」):
|
|
5
|
+
* - 单一存储:每个 profile 一份 `plugin-data/capyclaw/plugin-log.jsonl`,所有底盘
|
|
6
|
+
* (wizard 管理操作、suite-kit 挂载状态、service-host 服务生命周期/运行时错误)
|
|
7
|
+
* 往同一份台账追加,读取面统一查询,不按插件各写各的。
|
|
8
|
+
* - 只记事件不记噪音:管理操作结果、挂载/退让/降级/失败/释放、listen/dispatch 错误。
|
|
9
|
+
* - 永不反噬宿主:所有写盘 try/catch 吞错(台账坏了不能影响插件激活)。
|
|
10
|
+
* - 环形上限:超过 maxBytes(默认 2MB)轮转为 `.1`(保留一代历史),不无限增长。
|
|
11
|
+
* - 去重聚合在读取侧:fingerprint = hash(name + code + 归一化栈顶/消息前三行),
|
|
12
|
+
* 同指纹累加 count/firstAt/lastAt,复发一眼可见;原始行保留审计轨迹。
|
|
13
|
+
* - 纯本地:不上传、不记会话内容;导出由用户手动脱敏。
|
|
14
|
+
*
|
|
15
|
+
* 依赖方向:仅 node 内置模块(fs/path/crypto),任何底盘都可安全 import。
|
|
16
|
+
*/
|
|
17
|
+
import fs from 'node:fs'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import crypto from 'node:crypto'
|
|
20
|
+
|
|
21
|
+
/** 台账文件名(profile 的 plugin-data/capyclaw/ 下)。 */
|
|
22
|
+
export const LEDGER_FILENAME = 'plugin-log.jsonl'
|
|
23
|
+
|
|
24
|
+
/** profile 目录 → 台账绝对路径;profileDir 缺席返回 null(调用方降级为不记录)。 */
|
|
25
|
+
export function ledgerFileFor(profileDir) {
|
|
26
|
+
return profileDir ? path.join(profileDir, 'plugin-data', 'capyclaw', LEDGER_FILENAME) : null
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 复发指纹:name + code + 归一化消息/栈顶前三行(数字/地址抹平),
|
|
31
|
+
* 同一缺陷的不同实例(端口号、时间戳、pid 不同)归到同一指纹。
|
|
32
|
+
*/
|
|
33
|
+
export function fingerprintOf({ name, code, message, stackTop } = {}) {
|
|
34
|
+
const head = String(stackTop || message || '')
|
|
35
|
+
.split('\n').slice(0, 3).join('|')
|
|
36
|
+
.replace(/0x[0-9a-f]+/gi, '')
|
|
37
|
+
.replace(/\d+/g, '#')
|
|
38
|
+
const basis = `${name || ''}::${code || ''}::${head}`
|
|
39
|
+
return crypto.createHash('sha1').update(basis).digest('hex').slice(0, 12)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const clip = (v, n) => (typeof v === 'string' && v.length > n ? `${v.slice(0, n)}\n…(truncated)` : v)
|
|
43
|
+
|
|
44
|
+
/** 归一化一条台账记录:补 at/pid/fingerprint,截断超长 message/stackTop。 */
|
|
45
|
+
export function normalizeEntry(entry = {}) {
|
|
46
|
+
const e = {
|
|
47
|
+
at: typeof entry.at === 'number' ? entry.at : Date.now(),
|
|
48
|
+
pid: process.pid,
|
|
49
|
+
source: entry.source || 'unknown',
|
|
50
|
+
name: entry.name || null,
|
|
51
|
+
suite: entry.suite || null,
|
|
52
|
+
version: entry.version || null,
|
|
53
|
+
specKind: entry.specKind || null,
|
|
54
|
+
phase: entry.phase || 'runtime',
|
|
55
|
+
action: entry.action || null,
|
|
56
|
+
ok: entry.ok !== false,
|
|
57
|
+
degraded: entry.degraded === true,
|
|
58
|
+
code: entry.code || null,
|
|
59
|
+
message: clip(entry.message || null, 2000),
|
|
60
|
+
stackTop: clip(entry.stackTop || null, 1200),
|
|
61
|
+
mountPath: entry.mountPath || null,
|
|
62
|
+
url: entry.url || null,
|
|
63
|
+
jobId: entry.jobId || null,
|
|
64
|
+
}
|
|
65
|
+
e.fingerprint = entry.fingerprint || fingerprintOf(e)
|
|
66
|
+
return e
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 追加一条记录(best-effort,绝不抛错)。超 maxBytes 先轮转 `.1`。
|
|
71
|
+
* @returns {object|null} 归一化后的记录;file 缺席或写失败返回 null。
|
|
72
|
+
*/
|
|
73
|
+
export function appendLedger(entry, { file, maxBytes = 2 * 1024 * 1024 } = {}) {
|
|
74
|
+
if (!file) return null
|
|
75
|
+
try {
|
|
76
|
+
const e = normalizeEntry(entry)
|
|
77
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
78
|
+
try {
|
|
79
|
+
const st = fs.statSync(file)
|
|
80
|
+
if (st.size > maxBytes) { try { fs.renameSync(file, `${file}.1`) } catch { /* 轮转失败继续追加 */ } }
|
|
81
|
+
} catch { /* 新文件 */ }
|
|
82
|
+
fs.appendFileSync(file, `${JSON.stringify(e)}\n`)
|
|
83
|
+
return e
|
|
84
|
+
} catch {
|
|
85
|
+
return null
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 读取台账(坏行跳过)。filter:since(epoch ms)/name(匹配 name 或 suite)/source/
|
|
91
|
+
* errorsOnly(ok===false)/degradedOnly;limit 上限 2000,返回时间序尾部。
|
|
92
|
+
*/
|
|
93
|
+
export function readLedger({ file, since = 0, name = null, source = null, errorsOnly = false, degradedOnly = false, limit = 200 } = {}) {
|
|
94
|
+
if (!file) return []
|
|
95
|
+
let raw = ''
|
|
96
|
+
try { raw = fs.readFileSync(file, 'utf8') } catch { return [] }
|
|
97
|
+
const out = []
|
|
98
|
+
for (const line of raw.split('\n')) {
|
|
99
|
+
if (!line.trim()) continue
|
|
100
|
+
try {
|
|
101
|
+
const e = JSON.parse(line)
|
|
102
|
+
if (e && typeof e === 'object') out.push(e)
|
|
103
|
+
} catch { /* 坏行跳过 */ }
|
|
104
|
+
}
|
|
105
|
+
let rows = out.filter((e) => (e.at || 0) >= since)
|
|
106
|
+
if (name) rows = rows.filter((e) => e.name === name || e.suite === name)
|
|
107
|
+
if (source) rows = rows.filter((e) => e.source === source)
|
|
108
|
+
if (errorsOnly) rows = rows.filter((e) => e.ok === false)
|
|
109
|
+
if (degradedOnly) rows = rows.filter((e) => e.degraded === true)
|
|
110
|
+
const n = Math.max(1, Math.min(Number(limit) || 200, 2000))
|
|
111
|
+
return rows.slice(-n)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** 按指纹聚合:复发计数 + 首末时间 + 最近一条样本(count 降序)。 */
|
|
115
|
+
export function aggregateLedger(entries = []) {
|
|
116
|
+
const groups = new Map()
|
|
117
|
+
for (const e of entries) {
|
|
118
|
+
const key = e.fingerprint || fingerprintOf(e)
|
|
119
|
+
const g = groups.get(key) || { fingerprint: key, name: e.name, code: e.code, count: 0, firstAt: e.at, lastAt: e.at, message: e.message, stackTop: e.stackTop }
|
|
120
|
+
g.count += 1
|
|
121
|
+
g.firstAt = Math.min(g.firstAt, e.at || g.firstAt)
|
|
122
|
+
if ((e.at || 0) >= g.lastAt) { g.lastAt = e.at || g.lastAt; g.message = e.message; g.stackTop = e.stackTop }
|
|
123
|
+
groups.set(key, g)
|
|
124
|
+
}
|
|
125
|
+
return [...groups.values()].sort((a, b) => b.count - a.count || b.lastAt - a.lastAt)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 健康摘要:窗口内(默认 24h)按 name 汇总 events/errors/degraded/lastAction,
|
|
130
|
+
* 外加 top 指纹(默认 5 条),供 capyclaw_health 一眼看出「谁没在工作/谁在复发」。
|
|
131
|
+
*/
|
|
132
|
+
export function summarizeLedger(entries = [], { windowMs = 24 * 3600 * 1000, top = 5, now = Date.now() } = {}) {
|
|
133
|
+
const rows = entries.filter((e) => (e.at || 0) >= now - windowMs)
|
|
134
|
+
const per = new Map()
|
|
135
|
+
for (const e of rows) {
|
|
136
|
+
const key = e.name || e.suite || e.source || '?'
|
|
137
|
+
const p = per.get(key) || { name: key, events: 0, errors: 0, degraded: 0, lastAt: 0, lastAction: null, lastOk: null }
|
|
138
|
+
p.events += 1
|
|
139
|
+
if (e.ok === false) p.errors += 1
|
|
140
|
+
if (e.degraded === true) p.degraded += 1
|
|
141
|
+
if ((e.at || 0) >= p.lastAt) { p.lastAt = e.at || p.lastAt; p.lastAction = e.action; p.lastOk = e.ok }
|
|
142
|
+
per.set(key, p)
|
|
143
|
+
}
|
|
144
|
+
return {
|
|
145
|
+
windowMs,
|
|
146
|
+
events: rows.length,
|
|
147
|
+
errors: rows.filter((e) => e.ok === false).length,
|
|
148
|
+
per: [...per.values()].sort((a, b) => b.errors - a.errors || b.lastAt - a.lastAt),
|
|
149
|
+
top: aggregateLedger(rows.filter((e) => e.ok === false)).slice(0, top),
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/service-host",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"description": "DSH 公共服务宿主插件:统一 HTTP 路由、健康检查、指标、单实例锁、端口复用与静态资源,向插件提供 ctx.serviceHost。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./lib/host.mjs",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"test": "node --test test/*.test.mjs"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@capyclaw/plugin-kit": "^0.2.
|
|
48
|
+
"@capyclaw/plugin-kit": "^0.2.9",
|
|
49
49
|
"@capyclaw/foundation": "^0.1.1"
|
|
50
50
|
},
|
|
51
51
|
"repository": {
|
|
@@ -20,6 +20,7 @@ import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/h
|
|
|
20
20
|
import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
|
|
21
21
|
import { isLoopbackOrigin as sharedIsLoopbackOrigin, mimeFor } from '@capyclaw/plugin-kit/util/http'
|
|
22
22
|
import { safeJoin, cleanStaticPrefix, staticPrefixHit, staticRelRaw, decodeStaticRel, staticFileHit, staticHitNameType, staticBaseHeaders } from '@capyclaw/plugin-kit/service/static'
|
|
23
|
+
import { appendLedger, ledgerFileFor } from '@capyclaw/plugin-kit/ledger'
|
|
23
24
|
import { tuning } from './tuning.mjs'
|
|
24
25
|
|
|
25
26
|
function slugOf(id) {
|
|
@@ -166,6 +167,11 @@ export function createServiceApp(options = {}) {
|
|
|
166
167
|
let closed = false
|
|
167
168
|
let workdir = ''
|
|
168
169
|
|
|
170
|
+
/* 统一台账(2026-11-25):服务生命周期/运行时错误追加到 profile 台账,best-effort
|
|
171
|
+
* 绝不反噬服务;listenOptions.ledgerFile 可覆盖(suite-kit 传自己解析的路径)。 */
|
|
172
|
+
const defaultLedgerFile = ledgerFileFor(process.env.DSH_PROFILE_DIR || null)
|
|
173
|
+
const record = (action, ok, extra = {}, file = defaultLedgerFile) => appendLedger({ source: 'service-host', name: id, version, phase: 'runtime', action, ok, ...extra }, { file })
|
|
174
|
+
|
|
169
175
|
const app = {
|
|
170
176
|
id,
|
|
171
177
|
title,
|
|
@@ -361,13 +367,25 @@ export function createServiceApp(options = {}) {
|
|
|
361
367
|
const webServer = listenOptions.webServer
|
|
362
368
|
if (webServer && typeof webServer.register === 'function') {
|
|
363
369
|
const prefix = basePath || `/plugins/${id}`
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
370
|
+
try {
|
|
371
|
+
embeddedDispose = webServer.register({
|
|
372
|
+
kind: 'prefix',
|
|
373
|
+
path: prefix,
|
|
374
|
+
handler: (req, res) => Promise.resolve(app.dispatch(req, res, prefix)).catch((error) => {
|
|
375
|
+
record('dispatch-error', false, { code: 'dispatch-error', message: String((error && error.message) || error), stackTop: (error && error.stack) || null, url: req.url }, listenOptions.ledgerFile)
|
|
376
|
+
try {
|
|
377
|
+
if (!res.headersSent) send(req, res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
378
|
+
else res.destroy()
|
|
379
|
+
} catch { /* 连接已断开 */ }
|
|
380
|
+
}),
|
|
381
|
+
})
|
|
382
|
+
} catch (error) {
|
|
383
|
+
record('listen-error', false, { code: 'register-conflict', message: String((error && error.message) || error), stackTop: (error && error.stack) || null, mountPath: prefix }, listenOptions.ledgerFile)
|
|
384
|
+
throw error
|
|
385
|
+
}
|
|
369
386
|
listeningPort = Number(webServer.port) || 0
|
|
370
387
|
url = `http://127.0.0.1:${listeningPort}${prefix}`
|
|
388
|
+
record('listen', true, { mode: 'embedded', url, mountPath: prefix }, listenOptions.ledgerFile)
|
|
371
389
|
return { url, port: listeningPort, reused: false, mode: 'embedded', stop: app.close }
|
|
372
390
|
}
|
|
373
391
|
|
|
@@ -390,10 +408,12 @@ export function createServiceApp(options = {}) {
|
|
|
390
408
|
if (existing && sameContract && sameVersion && sameWorkdir) {
|
|
391
409
|
listeningPort = port
|
|
392
410
|
url = `http://127.0.0.1:${port}${publicBasePath}`
|
|
411
|
+
record('listen', true, { mode: 'standalone', reused: true, url, port }, listenOptions.ledgerFile)
|
|
393
412
|
return { url, port, reused: true, mode: 'standalone', stop: async () => {} }
|
|
394
413
|
}
|
|
395
414
|
if (existing && !(sameContract && sameVersion && sameWorkdir)) {
|
|
396
415
|
const old = `pid ${existing.pid || '?'},version ${existing.version || '?'},contract ${existing.contractVersion || '?'},workdir ${existing.workdir || '?'}`
|
|
416
|
+
record('listen-error', false, { code: 'identity-conflict', message: `端口 ${port} 被不同身份实例占用(${old})`, mountPath: publicBasePath }, listenOptions.ledgerFile)
|
|
397
417
|
throw new Error(
|
|
398
418
|
`${id} 端口 ${port} 被不同身份的实例占用(${old};当前 ${version} / ${contractVersion} / ${workdir})。` +
|
|
399
419
|
`为避免“新套件 + 旧进程”或“同版本 + 错数据目录”的假启动,已拒绝复用:请结束 ${existing.pid || '该'} 进程或重启 DSH 后再启动。`,
|
|
@@ -403,6 +423,7 @@ export function createServiceApp(options = {}) {
|
|
|
403
423
|
|
|
404
424
|
const lock = await acquireLock(lockFile, { healthPath, id })
|
|
405
425
|
if (!lock) {
|
|
426
|
+
record('listen-error', false, { code: 'lock-held', message: `已有另一个实例在运行: ${lockFile}` }, listenOptions.ledgerFile)
|
|
406
427
|
throw new Error(`${id} 已有另一个实例在运行;如确认没有,请删除锁文件: ${lockFile}`)
|
|
407
428
|
}
|
|
408
429
|
|
|
@@ -421,12 +442,14 @@ export function createServiceApp(options = {}) {
|
|
|
421
442
|
lastError = error
|
|
422
443
|
if (port === 0 || strictPort || attempt === scanLimit) {
|
|
423
444
|
releaseLock(lock)
|
|
445
|
+
record('listen-error', false, { code: 'port-unavailable', message: `端口 ${tryPort} 不可用: ${(error && error.message) || error}` }, listenOptions.ledgerFile)
|
|
424
446
|
throw new Error(`端口 ${tryPort} 不可用${strictPort ? '(strictPort)' : ''}: ${(error && error.message) || error}`)
|
|
425
447
|
}
|
|
426
448
|
}
|
|
427
449
|
}
|
|
428
450
|
if (!server) {
|
|
429
451
|
releaseLock(lock)
|
|
452
|
+
record('listen-error', false, { code: 'port-unavailable', message: String((lastError && lastError.message) || lastError || '无法监听端口') }, listenOptions.ledgerFile)
|
|
430
453
|
throw lastError || new Error('无法监听端口')
|
|
431
454
|
}
|
|
432
455
|
|
|
@@ -436,6 +459,7 @@ export function createServiceApp(options = {}) {
|
|
|
436
459
|
try { server.close() } catch { /* 忽略 */ }
|
|
437
460
|
server = null
|
|
438
461
|
releaseLock(lock)
|
|
462
|
+
record('listen-error', false, { code: 'write-lock-failed', message: String((error && error.message) || error), stackTop: (error && error.stack) || null }, listenOptions.ledgerFile)
|
|
439
463
|
throw error
|
|
440
464
|
}
|
|
441
465
|
listeningPort = actualPort
|
|
@@ -443,6 +467,7 @@ export function createServiceApp(options = {}) {
|
|
|
443
467
|
|
|
444
468
|
server.on('request', (req, res) => {
|
|
445
469
|
Promise.resolve(app.dispatch(req, res, publicBasePath)).catch((error) => {
|
|
470
|
+
record('dispatch-error', false, { code: 'dispatch-error', message: String((error && error.message) || error), stackTop: (error && error.stack) || null, url: req.url })
|
|
446
471
|
try {
|
|
447
472
|
if (!res.headersSent) send(req, res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
448
473
|
else res.destroy()
|
|
@@ -464,12 +489,14 @@ export function createServiceApp(options = {}) {
|
|
|
464
489
|
|
|
465
490
|
app._lock = lock
|
|
466
491
|
app._discoveryFile = discoveryFile
|
|
492
|
+
record('listen', true, { mode: 'standalone', url, port: actualPort }, listenOptions.ledgerFile)
|
|
467
493
|
return { url, port: actualPort, reused: false, mode: 'standalone', stop: app.close }
|
|
468
494
|
},
|
|
469
495
|
|
|
470
496
|
async close() {
|
|
471
497
|
if (closed) return
|
|
472
498
|
closed = true
|
|
499
|
+
record('closed', true, { phase: 'dispose', mode: embeddedDispose ? 'embedded' : 'standalone' })
|
|
473
500
|
if (embeddedDispose) {
|
|
474
501
|
try { embeddedDispose() } catch { /* 忽略 */ }
|
|
475
502
|
embeddedDispose = null
|
|
@@ -28,6 +28,10 @@ export function createModeGate({ getWorkStore } = {}) {
|
|
|
28
28
|
const domainByTool = new Map() // 原生工具名 → domain
|
|
29
29
|
const domainBySuite = new Map() // 套件名 → domain(描述符发现面按 suite 兜底)
|
|
30
30
|
const lockCache = new Map() // sid → kind(锁终生固化,一旦落定永不变更,可缓存)
|
|
31
|
+
// 规范工作模式种类:套件尚未 declare 时的兜底白名单(保证加载顺序鲁棒);
|
|
32
|
+
// 运行时与已注册 domain 取并集,容纳新增套件。防止拼错的 kind 把会话终生锁进
|
|
33
|
+
// 一个没有任何工具的域(会话砖化)。
|
|
34
|
+
const CANONICAL_KINDS = ['rsp', 'browser', 'ppt', 'canvas', 'capyclaw', 'works']
|
|
31
35
|
let guardInstalled = false
|
|
32
36
|
const guardDisposers = []
|
|
33
37
|
let coreToolsRegistered = false
|
|
@@ -77,6 +81,19 @@ export function createModeGate({ getWorkStore } = {}) {
|
|
|
77
81
|
return domainByTool.get(String(name)) || ''
|
|
78
82
|
}
|
|
79
83
|
|
|
84
|
+
/** 当前可用的工作模式种类(规范白名单 ∪ 已注册 domain),排序去重。 */
|
|
85
|
+
function knownKinds() {
|
|
86
|
+
const set = new Set(CANONICAL_KINDS)
|
|
87
|
+
for (const d of domainBySuite.values()) set.add(d)
|
|
88
|
+
for (const d of domainByTool.values()) set.add(d)
|
|
89
|
+
return [...set].sort()
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** kind 是否为已知工作模式(语义校验,防砖化)。 */
|
|
93
|
+
function isKnownKind(kind) {
|
|
94
|
+
return knownKinds().includes(String(kind || ''))
|
|
95
|
+
}
|
|
96
|
+
|
|
80
97
|
/**
|
|
81
98
|
* DSH register 的 when 条件。未声明领域的工具返回 undefined(不挂 when,恒可见,
|
|
82
99
|
* 也避免给内置/核心工具增加每步求值开销)。
|
|
@@ -125,6 +142,9 @@ export function createModeGate({ getWorkStore } = {}) {
|
|
|
125
142
|
execute: async (args, exec) => {
|
|
126
143
|
const kind = String(args?.kind || '').trim()
|
|
127
144
|
if (!kind) return { ok: false, error: '需要 kind(要锁定的工作模式/领域)' }
|
|
145
|
+
if (!isKnownKind(kind)) {
|
|
146
|
+
return { ok: false, error: `未知的工作模式「${kind}」,未锁定。`, validKinds: knownKinds() }
|
|
147
|
+
}
|
|
128
148
|
const sid = exec?.agent?.session?.id
|
|
129
149
|
if (!sid) return { ok: false, error: '无法识别当前会话,不能锁定' }
|
|
130
150
|
const ws = store()
|
|
@@ -268,5 +288,5 @@ export function createModeGate({ getWorkStore } = {}) {
|
|
|
268
288
|
})
|
|
269
289
|
}
|
|
270
290
|
|
|
271
|
-
return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, installPrompt, filterEntries }
|
|
291
|
+
return { declareTools, domainOf, modeOf, isVisible, whenFor, guard, install, installPrompt, filterEntries, knownKinds, isKnownKind }
|
|
272
292
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capyclaw/browser-workbench",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.23",
|
|
4
4
|
"description": "浏览器操控工作台运行时:18 个 browser_* MCP 工具(导航/快照/点击/填写/按键/下拉/上传/滚动/批量连做/拖拽/标签页/截图)+ Playwright 引擎(有头可见、登录态持久化)+ 可视化工作台。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./plugin.mjs",
|
|
@@ -46,12 +46,12 @@
|
|
|
46
46
|
"license": "MIT",
|
|
47
47
|
"scripts": {},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@capyclaw/asset-service": "^0.1.
|
|
50
|
-
"@capyclaw/document-workbench": "^0.2.
|
|
51
|
-
"@capyclaw/foundation": "^0.1.
|
|
52
|
-
"@capyclaw/plugin-kit": "^0.2.
|
|
53
|
-
"@capyclaw/service-host": "^0.1.
|
|
54
|
-
"@capyclaw/tool-host": "^0.3.
|
|
49
|
+
"@capyclaw/asset-service": "^0.1.8",
|
|
50
|
+
"@capyclaw/document-workbench": "^0.2.6",
|
|
51
|
+
"@capyclaw/foundation": "^0.1.13",
|
|
52
|
+
"@capyclaw/plugin-kit": "^0.2.11",
|
|
53
|
+
"@capyclaw/service-host": "^0.1.10",
|
|
54
|
+
"@capyclaw/tool-host": "^0.3.4",
|
|
55
55
|
"playwright": "^1.64.0"
|
|
56
56
|
},
|
|
57
57
|
"author": {
|
package/server/contract.mjs
CHANGED
|
@@ -10,7 +10,7 @@ import { createCapabilityReport } from './shared/tool-host.mjs'
|
|
|
10
10
|
export const CONTRACT_VERSION = '1.3.0'
|
|
11
11
|
|
|
12
12
|
/** 工作台包版本。 */
|
|
13
|
-
export const PACKAGE_VERSION = '0.1.
|
|
13
|
+
export const PACKAGE_VERSION = '0.1.23'
|
|
14
14
|
|
|
15
15
|
/** 生成模型可读的能力报告。 */
|
|
16
16
|
export function capabilityReport(args, workbenchUrl = '', runtime = {}) {
|
package/server/engine.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { mulberry32, randInt, resolveHumanProfile, bezierPath, moveDurationMs, m
|
|
|
24
24
|
import { openInput, closeInput } from './input.mjs'
|
|
25
25
|
import { readVault, writeVault, vaultSummary } from './login-vault.mjs'
|
|
26
26
|
import { createGovernor } from './governor.mjs'
|
|
27
|
+
import { isMissingBrowserError, resolvePlaywrightCli, ensureBrowserInstalled } from './ensure-browser.mjs'
|
|
27
28
|
|
|
28
29
|
/* --------------------------------------------------------------------------
|
|
29
30
|
* 配置解析(纯函数,可单测)
|
|
@@ -95,6 +96,13 @@ export const ENGINE_CONFIG_DEFAULTS = Object.freeze({
|
|
|
95
96
|
actionRate: 8,
|
|
96
97
|
backoffBaseMs: 4000,
|
|
97
98
|
backoffMaxMs: 60000,
|
|
99
|
+
/* 跨平台内核兜底:启动候选链全失败且判明「没有浏览器内核」时,自动跑一次
|
|
100
|
+
`playwright install chromium` 再重试(macOS 全新安装最常见——安装链 --ignore-scripts
|
|
101
|
+
跳过浏览器下载、又没有系统 Edge 兜底)。单一真源,任何平台开箱即用。
|
|
102
|
+
DSH_BROWSER_AUTO_INSTALL=false 关闭(回到只给安装提示的旧行为)。 */
|
|
103
|
+
autoInstallBrowser: true,
|
|
104
|
+
/* 自动安装 Chromium 的超时(ms):下载 ~150MB,慢网络给足 10 分钟;超时强杀并回落安装提示。 */
|
|
105
|
+
autoInstallTimeoutMs: 600000,
|
|
98
106
|
})
|
|
99
107
|
|
|
100
108
|
const ENV_FIELDS = [
|
|
@@ -131,6 +139,8 @@ const ENV_FIELDS = [
|
|
|
131
139
|
['DSH_BROWSER_ACTION_RATE', 'actionRate', 'number'],
|
|
132
140
|
['DSH_BROWSER_BACKOFF_BASE_MS', 'backoffBaseMs', 'number'],
|
|
133
141
|
['DSH_BROWSER_BACKOFF_MAX_MS', 'backoffMaxMs', 'number'],
|
|
142
|
+
['DSH_BROWSER_AUTO_INSTALL', 'autoInstallBrowser', 'boolean'],
|
|
143
|
+
['DSH_BROWSER_AUTO_INSTALL_TIMEOUT_MS', 'autoInstallTimeoutMs', 'number'],
|
|
134
144
|
]
|
|
135
145
|
|
|
136
146
|
/* 这几个数字字段允许 0(idleTimeoutMs=0 禁用空闲回收;maxRunningEngines=0 不限;
|
|
@@ -631,7 +641,7 @@ export function dshAuthWallNote(text) {
|
|
|
631
641
|
return '这是 DSH Web 自身的鉴权页(401):受控浏览器没有宿主浏览器的认证 cookie,不是目标网站故障。不要重试、不要试图登录宿主 GUI;请让用户在宿主浏览器打开 dsh web 打印的带 token 地址查看界面,受控浏览器继续用于互联网任务'
|
|
632
642
|
}
|
|
633
643
|
|
|
634
|
-
export async function createBrowserEngine({ hostDir, config, playwright, processOps } = {}) { if (!hostDir) throw new Error('createBrowserEngine: 缺少 hostDir')
|
|
644
|
+
export async function createBrowserEngine({ hostDir, config, playwright, processOps, installBrowser } = {}) { if (!hostDir) throw new Error('createBrowserEngine: 缺少 hostDir')
|
|
635
645
|
/* 局部配置必须能覆盖默认值:传 {headless:true} 时 viewport 等未给的键要落到默认,
|
|
636
646
|
否则 launchPersistentContext 收到 viewport.width=undefined 直接起不来。 */
|
|
637
647
|
const cfg = config ? { ...ENGINE_CONFIG_DEFAULTS, ...config } : resolveEngineConfig()
|
|
@@ -653,6 +663,7 @@ export async function createBrowserEngine({ hostDir, config, playwright, process
|
|
|
653
663
|
/* ---- 运行态 ---- */
|
|
654
664
|
let context = null
|
|
655
665
|
let launching = null
|
|
666
|
+
let autoInstallTried = false // 本引擎是否已自动装过一次 Chromium(防缺内核→装→仍缺的死循环)
|
|
656
667
|
let channelUsed = ''
|
|
657
668
|
let detectedUa = '' // 本次启动实际使用的 UA(真实内核版本,只去掉了 Headless 一词)
|
|
658
669
|
let detectedUaFull = '' // 内核完整版本(CDP product,如 156.0.8078.4):UA 字符串按 Chrome 规则削减成 major.0.0.0,完整值只用于 UA-CH
|
|
@@ -963,131 +974,155 @@ export async function createBrowserEngine({ hostDir, config, playwright, process
|
|
|
963
974
|
const cachedUa = cfg.stealth ? readUaCache(hostDir) : null
|
|
964
975
|
let uaHint = cachedUa ? cachedUa.ua : ''
|
|
965
976
|
let uaFullHint = cachedUa ? cachedUa.build : ''
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
candidates.push({ label: '
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
const
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
const
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
977
|
+
/* 候选链抽成可重跑的函数:首轮全失败且判明「缺内核」时,自动装一次 Chromium 后再调它重试。 */
|
|
978
|
+
const runCandidates = async () => {
|
|
979
|
+
const candidates = []
|
|
980
|
+
if (cfg.executablePath) candidates.push({ label: `executablePath(${cfg.executablePath})`, options: { executablePath: cfg.executablePath } })
|
|
981
|
+
if (cfg.channel) candidates.push({ label: `channel:${cfg.channel}`, options: { channel: cfg.channel } })
|
|
982
|
+
/* 实测(bench/probe-stealth-modes.mjs):Playwright 默认的 headless 走 chromium_headless_shell,
|
|
983
|
+
淘宝 baxia 会直接判定异常并下发 punish 框;`channel: 'chromium'` 是完整浏览器的新无头模式,
|
|
984
|
+
同一台机器上 punish 从 4 个降到 0。所以反检测模式下优先完整浏览器。 */
|
|
985
|
+
if (cfg.stealth) candidates.push({ label: 'channel:chromium', options: { channel: 'chromium' } })
|
|
986
|
+
candidates.push({ label: 'chromium', options: {} })
|
|
987
|
+
if (process.platform === 'win32') {
|
|
988
|
+
candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
|
|
989
|
+
candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
|
|
990
|
+
} else {
|
|
991
|
+
candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
|
|
992
|
+
candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
|
|
993
|
+
}
|
|
994
|
+
const seen = new Set()
|
|
995
|
+
for (const candidate of candidates) {
|
|
996
|
+
const key = candidate.label
|
|
997
|
+
if (seen.has(key)) continue
|
|
998
|
+
seen.add(key)
|
|
999
|
+
/* 每个候选最多试两次:首次撞 profile 锁(ProcessSingleton)时强制清扫
|
|
1000
|
+
占用该 profile 的进程(无论父进程死活——profile 每会话独占,撞锁即冲突),
|
|
1001
|
+
然后原样重试一次。其余错误直接记入明细换下一个候选。 */
|
|
1002
|
+
/* 每个候选最多重起一次(换 UA)。计数放在 pass 循环外:放里面会被 pass 递增重置,
|
|
1003
|
+
变成「每轮都重起」,启动时间翻几倍。 */
|
|
1004
|
+
let relaunched = false
|
|
1005
|
+
for (let pass = 0; pass < 2; pass += 1) {
|
|
1006
|
+
const launchUa = uaHint
|
|
1007
|
+
try {
|
|
1008
|
+
const ctx = await launchAttempt(pw.chromium.launchPersistentContext(profileDir, {
|
|
1009
|
+
headless: cfg.headless,
|
|
1010
|
+
viewport: { width: cfg.viewportWidth, height: cfg.viewportHeight },
|
|
1011
|
+
/* 反自动化:去掉 --enable-automation(它会让 navigator.webdriver 为 true、
|
|
1012
|
+
并在窗口上挂「正在受到自动测试软件控制」条),关掉 Blink 的自动化特征,
|
|
1013
|
+
并把 UA 换成与 JS 侧一致的正牌 Chrome(HeadlessChrome 是最显眼的标记)。 */
|
|
1014
|
+
...(cfg.stealth ? {
|
|
1015
|
+
ignoreDefaultArgs: ['--enable-automation'],
|
|
1016
|
+
/* 口径一致:Accept-Language / 时区 / 屏幕尺寸都要和 JS 侧补丁报的对上。
|
|
1017
|
+
locale 决定 Accept-Language 头与 navigator.language;timezoneId 用宿主时区
|
|
1018
|
+
(和 Intl 报的一致);screen 给一个常见桌面分辨率(无头默认屏幕=视口,很假)。
|
|
1019
|
+
window-size = 视口 + 一点窗口边框,让 outerHeight > innerHeight 像真窗口。 */
|
|
1020
|
+
locale: 'zh-CN',
|
|
1021
|
+
timezoneId: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai' } catch { return 'Asia/Shanghai' } })(),
|
|
1022
|
+
screen: { width: 1920, height: 1080 },
|
|
1023
|
+
args: ['--disable-blink-features=AutomationControlled', `--window-size=${cfg.viewportWidth},${cfg.viewportHeight + 100}`],
|
|
1024
|
+
...(uaHint ? { userAgent: uaHint } : {}),
|
|
1025
|
+
} : {}),
|
|
1026
|
+
...candidate.options,
|
|
1027
|
+
}))
|
|
1028
|
+
context = ctx
|
|
1029
|
+
channelUsed = candidate.label
|
|
1030
|
+
/* 真实内核 UA 对齐:缓存里的版本必须与本次启动的内核一致。
|
|
1031
|
+
首启无缓存、缓存是假的、或换了 channel 都会不一致——那就带真实 UA 重起一次,
|
|
1032
|
+
让 HTTP 头与 JS 侧报同一个版本(每个候选只重起一次,避免冷启动死循环)。 */
|
|
1033
|
+
if (cfg.stealth) {
|
|
1034
|
+
const probe = ctx.pages()[0] || (typeof ctx.newPage === 'function' ? await ctx.newPage() : null)
|
|
1035
|
+
/* UA 探测也在启动关键路径上:CDP/evaluate 卡死时 8s 封顶,降级为「无真实 UA」。 */
|
|
1036
|
+
let real = null
|
|
1037
|
+
if (probe) { try { real = await withTimeout(detectRealUserAgent(probe), 8000, '真实 UA 探测') } catch { real = null } }
|
|
1038
|
+
if (real) {
|
|
1039
|
+
detectedUa = real.ua
|
|
1040
|
+
detectedUaFull = real.build
|
|
1041
|
+
uaHint = real.ua
|
|
1042
|
+
uaFullHint = real.build
|
|
1043
|
+
writeUaCache(hostDir, real.ua, real.build)
|
|
1044
|
+
} else if (uaHint) {
|
|
1045
|
+
detectedUa = uaHint
|
|
1046
|
+
}
|
|
1047
|
+
/* 判据是「本次实际用出去的 UA」:拿它和真实值比,才不会每轮都判成不一致。 */
|
|
1048
|
+
if (!relaunched && real && launchUa !== real.ua) {
|
|
1049
|
+
relaunched = true
|
|
1050
|
+
context = null
|
|
1051
|
+
try { await closeAttempt(ctx) } catch { /* 已关/超时:下面重起会撞锁再强清 */ }
|
|
1052
|
+
continue /* 同一候选带真实 UA 重起一次 */
|
|
1053
|
+
}
|
|
1033
1054
|
}
|
|
1034
|
-
/*
|
|
1035
|
-
if (
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1055
|
+
/* 指纹补丁必须在任何导航之前注入:addInitScript 对之后创建的文档生效。 */
|
|
1056
|
+
if (cfg.stealth && typeof ctx.addInitScript === 'function') {
|
|
1057
|
+
try {
|
|
1058
|
+
await ctx.addInitScript({
|
|
1059
|
+
content: stealthInitScript({
|
|
1060
|
+
platform: process.platform === 'win32' ? 'Win32' : process.platform === 'darwin' ? 'MacIntel' : 'Linux x86_64',
|
|
1061
|
+
languages: ['zh-CN', 'zh', 'en-US', 'en'],
|
|
1062
|
+
ua: uaHint || undefined,
|
|
1063
|
+
uaFull: uaFullHint || undefined,
|
|
1064
|
+
screen: { width: 1920, height: 1080 },
|
|
1065
|
+
}),
|
|
1066
|
+
})
|
|
1067
|
+
} catch { /* 老驱动不支持:stealth 降级,不影响可用性 */ }
|
|
1040
1068
|
}
|
|
1069
|
+
/* 先把保险箱里的 cookie 注回去,再注册页面与恢复标签:
|
|
1070
|
+
恢复出来的页面一加载就是已登录状态,不会先闪一下登录页。
|
|
1071
|
+
注入失败(cookie 全过期/坏数据)不影响启动。 */
|
|
1072
|
+
if (cfg.loginVault && typeof ctx.addCookies === 'function') {
|
|
1073
|
+
try {
|
|
1074
|
+
const cookies = readVault(hostDir)
|
|
1075
|
+
vaultInjected = cookies.length
|
|
1076
|
+
if (cookies.length) await ctx.addCookies(cookies)
|
|
1077
|
+
} catch { vaultInjected = 0 }
|
|
1078
|
+
}
|
|
1079
|
+
for (const page of ctx.pages()) { registerPage(page); await applyUaHints(page) }
|
|
1080
|
+
ctx.on('page', (page) => { registerPage(page); activeTabId = tabIds.get(page); void applyUaHints(page) })
|
|
1081
|
+
if (!activeTabId && tabs.size) activeTabId = [...tabs.keys()][0]
|
|
1082
|
+
await restoreJournal(ctx)
|
|
1083
|
+
return ctx
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
const msg = String(error && error.message || error)
|
|
1086
|
+
/* 撞 profile 锁或启动超时:都可能有一个占着 profile 的进程在挡路
|
|
1087
|
+
(超时往往是半启动的浏览器卡住了)。强清占用者后重试本候选一次。 */
|
|
1088
|
+
const timedOut = !!(error && error.code === 'TIMEOUT')
|
|
1089
|
+
if (pass === 0 && cfg.reapOrphans && (isProfileLockError(msg) || timedOut)) {
|
|
1090
|
+
try {
|
|
1091
|
+
const swept = await reapOrphanBrowsers({ profileDirs: [profileDir], processOps: ops, force: true })
|
|
1092
|
+
counters.orphansKilled += swept.killed.length
|
|
1093
|
+
if (swept.killed.length) continue // 清掉了占用者 → 重试本候选
|
|
1094
|
+
} catch { /* 清扫失败 → 按原错误记录 */ }
|
|
1095
|
+
}
|
|
1096
|
+
attempts.push(`${candidate.label}: ${msg.split('\n')[0].slice(0, 200)}`)
|
|
1097
|
+
break
|
|
1041
1098
|
}
|
|
1042
|
-
/* 指纹补丁必须在任何导航之前注入:addInitScript 对之后创建的文档生效。 */
|
|
1043
|
-
if (cfg.stealth && typeof ctx.addInitScript === 'function') {
|
|
1044
|
-
try {
|
|
1045
|
-
await ctx.addInitScript({
|
|
1046
|
-
content: stealthInitScript({
|
|
1047
|
-
platform: process.platform === 'win32' ? 'Win32' : process.platform === 'darwin' ? 'MacIntel' : 'Linux x86_64',
|
|
1048
|
-
languages: ['zh-CN', 'zh', 'en-US', 'en'],
|
|
1049
|
-
ua: uaHint || undefined,
|
|
1050
|
-
uaFull: uaFullHint || undefined,
|
|
1051
|
-
screen: { width: 1920, height: 1080 },
|
|
1052
|
-
}),
|
|
1053
|
-
})
|
|
1054
|
-
} catch { /* 老驱动不支持:stealth 降级,不影响可用性 */ }
|
|
1055
|
-
}
|
|
1056
|
-
/* 先把保险箱里的 cookie 注回去,再注册页面与恢复标签:
|
|
1057
|
-
恢复出来的页面一加载就是已登录状态,不会先闪一下登录页。
|
|
1058
|
-
注入失败(cookie 全过期/坏数据)不影响启动。 */
|
|
1059
|
-
if (cfg.loginVault && typeof ctx.addCookies === 'function') {
|
|
1060
|
-
try {
|
|
1061
|
-
const cookies = readVault(hostDir)
|
|
1062
|
-
vaultInjected = cookies.length
|
|
1063
|
-
if (cookies.length) await ctx.addCookies(cookies)
|
|
1064
|
-
} catch { vaultInjected = 0 }
|
|
1065
|
-
}
|
|
1066
|
-
for (const page of ctx.pages()) { registerPage(page); await applyUaHints(page) }
|
|
1067
|
-
ctx.on('page', (page) => { registerPage(page); activeTabId = tabIds.get(page); void applyUaHints(page) })
|
|
1068
|
-
if (!activeTabId && tabs.size) activeTabId = [...tabs.keys()][0]
|
|
1069
|
-
await restoreJournal(ctx)
|
|
1070
|
-
return ctx
|
|
1071
|
-
} catch (error) {
|
|
1072
|
-
const msg = String(error && error.message || error)
|
|
1073
|
-
/* 撞 profile 锁或启动超时:都可能有一个占着 profile 的进程在挡路
|
|
1074
|
-
(超时往往是半启动的浏览器卡住了)。强清占用者后重试本候选一次。 */
|
|
1075
|
-
const timedOut = !!(error && error.code === 'TIMEOUT')
|
|
1076
|
-
if (pass === 0 && cfg.reapOrphans && (isProfileLockError(msg) || timedOut)) {
|
|
1077
|
-
try {
|
|
1078
|
-
const swept = await reapOrphanBrowsers({ profileDirs: [profileDir], processOps: ops, force: true })
|
|
1079
|
-
counters.orphansKilled += swept.killed.length
|
|
1080
|
-
if (swept.killed.length) continue // 清掉了占用者 → 重试本候选
|
|
1081
|
-
} catch { /* 清扫失败 → 按原错误记录 */ }
|
|
1082
|
-
}
|
|
1083
|
-
attempts.push(`${candidate.label}: ${msg.split('\n')[0].slice(0, 200)}`)
|
|
1084
|
-
break
|
|
1085
1099
|
}
|
|
1086
1100
|
}
|
|
1101
|
+
return null
|
|
1102
|
+
}
|
|
1103
|
+
let ctx = await runCandidates()
|
|
1104
|
+
/* 跨平台内核兜底(单一真源,见 ensure-browser.mjs):全候选失败且明细里判明「没有浏览器
|
|
1105
|
+
内核」时,自动跑一次 `playwright install chromium` 再重试候选链。macOS 全新安装最常见
|
|
1106
|
+
(安装链 --ignore-scripts 跳过浏览器下载、无系统 Edge 兜底);Windows/Linux 干净系统同样受益。
|
|
1107
|
+
每引擎只试一次;撞锁/超时等非缺内核错误不触发安装。DSH_BROWSER_AUTO_INSTALL=false 关闭。 */
|
|
1108
|
+
let installNote = ''
|
|
1109
|
+
if (!ctx && cfg.autoInstallBrowser && !autoInstallTried && attempts.some((a) => isMissingBrowserError(a))) {
|
|
1110
|
+
autoInstallTried = true
|
|
1111
|
+
const cliPath = resolvePlaywrightCli({ driver: cfg.stealthDriver, requireFn: engineRequire })
|
|
1112
|
+
process.stderr.write('[browser] 未检测到浏览器内核,自动安装 Playwright Chromium(一次性;DSH_BROWSER_AUTO_INSTALL=false 可关闭)…\n')
|
|
1113
|
+
const res = await (installBrowser || ensureBrowserInstalled)({ cliPath, timeoutMs: cfg.autoInstallTimeoutMs })
|
|
1114
|
+
if (res.ok) {
|
|
1115
|
+
process.stderr.write('[browser] Chromium 安装完成,重试启动。\n')
|
|
1116
|
+
attempts.length = 0
|
|
1117
|
+
ctx = await runCandidates()
|
|
1118
|
+
} else {
|
|
1119
|
+
installNote = `自动安装 Chromium 失败(${res.timedOut ? '超时' : '退出码 ' + res.code}):${String(res.log).slice(-300)}。`
|
|
1120
|
+
}
|
|
1087
1121
|
}
|
|
1122
|
+
if (ctx) return ctx
|
|
1088
1123
|
throw engineError('ENGINE_LAUNCH_FAILED',
|
|
1089
1124
|
`浏览器启动失败(已尝试 ${attempts.length} 种方式)`,
|
|
1090
|
-
|
|
1125
|
+
`${installNote}安装 Playwright Chromium(npx playwright install chromium)或系统 Chrome/Edge 后重试。尝试明细:${attempts.join(';')}`)
|
|
1091
1126
|
})()
|
|
1092
1127
|
try {
|
|
1093
1128
|
return await launching
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 跨平台浏览器内核兜底(单一真源,不为 macOS 分叉)。
|
|
3
|
+
*
|
|
4
|
+
* 背景:安装链走 `pnpm install --ignore-scripts`,会跳过 Playwright 的浏览器下载 postinstall。
|
|
5
|
+
* Windows 有系统 Edge/Chrome 兜底所以常常无感;macOS 全新机器若没装 Chrome、又没手动跑
|
|
6
|
+
* `npx playwright install chromium`,启动候选链就全失败,报「没有浏览器内核」(ENGINE_LAUNCH_FAILED)。
|
|
7
|
+
* Linux 干净系统同理。这里在引擎判明「缺内核」时自动跑一次 `playwright install chromium`,
|
|
8
|
+
* 然后让引擎重试候选链——任何平台开箱即用。
|
|
9
|
+
*
|
|
10
|
+
* 设计:纯函数 + 可注入 spawn/require,便于单测;真实安装只在启动失败且判明缺内核时触发,
|
|
11
|
+
* 每引擎只试一次(autoInstallTried),跨引擎并发共享同一次下载(inflight)。
|
|
12
|
+
* 用 process.execPath(宿主 node)跑 CLI,不依赖 PATH 里有 node/npx;继承 env 使
|
|
13
|
+
* PLAYWRIGHT_BROWSERS_PATH 等设置在「安装」与「启动查找」两侧一致。
|
|
14
|
+
*/
|
|
15
|
+
import path from 'node:path'
|
|
16
|
+
import { spawn } from 'node:child_process'
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* 判明「没有浏览器内核」的启动错误(区别于撞 profile 锁 / 启动超时 / 导航失败)。
|
|
20
|
+
* Playwright 缺内核的典型文案:
|
|
21
|
+
* - "Executable doesn't exist at /path/..."(bundled chromium 未下载)
|
|
22
|
+
* - "Please run the following command to download new browsers: npx playwright install"
|
|
23
|
+
* - "Chromium distribution 'chrome' is not found at ..."(channel 找不到系统浏览器)
|
|
24
|
+
* 传入的通常是引擎候选明细串 `${label}: ${msg}`,label 含 chromium/chrome/msedge 字样。
|
|
25
|
+
*/
|
|
26
|
+
export function isMissingBrowserError(message) {
|
|
27
|
+
const msg = String(message || '')
|
|
28
|
+
if (/Executable doesn't exist/i.test(msg)) return true
|
|
29
|
+
if (/download new browsers/i.test(msg)) return true
|
|
30
|
+
if (/playwright install/i.test(msg)) return true
|
|
31
|
+
if (/distribution\s+'[^']*'\s+is not found/i.test(msg)) return true
|
|
32
|
+
if (/is not found/i.test(msg) && /chromium|chrome|msedge|browser/i.test(msg)) return true
|
|
33
|
+
return false
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 定位 Playwright CLI(install 子命令入口)。优先 require.resolve('<pkg>/cli.js'),
|
|
38
|
+
* 退回 package.json 同目录的 cli.js。patchright 驱动优先 patchright、回落 playwright。
|
|
39
|
+
* 注入 requireFn(createRequire 产物)便于单测;拿不到返回 ''。
|
|
40
|
+
*/
|
|
41
|
+
export function resolvePlaywrightCli({ driver = '', requireFn } = {}) {
|
|
42
|
+
if (!requireFn || typeof requireFn.resolve !== 'function') return ''
|
|
43
|
+
const names = String(driver || '').toLowerCase() === 'patchright' ? ['patchright', 'playwright'] : ['playwright']
|
|
44
|
+
for (const name of names) {
|
|
45
|
+
try { return requireFn.resolve(`${name}/cli.js`) } catch { /* 换下一种定位 */ }
|
|
46
|
+
try { return path.join(path.dirname(requireFn.resolve(`${name}/package.json`)), 'cli.js') } catch { /* 没装这个包 */ }
|
|
47
|
+
}
|
|
48
|
+
return ''
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* 跑 `node cli.js install chromium`。注入 spawnFn 便于单测;真实用 process.execPath。
|
|
53
|
+
* stdout/stderr 收进日志(尾部 4000 字符)并可选 onLog 实时回报;超时强杀。
|
|
54
|
+
* 返回 { ok, code, log, timedOut }。ok 仅在退出码 0 且未超时时为真。
|
|
55
|
+
*/
|
|
56
|
+
export function installChromium({ cliPath, nodePath = process.execPath, timeoutMs = 600000, onLog, spawnFn = spawn, env = process.env } = {}) {
|
|
57
|
+
return new Promise((resolve) => {
|
|
58
|
+
if (!cliPath) {
|
|
59
|
+
resolve({ ok: false, code: -1, log: '未找到 Playwright CLI(playwright/cli.js)', timedOut: false })
|
|
60
|
+
return
|
|
61
|
+
}
|
|
62
|
+
let child
|
|
63
|
+
try {
|
|
64
|
+
child = spawnFn(nodePath, [cliPath, 'install', 'chromium'], { env, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
65
|
+
} catch (error) {
|
|
66
|
+
resolve({ ok: false, code: -1, log: String(error && error.message || error), timedOut: false })
|
|
67
|
+
return
|
|
68
|
+
}
|
|
69
|
+
const logs = []
|
|
70
|
+
let timedOut = false
|
|
71
|
+
let settled = false
|
|
72
|
+
const finish = (result) => { if (!settled) { settled = true; if (timer) clearTimeout(timer); resolve(result) } }
|
|
73
|
+
const timer = timeoutMs > 0 ? setTimeout(() => { timedOut = true; try { child.kill('SIGKILL') } catch { /* 已退出 */ } }, timeoutMs) : null
|
|
74
|
+
const collect = (chunk) => {
|
|
75
|
+
const s = String(chunk)
|
|
76
|
+
logs.push(s)
|
|
77
|
+
if (onLog) { try { onLog(s) } catch { /* 日志回报失败不影响安装 */ } }
|
|
78
|
+
}
|
|
79
|
+
if (child.stdout) child.stdout.on('data', collect)
|
|
80
|
+
if (child.stderr) child.stderr.on('data', collect)
|
|
81
|
+
child.on('error', (error) => finish({ ok: false, code: -1, log: String(error && error.message || error), timedOut }))
|
|
82
|
+
child.on('close', (code) => finish({ ok: code === 0 && !timedOut, code: code == null ? -1 : code, log: logs.join('').slice(-4000), timedOut }))
|
|
83
|
+
})
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* 跨引擎并发共享同一次下载:relay 每会话一个引擎,两个会话同时首启不该各下一份 Chromium。
|
|
87
|
+
按 cliPath 键控;安装结束(成败皆然)即释放,下次缺内核仍可再试。 */
|
|
88
|
+
const inflight = new Map()
|
|
89
|
+
|
|
90
|
+
/** ensureBrowserInstalled:installChromium 的并发去重包装。 */
|
|
91
|
+
export function ensureBrowserInstalled(opts = {}) {
|
|
92
|
+
const key = opts.cliPath || 'default'
|
|
93
|
+
if (inflight.has(key)) return inflight.get(key)
|
|
94
|
+
const p = installChromium(opts).finally(() => inflight.delete(key))
|
|
95
|
+
inflight.set(key, p)
|
|
96
|
+
return p
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 测试用:清空并发缓存。 */
|
|
100
|
+
export function _resetInflight() { inflight.clear() }
|
|
@@ -4,28 +4,28 @@
|
|
|
4
4
|
"packages": {
|
|
5
5
|
"service-host": {
|
|
6
6
|
"package": "@capyclaw/service-host",
|
|
7
|
-
"version": "0.1.
|
|
7
|
+
"version": "0.1.10",
|
|
8
8
|
"apiVersion": "1.0.0",
|
|
9
9
|
"spec": "@capyclaw/service-host/src",
|
|
10
10
|
"sha256": "af0a57d779bfe6a66dc935320178d591ef799a7e037f7a5823cdfa1fe5878eeb"
|
|
11
11
|
},
|
|
12
12
|
"tool-host": {
|
|
13
13
|
"package": "@capyclaw/tool-host",
|
|
14
|
-
"version": "0.3.
|
|
14
|
+
"version": "0.3.4",
|
|
15
15
|
"apiVersion": "1.1.0",
|
|
16
16
|
"spec": "@capyclaw/tool-host/src",
|
|
17
17
|
"sha256": "23256dbcd5cbee0b96b33c97e4eb4e74d0e169cbdde52f91d4526f2fc0f60d3e"
|
|
18
18
|
},
|
|
19
19
|
"asset-service": {
|
|
20
20
|
"package": "@capyclaw/asset-service",
|
|
21
|
-
"version": "0.1.
|
|
21
|
+
"version": "0.1.8",
|
|
22
22
|
"apiVersion": "1.0.0",
|
|
23
23
|
"spec": "@capyclaw/asset-service/src",
|
|
24
24
|
"sha256": "311a83e95d56dbb69b739d61aced0889b64e85eddd95b883e322e0fa5be8bd6f"
|
|
25
25
|
},
|
|
26
26
|
"editor-host": {
|
|
27
27
|
"package": "@capyclaw/editor-host",
|
|
28
|
-
"version": "0.1.
|
|
28
|
+
"version": "0.1.9",
|
|
29
29
|
"apiVersion": "1.0.0",
|
|
30
30
|
"spec": "@capyclaw/editor-host/src",
|
|
31
31
|
"sha256": "c8b80dbd4f1b2bee9ef9001423a013031a21ea9a3b8897b5536fe6e5687f01b3"
|