dsh-rig 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.
- package/CHANGELOG.md +26 -0
- package/LICENSE +202 -0
- package/NOTICE +18 -0
- package/README.en.md +100 -0
- package/README.md +101 -2
- package/cordis.patch.yml +3 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/preview.svg +40 -0
- package/docs/screenshot-detail.png +0 -0
- package/docs/screenshot-panel.png +0 -0
- package/icon.svg +8 -0
- package/lib/client.js +591 -0
- package/lib/http/routes.js +177 -0
- package/lib/index.js +130 -0
- package/lib/lab/browser.js +221 -0
- package/lib/lab/constants.js +68 -0
- package/lib/lab/core-bin.js +29 -0
- package/lib/lab/diagnostics.js +34 -0
- package/lib/lab/driver.js +52 -0
- package/lib/lab/layout.js +38 -0
- package/lib/lab/log-buffer.js +50 -0
- package/lib/lab/naming.js +77 -0
- package/lib/lab/probe.js +56 -0
- package/lib/lab/process.js +48 -0
- package/lib/lab/redact.js +23 -0
- package/lib/lab/registry.js +89 -0
- package/lib/lab/report.js +162 -0
- package/lib/lab/runtime.js +106 -0
- package/lib/lab/seed.js +80 -0
- package/lib/lab/spawn-plan.js +114 -0
- package/lib/lab/supervisor.js +419 -0
- package/lib/lab/ui/cdp-impl.js +190 -0
- package/lib/lab/ui/playwright-impl.js +185 -0
- package/lib/lab/ui-session.js +100 -0
- package/lib/lab/versions.js +107 -0
- package/lib/tools/lab-tool.js +130 -0
- package/lib/tools/lab-ui-tool.js +67 -0
- package/lib/tools/mount.js +64 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +83 -4
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 进程看管(IO 层 · 唯一写盘点)
|
|
3
|
+
*
|
|
4
|
+
* 只做三件事:**把实验室拉起来、看着它、把它收干净**。
|
|
5
|
+
* 拼命令行在 `spawn-plan.js`(纯)、判隔离在 `naming.js`(纯)、日志缓冲在 `log-buffer.js`(纯)、
|
|
6
|
+
* 瞬时状态在 `runtime.js`(纯)、探针在 `probe.js`、一次性命令在 `seed.js`、界面驱动在 `ui-session.js`。
|
|
7
|
+
* 这里只负责把它们串起来,并保证**所有落盘与杀进程都只发生在本文件**。
|
|
8
|
+
*
|
|
9
|
+
* 刻意不做的两件事:
|
|
10
|
+
* - 不做常驻健康轮询:只在启动阶段探到活,之后靠子进程 `exit` 判死。
|
|
11
|
+
* 常驻轮询会让「卡住」和「在忙」长得一样,反而更难判断。
|
|
12
|
+
* - 不持久化端口/token/pid:端口每次由系统分配、token 每次现生成。
|
|
13
|
+
*/
|
|
14
|
+
import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import { DEFAULTS, STATUS } from './constants.js'
|
|
17
|
+
import { labPaths } from './layout.js'
|
|
18
|
+
import { assertIsolated, isValidLabId, nextLabId, profileNameFor } from './naming.js'
|
|
19
|
+
import { buildSeedPlan, buildStartPlan, parseLabUrl } from './spawn-plan.js'
|
|
20
|
+
import { buildDiagnostics } from './diagnostics.js'
|
|
21
|
+
import { resolveCoreBin } from './core-bin.js'
|
|
22
|
+
import { copyCredentials, runOnce } from './seed.js'
|
|
23
|
+
import { attachLines, killTree, spawnChild } from './process.js'
|
|
24
|
+
import { probeOnce } from './probe.js'
|
|
25
|
+
import { addLab, describeLab, emptyState, findLab, parseState, removeLab, serializeState } from './registry.js'
|
|
26
|
+
import { createRuntimeTable } from './runtime.js'
|
|
27
|
+
import { UiSessions } from './ui-session.js'
|
|
28
|
+
import { buildLabReport } from './report.js'
|
|
29
|
+
|
|
30
|
+
export class LabSupervisor {
|
|
31
|
+
#root
|
|
32
|
+
#hostHome
|
|
33
|
+
#hostProfile
|
|
34
|
+
#execPath
|
|
35
|
+
#isElectron
|
|
36
|
+
#env
|
|
37
|
+
#log
|
|
38
|
+
#config
|
|
39
|
+
#state = emptyState()
|
|
40
|
+
#rt
|
|
41
|
+
#ui
|
|
42
|
+
#uiMode = false
|
|
43
|
+
#disposed = false
|
|
44
|
+
|
|
45
|
+
constructor(opts) {
|
|
46
|
+
this.#root = opts.root
|
|
47
|
+
this.#hostHome = opts.hostHome
|
|
48
|
+
this.#hostProfile = opts.hostProfile || 'web'
|
|
49
|
+
this.#execPath = opts.execPath
|
|
50
|
+
this.#isElectron = Boolean(opts.isElectron)
|
|
51
|
+
this.#env = opts.env || {}
|
|
52
|
+
this.#log = typeof opts.log === 'function' ? opts.log : () => {}
|
|
53
|
+
this.#config = { ...DEFAULTS, ...(opts.config || {}) }
|
|
54
|
+
this.#rt = createRuntimeTable({
|
|
55
|
+
logRingLines: this.#config.logRingLines,
|
|
56
|
+
log: (line) => this.#log(line),
|
|
57
|
+
onEvent: opts.onEvent,
|
|
58
|
+
})
|
|
59
|
+
// 后端偏好:配置优先,其次环境变量(调试时一条 export 就能强制走 CDP)。
|
|
60
|
+
const backendPreference = this.#config.uiBackend || this.#env.DSH_RIG_UI_BACKEND || 'auto'
|
|
61
|
+
this.#ui = new UiSessions({ log: (line) => this.#log(line), preference: backendPreference })
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ── 事件 ────────────────────────────────────────────────────────────
|
|
65
|
+
subscribe(fn) {
|
|
66
|
+
return this.#rt.subscribe(fn)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ── 持久状态 ────────────────────────────────────────────────────────
|
|
70
|
+
async load() {
|
|
71
|
+
const { labsFile, root } = labPaths(this.#root, null)
|
|
72
|
+
await mkdir(root, { recursive: true })
|
|
73
|
+
let text = ''
|
|
74
|
+
try {
|
|
75
|
+
text = await readFile(labsFile, 'utf8')
|
|
76
|
+
} catch {
|
|
77
|
+
this.#state = emptyState()
|
|
78
|
+
return this.#state
|
|
79
|
+
}
|
|
80
|
+
const { state, problem } = parseState(text)
|
|
81
|
+
if (problem) this.#log(`[dsh-rig] labs.json 读不出(${problem}),按空状态处理`)
|
|
82
|
+
this.#state = state
|
|
83
|
+
return state
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async #save() {
|
|
87
|
+
const { labsFile } = labPaths(this.#root, null)
|
|
88
|
+
const tmp = `${labsFile}.tmp`
|
|
89
|
+
await writeFile(tmp, serializeState(this.#state), 'utf8')
|
|
90
|
+
await rename(tmp, labsFile)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ── 读取 ────────────────────────────────────────────────────────────
|
|
94
|
+
list() {
|
|
95
|
+
return this.#state.labs.map((lab) => describeLab(lab, this.#rt.get(lab.id)))
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
get(id) {
|
|
99
|
+
const lab = findLab(this.#state, id)
|
|
100
|
+
return lab ? describeLab(lab, this.#rt.get(id)) : null
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
logs(id, since = 0) {
|
|
104
|
+
return this.#rt.logs(id, since)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 体检:声明 / 补丁 / 运行时 / 启动日志事实 / 工作区,五块证据各自独立。 */
|
|
108
|
+
async report(id) {
|
|
109
|
+
const lab = findLab(this.#state, id)
|
|
110
|
+
if (!lab) throw new Error(`没有实验室 ${id}`)
|
|
111
|
+
const paths = labPaths(this.#root, id)
|
|
112
|
+
return buildLabReport({
|
|
113
|
+
lab,
|
|
114
|
+
runtime: this.#rt.get(id),
|
|
115
|
+
labPaths: paths,
|
|
116
|
+
logEntries: this.#rt.logs(id, 0).entries,
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
diagnostics() {
|
|
121
|
+
const sample = this.#state.labs[0]
|
|
122
|
+
return buildDiagnostics({
|
|
123
|
+
labRoot: this.#root,
|
|
124
|
+
hostHome: this.#hostHome,
|
|
125
|
+
hostProfile: this.#hostProfile,
|
|
126
|
+
isElectron: this.#isElectron,
|
|
127
|
+
env: this.#env,
|
|
128
|
+
limits: {
|
|
129
|
+
startTimeoutMs: this.#config.startTimeoutMs,
|
|
130
|
+
logRingLines: this.#config.logRingLines,
|
|
131
|
+
maxLabs: this.#config.maxLabs,
|
|
132
|
+
},
|
|
133
|
+
sampleLabHome: sample ? labPaths(this.#root, sample.id).home : null,
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ── 界面驱动(让智能体像人一样操作实验室) ──────────────────────────
|
|
138
|
+
uiAvailable() {
|
|
139
|
+
return this.#ui.available()
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** 智能体能否操作界面:默认关,随宿主重启复位(避免「一次授权永久生效」)。 */
|
|
143
|
+
uiMode() {
|
|
144
|
+
return this.#uiMode
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
setUiMode(enabled) {
|
|
148
|
+
const next = Boolean(enabled)
|
|
149
|
+
if (next === this.#uiMode) return next
|
|
150
|
+
this.#uiMode = next
|
|
151
|
+
this.#rt.emit({ type: 'ui-mode', enabled: next })
|
|
152
|
+
return next
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* 看 / 拍 / 点 / 打 / 跑任务。不碰实验室内部服务,只驱动它的界面。
|
|
157
|
+
* 这样它对界面改版是**脆**的 —— 所以按文字找元素、找不到就报候选,而不是点空。
|
|
158
|
+
*/
|
|
159
|
+
async ui(id, action, args = {}) {
|
|
160
|
+
if (!this.#uiMode) throw new Error('智能体操作界面未开启:先在面板里打开「允许智能体操作」')
|
|
161
|
+
const lab = findLab(this.#state, id)
|
|
162
|
+
if (!lab) throw new Error(`没有实验室 ${id}`)
|
|
163
|
+
const rt = this.#rt.get(id)
|
|
164
|
+
if (!rt || !rt.url) throw new Error('实验室没在运行:先 start')
|
|
165
|
+
return this.#ui.call(id, rt.url, labPaths(this.#root, id).dir, action, args)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// ── 生命周期 ────────────────────────────────────────────────────────
|
|
169
|
+
async create({ name, version = 'host' } = {}) {
|
|
170
|
+
if (this.#state.labs.length >= this.#config.maxLabs) {
|
|
171
|
+
throw new Error(`最多 ${this.#config.maxLabs} 个实验室;先销毁一个`)
|
|
172
|
+
}
|
|
173
|
+
const id = nextLabId(this.#state.labs.map((lab) => lab.id))
|
|
174
|
+
if (!id) throw new Error('没有可用 id')
|
|
175
|
+
|
|
176
|
+
const paths = labPaths(this.#root, id)
|
|
177
|
+
const iso = assertIsolated(paths.home, this.#hostHome)
|
|
178
|
+
if (!iso.ok) throw new Error(`拒绝创建:${iso.reason}`)
|
|
179
|
+
|
|
180
|
+
await mkdir(paths.home, { recursive: true })
|
|
181
|
+
await mkdir(paths.workspace, { recursive: true })
|
|
182
|
+
await mkdir(paths.tasks, { recursive: true })
|
|
183
|
+
|
|
184
|
+
const lab = {
|
|
185
|
+
id,
|
|
186
|
+
name: typeof name === 'string' && name.trim() !== '' ? name.trim().slice(0, 40) : `实验台 ${id}`,
|
|
187
|
+
version: typeof version === 'string' ? version : 'host',
|
|
188
|
+
profile: profileNameFor(id),
|
|
189
|
+
createdAt: new Date().toISOString(),
|
|
190
|
+
}
|
|
191
|
+
this.#rt.of(id)
|
|
192
|
+
|
|
193
|
+
await this.#seedProfile(lab)
|
|
194
|
+
if (this.#config.copyCredentials !== false) {
|
|
195
|
+
const ok = await copyCredentials({ fromHome: this.#hostHome, toHome: paths.home })
|
|
196
|
+
this.#rt.pushLog(
|
|
197
|
+
id,
|
|
198
|
+
'rig',
|
|
199
|
+
ok ? '已复制宿主凭据到实验室(可在配置里关掉)' : '宿主凭据不存在或复制失败:实验室里的智能体将没有可用模型',
|
|
200
|
+
)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
addLab(this.#state, lab)
|
|
204
|
+
await this.#save()
|
|
205
|
+
this.#rt.pushLog(id, 'rig', `实验室已创建:${lab.name}(profile=${lab.profile})`)
|
|
206
|
+
this.#rt.emit({ type: 'labs', at: new Date().toISOString() })
|
|
207
|
+
return this.get(id)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** 建 profile:一次性命令,`--dump-config` 只算不建、不起服务。 */
|
|
211
|
+
async #seedProfile(lab) {
|
|
212
|
+
const paths = labPaths(this.#root, lab.id)
|
|
213
|
+
let coreBin
|
|
214
|
+
try {
|
|
215
|
+
coreBin = await resolveCoreBin({ version: lab.version, root: this.#root, env: this.#env })
|
|
216
|
+
} catch (err) {
|
|
217
|
+
this.#rt.pushLog(lab.id, 'rig', `建 profile 失败:${err?.message ?? err}`)
|
|
218
|
+
return
|
|
219
|
+
}
|
|
220
|
+
const plan = buildSeedPlan({
|
|
221
|
+
execPath: this.#execPath,
|
|
222
|
+
isElectron: this.#isElectron,
|
|
223
|
+
coreBin,
|
|
224
|
+
profile: lab.profile,
|
|
225
|
+
cwd: paths.workspace,
|
|
226
|
+
home: paths.home,
|
|
227
|
+
env: this.#env,
|
|
228
|
+
})
|
|
229
|
+
const result = await runOnce(plan, {
|
|
230
|
+
onLine: (stream, line) => {
|
|
231
|
+
// 建 profile 的输出里,只有「被禁用的插件行」值得留给人看,其余(整份 dump)丢掉。
|
|
232
|
+
if (stream === 'err' && /disabling profile plugin row|incompatible with dsh/iu.test(line)) {
|
|
233
|
+
this.#rt.pushLog(lab.id, 'seed', line)
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
})
|
|
237
|
+
this.#rt.pushLog(lab.id, 'rig', `profile 就绪(exit ${result.code ?? 'null'}${result.timedOut ? ',超时' : ''})`)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async start(id) {
|
|
241
|
+
const lab = findLab(this.#state, id)
|
|
242
|
+
if (!lab) throw new Error(`没有实验室 ${id}`)
|
|
243
|
+
const rt = this.#rt.of(id)
|
|
244
|
+
if (rt.status === STATUS.starting || rt.status === STATUS.running) return this.get(id)
|
|
245
|
+
|
|
246
|
+
const paths = labPaths(this.#root, id)
|
|
247
|
+
const iso = assertIsolated(paths.home, this.#hostHome)
|
|
248
|
+
if (!iso.ok) throw new Error(`拒绝启动:${iso.reason}`)
|
|
249
|
+
|
|
250
|
+
await mkdir(paths.home, { recursive: true })
|
|
251
|
+
await mkdir(paths.workspace, { recursive: true })
|
|
252
|
+
|
|
253
|
+
const plan = buildStartPlan({
|
|
254
|
+
execPath: this.#execPath,
|
|
255
|
+
isElectron: this.#isElectron,
|
|
256
|
+
coreBin: await resolveCoreBin({ version: lab.version, root: this.#root, env: this.#env }),
|
|
257
|
+
profile: lab.profile,
|
|
258
|
+
cwd: paths.workspace,
|
|
259
|
+
home: paths.home,
|
|
260
|
+
env: this.#env,
|
|
261
|
+
})
|
|
262
|
+
|
|
263
|
+
rt.exit = null
|
|
264
|
+
rt.port = null
|
|
265
|
+
rt.url = null
|
|
266
|
+
rt.token = null
|
|
267
|
+
this.#rt.setStatus(id, STATUS.starting, { startedAt: new Date().toISOString() })
|
|
268
|
+
this.#rt.pushLog(id, 'rig', `启动:${plan.command} ${plan.args.join(' ')}`)
|
|
269
|
+
this.#rt.pushLog(id, 'rig', `DSH_HOME=${plan.env.DSH_HOME} cwd=${plan.cwd}`)
|
|
270
|
+
|
|
271
|
+
let child
|
|
272
|
+
try {
|
|
273
|
+
child = spawnChild(plan)
|
|
274
|
+
} catch (err) {
|
|
275
|
+
this.#rt.setStatus(id, STATUS.crashed, { exit: { code: null, at: new Date().toISOString(), error: String(err) } })
|
|
276
|
+
throw err
|
|
277
|
+
}
|
|
278
|
+
rt.child = child
|
|
279
|
+
rt.pid = child.pid ?? null
|
|
280
|
+
|
|
281
|
+
// 注意签名:process.js 的 attachLines 回调是 (stream, line),不是柯里化 ——
|
|
282
|
+
// 2026-11-21 重构时这里错成柯里化,结果实验室的输出一行都没被接收,看着像「启动卡死」。
|
|
283
|
+
attachLines(child, (stream, line) => {
|
|
284
|
+
if (!this.#rt.pushLog(id, stream, line)) return
|
|
285
|
+
const parsed = parseLabUrl(line)
|
|
286
|
+
if (parsed) {
|
|
287
|
+
rt.port = parsed.port
|
|
288
|
+
rt.token = parsed.token
|
|
289
|
+
rt.url = parsed.url
|
|
290
|
+
this.#rt.emit({ type: 'url', id, url: parsed.url, port: parsed.port })
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
child.on('error', (err) => {
|
|
295
|
+
this.#rt.pushLog(id, 'rig', `子进程错误:${err?.message ?? err}`)
|
|
296
|
+
this.#rt.setStatus(id, STATUS.crashed, { exit: { code: null, at: new Date().toISOString(), error: String(err) } })
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
child.on('exit', (code, signal) => {
|
|
300
|
+
rt.child = null
|
|
301
|
+
rt.pid = null
|
|
302
|
+
const wasLive = rt.status === STATUS.starting || rt.status === STATUS.running
|
|
303
|
+
const exit = { code: code ?? null, signal: signal ?? null, at: new Date().toISOString() }
|
|
304
|
+
this.#rt.pushLog(id, 'rig', `实验室退出:code=${exit.code ?? 'null'} signal=${exit.signal ?? 'null'}`)
|
|
305
|
+
if (wasLive && code !== 0) this.#rt.setStatus(id, STATUS.crashed, { exit })
|
|
306
|
+
else if (wasLive) this.#rt.setStatus(id, STATUS.stopped, { exit })
|
|
307
|
+
rt.url = null
|
|
308
|
+
rt.token = null
|
|
309
|
+
rt.port = null
|
|
310
|
+
this.#ui.close(id)
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
void this.#waitHealthy(id, rt, Date.now() + this.#config.startTimeoutMs)
|
|
314
|
+
return this.get(id)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
async #waitHealthy(id, rt, deadline) {
|
|
318
|
+
let firstFailure = ''
|
|
319
|
+
while (!this.#disposed && Date.now() < deadline) {
|
|
320
|
+
if (rt.status !== STATUS.starting) return
|
|
321
|
+
if (rt.url) {
|
|
322
|
+
const probe = await probeOnce(rt.url)
|
|
323
|
+
if (probe.ok) {
|
|
324
|
+
this.#rt.setStatus(id, STATUS.running)
|
|
325
|
+
this.#rt.pushLog(id, 'rig', `就绪:${rt.url.replace(/token=[^&]+/u, 'token=***')}`)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
// 只记第一次失败:探针会连失败几百次,全记会把日志刷爆。
|
|
329
|
+
if (firstFailure === '') {
|
|
330
|
+
firstFailure = probe.reason || 'unknown'
|
|
331
|
+
this.#rt.pushLog(id, 'rig', `探针未通过(${firstFailure}),继续等…`)
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
await new Promise((r) => setTimeout(r, this.#config.healthPollMs))
|
|
335
|
+
}
|
|
336
|
+
if (rt.status === STATUS.starting) {
|
|
337
|
+
this.#rt.pushLog(
|
|
338
|
+
id,
|
|
339
|
+
'rig',
|
|
340
|
+
`启动超时(${Math.round(this.#config.startTimeoutMs / 1000)}s)${firstFailure ? `:${firstFailure}` : ''}`,
|
|
341
|
+
)
|
|
342
|
+
await this.stop(id, { asCrash: true })
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
async stop(id, opts = {}) {
|
|
347
|
+
const rt = this.#rt.get(id)
|
|
348
|
+
if (!rt) return this.get(id)
|
|
349
|
+
const pid = rt.pid
|
|
350
|
+
if (pid) {
|
|
351
|
+
this.#rt.pushLog(id, 'rig', `停止 pid=${pid}…`)
|
|
352
|
+
try {
|
|
353
|
+
await killTree(pid)
|
|
354
|
+
} catch (err) {
|
|
355
|
+
this.#rt.pushLog(id, 'rig', `停止命令失败(进程可能已退出):${err?.message ?? err}`)
|
|
356
|
+
}
|
|
357
|
+
const until = Date.now() + 10_000
|
|
358
|
+
while (rt.pid && Date.now() < until) await new Promise((r) => setTimeout(r, 200))
|
|
359
|
+
}
|
|
360
|
+
if (opts.asCrash) this.#rt.setStatus(id, STATUS.crashed)
|
|
361
|
+
else if (rt.status !== STATUS.crashed) this.#rt.setStatus(id, STATUS.stopped)
|
|
362
|
+
rt.url = null
|
|
363
|
+
rt.token = null
|
|
364
|
+
rt.port = null
|
|
365
|
+
this.#ui.close(id)
|
|
366
|
+
return this.get(id)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** 切版本:只改声明并落盘;真正生效要重启(面板/工具会提示)。 */
|
|
370
|
+
async setVersion(id, version) {
|
|
371
|
+
const lab = findLab(this.#state, id)
|
|
372
|
+
if (!lab) throw new Error(`没有实验室 ${id}`)
|
|
373
|
+
const next = typeof version === 'string' && version.trim() !== '' ? version.trim() : 'host'
|
|
374
|
+
// 切到某个具体版本前先确认它真的装着:否则重启时才发现,等于把失败推给下一次启动。
|
|
375
|
+
if (next !== 'host') await resolveCoreBin({ version: next, root: this.#root, env: this.#env })
|
|
376
|
+
lab.version = next
|
|
377
|
+
await this.#save()
|
|
378
|
+
this.#rt.emit({ type: 'labs', at: new Date().toISOString() })
|
|
379
|
+
this.#rt.pushLog(id, 'rig', `版本已切换为 ${next}(重启后生效)`)
|
|
380
|
+
return this.get(id)
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async restart(id) {
|
|
384
|
+
await this.stop(id)
|
|
385
|
+
return this.start(id)
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async destroy(id) {
|
|
389
|
+
if (!isValidLabId(id)) throw new Error(`非法 id:${id}`)
|
|
390
|
+
await this.stop(id)
|
|
391
|
+
const paths = labPaths(this.#root, id)
|
|
392
|
+
if (!paths.dir.startsWith(join(this.#root, 'labs'))) throw new Error('拒绝删除:路径越界')
|
|
393
|
+
try {
|
|
394
|
+
await rm(paths.dir, { recursive: true, force: true })
|
|
395
|
+
} catch (err) {
|
|
396
|
+
this.#rt.pushLog(id, 'rig', `删目录失败:${err?.message ?? err}`)
|
|
397
|
+
}
|
|
398
|
+
this.#ui.close(id)
|
|
399
|
+
removeLab(this.#state, id)
|
|
400
|
+
this.#rt.drop(id)
|
|
401
|
+
await this.#save()
|
|
402
|
+
this.#rt.emit({ type: 'labs', at: new Date().toISOString() })
|
|
403
|
+
return { id, destroyed: true }
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** 插件卸载 / 宿主退出:把还活着的实验室全停掉,不留孤儿。 */
|
|
407
|
+
async disposeAll() {
|
|
408
|
+
this.#disposed = true
|
|
409
|
+
for (const id of this.#rt.liveIds()) {
|
|
410
|
+
try {
|
|
411
|
+
await this.stop(id)
|
|
412
|
+
} catch {
|
|
413
|
+
/* 收工阶段不抛 */
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
await this.#ui.closeAll()
|
|
417
|
+
this.#rt.dispose()
|
|
418
|
+
}
|
|
419
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 界面驱动后端:CDP(系统浏览器)
|
|
3
|
+
*
|
|
4
|
+
* 零 npm 依赖的实现:用本机已装的 Edge/Chrome,`--headless=new` 起一个无头实例,
|
|
5
|
+
* 通过 DevTools 协议(Node 24 自带全局 WebSocket)驱动。
|
|
6
|
+
*
|
|
7
|
+
* 它只是**兜底后端**:本机不保证有浏览器,所以上层(driver.js)会先试 Playwright,
|
|
8
|
+
* 找不到才退到这里,两者都没有就明确告诉用户缺什么。
|
|
9
|
+
*/
|
|
10
|
+
import { mkdir, writeFile } from 'node:fs/promises'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { findBrowserExecutable, launchBrowser } from '../browser.js'
|
|
13
|
+
|
|
14
|
+
const INTERACTIVE =
|
|
15
|
+
'button,[role="button"],a,[role="menuitem"],[role="tab"],[role="treeitem"],input,textarea,[contenteditable="true"]'
|
|
16
|
+
|
|
17
|
+
/** 生成「按文字找元素」的注入脚本。参数走 JSON.stringify,不拼字符串。 */
|
|
18
|
+
function findElementScript(text) {
|
|
19
|
+
return `(() => {
|
|
20
|
+
const want = ${JSON.stringify(String(text ?? ''))}.trim().toLowerCase();
|
|
21
|
+
const nodes = [...document.querySelectorAll(${JSON.stringify(INTERACTIVE)})].filter((el) => {
|
|
22
|
+
const r = el.getBoundingClientRect();
|
|
23
|
+
if (r.width < 2 || r.height < 2) return false;
|
|
24
|
+
const st = getComputedStyle(el);
|
|
25
|
+
return st.visibility !== 'hidden' && st.display !== 'none' && Number(st.opacity) > 0.05;
|
|
26
|
+
});
|
|
27
|
+
const labelOf = (el) =>
|
|
28
|
+
(el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder') || '')
|
|
29
|
+
.replace(/\\s+/g, ' ').trim();
|
|
30
|
+
const hit = nodes.find((el) => labelOf(el).toLowerCase().includes(want));
|
|
31
|
+
if (!hit) {
|
|
32
|
+
const candidates = [...new Set(nodes.map(labelOf).filter(Boolean))].slice(0, 20);
|
|
33
|
+
return { ok: false, reason: 'not-found', candidates };
|
|
34
|
+
}
|
|
35
|
+
const r = hit.getBoundingClientRect();
|
|
36
|
+
return { ok: true, x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2), label: labelOf(hit).slice(0, 60) };
|
|
37
|
+
})()`
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const FIND_COMPOSER = `(() => {
|
|
41
|
+
const nodes = [...document.querySelectorAll('textarea,[contenteditable="true"],input[type="text"]')].filter((el) => {
|
|
42
|
+
const r = el.getBoundingClientRect();
|
|
43
|
+
return r.width > 40 && r.height > 16 && getComputedStyle(el).visibility !== 'hidden';
|
|
44
|
+
});
|
|
45
|
+
if (!nodes.length) return { ok: false };
|
|
46
|
+
nodes.sort((a, b) => b.getBoundingClientRect().height - a.getBoundingClientRect().height);
|
|
47
|
+
const el = nodes[0];
|
|
48
|
+
const r = el.getBoundingClientRect();
|
|
49
|
+
return { ok: true, x: Math.round(r.x + Math.min(40, r.width / 2)), y: Math.round(r.y + r.height / 2), tag: el.tagName.toLowerCase() };
|
|
50
|
+
})()`
|
|
51
|
+
|
|
52
|
+
export class CdpDriver {
|
|
53
|
+
name = 'cdp'
|
|
54
|
+
#labUrl
|
|
55
|
+
#userDataDir
|
|
56
|
+
#shotsDir
|
|
57
|
+
#log
|
|
58
|
+
#browserPath
|
|
59
|
+
#handle = null
|
|
60
|
+
#shotSeq = 0
|
|
61
|
+
|
|
62
|
+
constructor({ labUrl, userDataDir, shotsDir, log, browserPath }) {
|
|
63
|
+
this.#labUrl = labUrl
|
|
64
|
+
this.#userDataDir = userDataDir
|
|
65
|
+
this.#shotsDir = shotsDir
|
|
66
|
+
this.#log = typeof log === 'function' ? log : () => {}
|
|
67
|
+
this.#browserPath = browserPath || findBrowserExecutable()
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 这个后端能不能用:只看有没有浏览器可执行文件。 */
|
|
71
|
+
get available() {
|
|
72
|
+
return Boolean(this.#browserPath)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
get unavailableReason() {
|
|
76
|
+
return this.available ? null : '本机没有 Edge/Chrome(可用 DSH_RIG_BROWSER 指定,或安装 playwright)'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async #ensure() {
|
|
80
|
+
if (this.#handle) return this.#handle
|
|
81
|
+
if (!this.#browserPath) throw new Error(this.unavailableReason)
|
|
82
|
+
this.#log(`启动无头浏览器:${this.#browserPath}`)
|
|
83
|
+
this.#handle = await launchBrowser({ browserPath: this.#browserPath, labUrl: this.#labUrl, userDataDir: this.#userDataDir })
|
|
84
|
+
await this.#waitReady(this.#handle)
|
|
85
|
+
return this.#handle
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 等页面真的可用,而不是睡一个固定时长。
|
|
90
|
+
*
|
|
91
|
+
* 2026-11-21 实测:固定等 800ms 时,第一次 snapshot 在冷启动下返回 **0 个元素**,
|
|
92
|
+
* 调用方会以为「这个界面没有可点的东西」。判据改成:readyState=complete **且**
|
|
93
|
+
* 至少有一个可交互元素(DSH 的首屏是异步渲染的,DOM ready 时按钮可能还没出来)。
|
|
94
|
+
*/
|
|
95
|
+
async #waitReady(handle, timeoutMs = 20_000) {
|
|
96
|
+
const deadline = Date.now() + timeoutMs
|
|
97
|
+
const probe = `(() => ({ state: document.readyState, n: document.querySelectorAll(${INTERACTIVE}).length }))()`
|
|
98
|
+
while (Date.now() < deadline) {
|
|
99
|
+
try {
|
|
100
|
+
const res = await handle.conn.send('Runtime.evaluate', { expression: probe, returnByValue: true })
|
|
101
|
+
const value = res?.result?.value
|
|
102
|
+
if (value && value.state === 'complete' && value.n > 0) return true
|
|
103
|
+
} catch {
|
|
104
|
+
/* 页面还在切,继续等 */
|
|
105
|
+
}
|
|
106
|
+
await new Promise((r) => setTimeout(r, 300))
|
|
107
|
+
}
|
|
108
|
+
this.#log('页面在 20 秒内没有进入可交互状态,仍继续(后续动作可能失败)')
|
|
109
|
+
return false
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async evaluate(expression, { awaitPromise = false } = {}) {
|
|
113
|
+
const { conn } = await this.#ensure()
|
|
114
|
+
const result = await conn.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise })
|
|
115
|
+
if (result?.exceptionDetails) {
|
|
116
|
+
throw new Error(String(result.exceptionDetails.exception?.description || result.exceptionDetails.text || '页面脚本异常'))
|
|
117
|
+
}
|
|
118
|
+
return result?.result?.value
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async click(text) {
|
|
122
|
+
const found = await this.evaluate(findElementScript(text))
|
|
123
|
+
if (!found || found.ok !== true) {
|
|
124
|
+
const list = found && found.candidates && found.candidates.length ? `;能点的有:${found.candidates.join(' / ')}` : ''
|
|
125
|
+
throw new Error(`没找到「${text}」${list}`)
|
|
126
|
+
}
|
|
127
|
+
const { conn } = await this.#ensure()
|
|
128
|
+
await conn.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: found.x, y: found.y })
|
|
129
|
+
await conn.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: found.x, y: found.y, button: 'left', clickCount: 1 })
|
|
130
|
+
await conn.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: found.x, y: found.y, button: 'left', clickCount: 1 })
|
|
131
|
+
return { clicked: found.label, x: found.x, y: found.y }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async type(text, { submit = false } = {}) {
|
|
135
|
+
const box = await this.evaluate(FIND_COMPOSER)
|
|
136
|
+
if (!box || box.ok !== true) throw new Error('页面上找不到输入框(也许实验室还在加载)')
|
|
137
|
+
const { conn } = await this.#ensure()
|
|
138
|
+
await conn.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: box.x, y: box.y, button: 'left', clickCount: 1 })
|
|
139
|
+
await conn.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: box.x, y: box.y, button: 'left', clickCount: 1 })
|
|
140
|
+
await conn.send('Input.insertText', { text: String(text ?? '') })
|
|
141
|
+
if (submit) {
|
|
142
|
+
for (const type of ['keyDown', 'keyUp']) {
|
|
143
|
+
await conn.send('Input.dispatchKeyEvent', {
|
|
144
|
+
type,
|
|
145
|
+
key: 'Enter',
|
|
146
|
+
code: 'Enter',
|
|
147
|
+
windowsVirtualKeyCode: 13,
|
|
148
|
+
nativeVirtualKeyCode: 13,
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { typed: String(text ?? '').length, submit }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async screenshot() {
|
|
156
|
+
const { conn } = await this.#ensure()
|
|
157
|
+
const shot = await conn.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false })
|
|
158
|
+
if (!shot?.data) throw new Error('截图失败(没有数据)')
|
|
159
|
+
await mkdir(this.#shotsDir, { recursive: true })
|
|
160
|
+
this.#shotSeq += 1
|
|
161
|
+
const file = join(this.#shotsDir, `${Date.now()}-${this.#shotSeq}.png`)
|
|
162
|
+
await writeFile(file, Buffer.from(shot.data, 'base64'))
|
|
163
|
+
return { path: file, bytes: Math.round((shot.data.length * 3) / 4) }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async snapshot(limit = 40) {
|
|
167
|
+
const raw = await this.evaluate(`(() => {
|
|
168
|
+
const nodes = [...document.querySelectorAll(${JSON.stringify(INTERACTIVE)})];
|
|
169
|
+
const out = [];
|
|
170
|
+
for (const el of nodes) {
|
|
171
|
+
const r = el.getBoundingClientRect();
|
|
172
|
+
if (r.width < 2 || r.height < 2) continue;
|
|
173
|
+
const st = getComputedStyle(el);
|
|
174
|
+
if (st.visibility === 'hidden' || st.display === 'none' || Number(st.opacity) <= 0.05) continue;
|
|
175
|
+
const name = (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('placeholder') || '').replace(/\\s+/g, ' ').trim();
|
|
176
|
+
if (!name) continue;
|
|
177
|
+
out.push((el.getAttribute('role') || el.tagName.toLowerCase()) + ': ' + name.slice(0, 60));
|
|
178
|
+
}
|
|
179
|
+
return [...new Set(out)];
|
|
180
|
+
})()`)
|
|
181
|
+
const list = Array.isArray(raw) ? raw : []
|
|
182
|
+
return { total: list.length, items: list.slice(0, limit), backend: this.name }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async close() {
|
|
186
|
+
const handle = this.#handle
|
|
187
|
+
this.#handle = null
|
|
188
|
+
if (handle) handle.kill()
|
|
189
|
+
}
|
|
190
|
+
}
|