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,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 界面驱动门面(IO 层)
|
|
3
|
+
*
|
|
4
|
+
* 只做一件事:**按可用性挑一个后端**,然后交出统一的五个动作。
|
|
5
|
+
*
|
|
6
|
+
* 选择顺序(配置 `uiBackend` 可强制):
|
|
7
|
+
* 1. `playwright` —— 自带浏览器,不假设用户装了 Edge/Chrome。**可选依赖**:没装就跳过。
|
|
8
|
+
* 2. `cdp` —— 用本机 Edge/Chrome,零下载。找不到就说明没有可用后端。
|
|
9
|
+
*
|
|
10
|
+
* 为什么不当场把 Chromium 打进包里:几百 MB + postinstall 下载,属于「为了一个可选能力
|
|
11
|
+
* 让所有用户付账」,也踩供应链审查的红线。插件只声明它是 optional peer。
|
|
12
|
+
*/
|
|
13
|
+
import { probePlaywright, PlaywrightDriver } from './ui/playwright-impl.js'
|
|
14
|
+
import { CdpDriver } from './ui/cdp-impl.js'
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @returns {Promise<{driver: object|null, backend: string, reason: string|null}>}
|
|
18
|
+
*/
|
|
19
|
+
export async function createDriver({ labUrl, userDataDir, shotsDir, log, preference = 'auto', browserPath }) {
|
|
20
|
+
const pref = String(preference || 'auto')
|
|
21
|
+
let playwrightReason = '未尝试'
|
|
22
|
+
|
|
23
|
+
if (pref !== 'cdp') {
|
|
24
|
+
const probe = await probePlaywright()
|
|
25
|
+
if (probe.ok) {
|
|
26
|
+
return {
|
|
27
|
+
driver: new PlaywrightDriver({ labUrl, shotsDir, log, mode: probe.mode }),
|
|
28
|
+
backend: probe.mode === 'channel' ? 'playwright(channel)' : 'playwright',
|
|
29
|
+
reason: null,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
playwrightReason = probe.reason
|
|
33
|
+
if (pref === 'playwright') return { driver: null, backend: 'none', reason: playwrightReason }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const cdp = new CdpDriver({ labUrl, userDataDir, shotsDir, log, browserPath })
|
|
37
|
+
if (cdp.available) return { driver: cdp, backend: 'cdp', reason: null }
|
|
38
|
+
return { driver: null, backend: 'none', reason: cdp.unavailableReason || playwrightReason }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 只问「有没有得用」,不启动浏览器。给诊断与面板提示用。 */
|
|
42
|
+
export async function probeDriver({ preference = 'auto', browserPath } = {}) {
|
|
43
|
+
const pref = String(preference || 'auto')
|
|
44
|
+
if (pref !== 'cdp') {
|
|
45
|
+
const probe = await probePlaywright()
|
|
46
|
+
if (probe.ok) return { backend: probe.mode === 'channel' ? 'playwright(channel)' : 'playwright', available: true, reason: null }
|
|
47
|
+
if (pref === 'playwright') return { backend: 'none', available: false, reason: probe.reason }
|
|
48
|
+
}
|
|
49
|
+
const cdp = new CdpDriver({ labUrl: 'about:blank', userDataDir: '', shotsDir: '', log: () => {}, browserPath })
|
|
50
|
+
if (cdp.available) return { backend: 'cdp', available: true, reason: null }
|
|
51
|
+
return { backend: 'none', available: false, reason: cdp.unavailableReason }
|
|
52
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 落点布局(纯计算,无 IO)
|
|
3
|
+
*
|
|
4
|
+
* 只算路径,不 mkdir、不 stat。`node:path` 用在这里是**有意的例外**:
|
|
5
|
+
* 手写 join 在 Windows 盘符与 UNC 上太容易错,而这一层本身没有副作用,测起来只是字符串断言。
|
|
6
|
+
* 判据(隔离/命名)不在这里 —— 它们在 `naming.js`(零内建,可穷举)。
|
|
7
|
+
*/
|
|
8
|
+
import { join } from 'node:path'
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 一个实验室的全部落点。传 null/空 id 时只给根级路径。
|
|
12
|
+
* 目录层级:`<root>/labs/<id>/{home,workspace,tasks}`,版本缓存另放 `<root>/core/<ver>/`。
|
|
13
|
+
*/
|
|
14
|
+
export function labPaths(root, id) {
|
|
15
|
+
if (!root) throw new Error('labPaths: 缺少 root')
|
|
16
|
+
const base = { root, labsFile: join(root, 'labs.json'), coreDir: join(root, 'core') }
|
|
17
|
+
if (!id) return base
|
|
18
|
+
const dir = join(root, 'labs', id)
|
|
19
|
+
return {
|
|
20
|
+
...base,
|
|
21
|
+
dir,
|
|
22
|
+
home: join(dir, 'home'),
|
|
23
|
+
workspace: join(dir, 'workspace'),
|
|
24
|
+
tasks: join(dir, 'tasks'),
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 版本 core 的 bin 落点。 */
|
|
29
|
+
export function coreBinPath(root, version) {
|
|
30
|
+
return join(root, 'core', version, 'lib', 'bin.js')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 实验室根目录:默认放本机应用数据目录,绝不放进宿主 DSH_HOME 里。 */
|
|
34
|
+
export function resolveLabRoot(configRoot, env) {
|
|
35
|
+
if (typeof configRoot === 'string' && configRoot.trim() !== '') return configRoot.trim()
|
|
36
|
+
const base = env.LOCALAPPDATA || env.APPDATA || env.USERPROFILE || '.'
|
|
37
|
+
return join(base, 'dsh-rig')
|
|
38
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 日志环形缓冲(纯逻辑层)
|
|
3
|
+
*
|
|
4
|
+
* 只回答一个问题:**给定上限,新来一行之后应该留下哪些行、序号是多少**。
|
|
5
|
+
* 不持有订阅者、不认识 supervisor、不知道面板 —— 那些是上面两层的事。
|
|
6
|
+
*
|
|
7
|
+
* 为什么要单独抽:日志是唯一会被「复制出去给人看」的东西(面板复制按钮、工具回执),
|
|
8
|
+
* 它的截断与序号规则值得单独断言,而不是埋在 500 行的进程看管里。
|
|
9
|
+
*/
|
|
10
|
+
import { redactLine } from './redact.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 建一个缓冲。返回的对象是**可变**的(它就是那份状态),但所有变更都只经由两个方法。
|
|
14
|
+
*
|
|
15
|
+
* @param {number} cap 最多保留多少行
|
|
16
|
+
*/
|
|
17
|
+
export function createLogBuffer(cap) {
|
|
18
|
+
if (!Number.isInteger(cap) || cap < 1) throw new Error('createLogBuffer: cap 必须是正整数')
|
|
19
|
+
return {
|
|
20
|
+
entries: [],
|
|
21
|
+
seq: 0,
|
|
22
|
+
cap,
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* 追加一行。
|
|
28
|
+
* @returns {{seq: number, at: string, stream: string, text: string} | null} 空行返回 null(不占序号)
|
|
29
|
+
*/
|
|
30
|
+
export function appendLine(buffer, stream, rawLine, now = new Date()) {
|
|
31
|
+
const text = redactLine(rawLine).replace(/\s+$/u, '')
|
|
32
|
+
if (text === '') return null
|
|
33
|
+
buffer.seq += 1
|
|
34
|
+
const entry = { seq: buffer.seq, at: now.toISOString(), stream, text }
|
|
35
|
+
buffer.entries.push(entry)
|
|
36
|
+
if (buffer.entries.length > buffer.cap) buffer.entries.splice(0, buffer.entries.length - buffer.cap)
|
|
37
|
+
return entry
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 取序号大于 since 的那些行。 */
|
|
41
|
+
export function sliceSince(buffer, since = 0) {
|
|
42
|
+
const floor = Number(since) || 0
|
|
43
|
+
return buffer.entries.filter((entry) => entry.seq > floor)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 取最后 n 行。 */
|
|
47
|
+
export function tail(buffer, n) {
|
|
48
|
+
const count = Math.max(1, Number(n) || 1)
|
|
49
|
+
return buffer.entries.slice(-count)
|
|
50
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 命名与隔离判定(纯逻辑层)
|
|
3
|
+
*
|
|
4
|
+
* 纪律:**零 `node:` 内建、零 IO**。这一层要能被穷举断言,所以路径比较自己写字符串逻辑,
|
|
5
|
+
* 不借 `node:path`(借了就得在测试里模拟平台分隔符,反而更脆)。
|
|
6
|
+
*
|
|
7
|
+
* 唯一真相源:profile 前缀 `rig-` 只在这里出现;id 白名单只在这里判。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** 实验室 profile 的固定前缀。内置模板叫 web/desktop/headless,绝不能撞。 */
|
|
11
|
+
export const PROFILE_PREFIX = 'rig-'
|
|
12
|
+
|
|
13
|
+
/** id 白名单:小写字母数字与短横,1–24 字符,不能以短横开头。 */
|
|
14
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,23}$/u
|
|
15
|
+
|
|
16
|
+
export function isValidLabId(id) {
|
|
17
|
+
return typeof id === 'string' && ID_PATTERN.test(id)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function profileNameFor(id) {
|
|
21
|
+
return `${PROFILE_PREFIX}${id}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** 从 1 开始找一个没用过的 id(传已有 id 列表,纯函数)。 */
|
|
25
|
+
export function nextLabId(existing) {
|
|
26
|
+
const used = new Set(Array.isArray(existing) ? existing : [])
|
|
27
|
+
for (let i = 1; i <= 999; i += 1) {
|
|
28
|
+
const id = `lab${i}`
|
|
29
|
+
if (!used.has(id)) return id
|
|
30
|
+
}
|
|
31
|
+
return null
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 路径归一:统一分隔符、去尾分隔符、Windows 下转小写。
|
|
36
|
+
* 只做比较用的归一,**不是**真实路径解析(不处理 `..`、不解析符号链接)——
|
|
37
|
+
* 真正的等价判定由调用方补 realpath,这里管的是「同一处」的粗判。
|
|
38
|
+
*/
|
|
39
|
+
export function normalizeForCompare(p) {
|
|
40
|
+
if (typeof p !== 'string' || p === '') return ''
|
|
41
|
+
let s = p.replace(/[\\/]+/gu, '/').replace(/\/+$/u, '')
|
|
42
|
+
// 盘符大小写与整体大小写:Windows 文件系统不区分
|
|
43
|
+
if (/^[a-z]:/iu.test(s)) s = s.toLowerCase()
|
|
44
|
+
return s
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 隔离判定:实验室 home 与宿主 home 必须互不包含。
|
|
49
|
+
*
|
|
50
|
+
* 三个方向都要挡:相等、实验室在宿主里面、宿主在实验室里面。
|
|
51
|
+
* 这是整个项目唯一一条硬约束的**唯一**判据实现 —— 别处不许再写一份。
|
|
52
|
+
*
|
|
53
|
+
* @returns {{ok: boolean, reason?: string}}
|
|
54
|
+
*/
|
|
55
|
+
export function assertIsolated(labHome, hostHome) {
|
|
56
|
+
const a = normalizeForCompare(labHome)
|
|
57
|
+
const b = normalizeForCompare(hostHome)
|
|
58
|
+
if (a === '' || b === '') return { ok: false, reason: '路径为空,无法判定隔离' }
|
|
59
|
+
if (a === b) return { ok: false, reason: '实验室 DSH_HOME 与宿主相同' }
|
|
60
|
+
if (a.startsWith(`${b}/`)) return { ok: false, reason: '实验室 DSH_HOME 落在宿主 DSH_HOME 里面' }
|
|
61
|
+
if (b.startsWith(`${a}/`)) return { ok: false, reason: '宿主 DSH_HOME 落在实验室 DSH_HOME 里面' }
|
|
62
|
+
return { ok: true }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 从**安装路径**里读 profile 名:<home>/profiles/<name>/node_modules/<pkg>/lib/index.js。
|
|
67
|
+
*
|
|
68
|
+
* 为什么不信 DSH_PROFILE/DSH_PROFILE_DIR:从别的会话派生的进程会把这两个变量一起继承下去。
|
|
69
|
+
* 2026-11-21 实测:起着 --profile web 的实例,插件却报 desktop,因为父进程的环境被带进来了。
|
|
70
|
+
* 自己的安装位置不会说谎 —— 它就在那个 profile 的 node_modules 里。
|
|
71
|
+
*/
|
|
72
|
+
export function profileFromInstallPath(anyPath) {
|
|
73
|
+
// 先把连续分隔符折成一个:URL 形式是 /,Windows 字面量可能是 \\,直接匹配会漏。
|
|
74
|
+
const normalized = String(anyPath || '').replace(/[\\/]+/gu, '/')
|
|
75
|
+
const m = /\/profiles\/([^/]+)\//u.exec(normalized)
|
|
76
|
+
return m ? m[1] : null
|
|
77
|
+
}
|
package/lib/lab/probe.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 存活探针(IO 层)
|
|
3
|
+
*
|
|
4
|
+
* **用 `node:http`,不用 `fetch`。** 宿主进程里的全局 `fetch` 不是原生那个 ——
|
|
5
|
+
* DSH 自己接管了它(`ctx.connection` 的共享 fetch handler),拿去请求一个外部回环端口会直接失败。
|
|
6
|
+
* 2026-11-21 实测:同一个 URL,PowerShell 的 `Invoke-WebRequest` 回 200,宿主进程内 `fetch`
|
|
7
|
+
* 报 `fetch failed`,于是「实验室明明起来了」被探针连续判死 60 秒、然后被我们杀掉。
|
|
8
|
+
*
|
|
9
|
+
* 判据:**只要拿到任何 HTTP 状态码就算活着**。401(缺 token)、404(根路径变了)都证明进程在听;
|
|
10
|
+
* 进程死了由 `exit` 事件负责,不靠探针猜。
|
|
11
|
+
*/
|
|
12
|
+
import { request } from 'node:http'
|
|
13
|
+
|
|
14
|
+
export function probeOnce(url, timeoutMs = 2_000) {
|
|
15
|
+
return new Promise((resolve) => {
|
|
16
|
+
let settled = false
|
|
17
|
+
const done = (ok, reason) => {
|
|
18
|
+
if (settled) return
|
|
19
|
+
settled = true
|
|
20
|
+
resolve({ ok, reason })
|
|
21
|
+
}
|
|
22
|
+
let target
|
|
23
|
+
try {
|
|
24
|
+
target = new URL(url)
|
|
25
|
+
} catch {
|
|
26
|
+
done(false, 'URL 解析失败')
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
let req
|
|
30
|
+
try {
|
|
31
|
+
req = request(
|
|
32
|
+
{
|
|
33
|
+
hostname: target.hostname,
|
|
34
|
+
port: target.port,
|
|
35
|
+
path: `${target.pathname}${target.search}`,
|
|
36
|
+
method: 'GET',
|
|
37
|
+
timeout: timeoutMs,
|
|
38
|
+
},
|
|
39
|
+
(res) => {
|
|
40
|
+
res.resume()
|
|
41
|
+
const code = res.statusCode ?? 0
|
|
42
|
+
done(code > 0, `HTTP ${code}`)
|
|
43
|
+
},
|
|
44
|
+
)
|
|
45
|
+
} catch (err) {
|
|
46
|
+
done(false, String(err?.message ?? err))
|
|
47
|
+
return
|
|
48
|
+
}
|
|
49
|
+
req.on('timeout', () => {
|
|
50
|
+
req.destroy()
|
|
51
|
+
done(false, '超时')
|
|
52
|
+
})
|
|
53
|
+
req.on('error', (err) => done(false, String(err?.message ?? err)))
|
|
54
|
+
req.end()
|
|
55
|
+
})
|
|
56
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 子进程机制(IO 层)
|
|
3
|
+
*
|
|
4
|
+
* 只回答「怎么起、怎么读、怎么杀」这三件事,不判断谁该起、谁该杀。
|
|
5
|
+
* 和 `supervisor.js` 的分工:那边是**实验室的业务**(状态机、持久化、装配),
|
|
6
|
+
* 这边是**操作系统的机制**。分开之后,换掉终止方式(比如将来加 Job Object)
|
|
7
|
+
* 只需要动这一个文件。
|
|
8
|
+
*/
|
|
9
|
+
import { spawn, execFile } from 'node:child_process'
|
|
10
|
+
import { promisify } from 'node:util'
|
|
11
|
+
import { createInterface } from 'node:readline'
|
|
12
|
+
|
|
13
|
+
const execFileAsync = promisify(execFile)
|
|
14
|
+
|
|
15
|
+
/** 起一个后台子进程。stdio 固定:stdin 不要,标准输出/错误各一根管道。 */
|
|
16
|
+
export function spawnChild(plan) {
|
|
17
|
+
return spawn(plan.command, plan.args, {
|
|
18
|
+
cwd: plan.cwd,
|
|
19
|
+
env: plan.env,
|
|
20
|
+
windowsHide: true,
|
|
21
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 把子进程的两根输出管道都接到同一个回调(逐行,已去换行)。 */
|
|
26
|
+
export function attachLines(child, onLine) {
|
|
27
|
+
if (child.stdout) createInterface({ input: child.stdout }).on('line', (line) => onLine('out', line))
|
|
28
|
+
if (child.stderr) createInterface({ input: child.stderr }).on('line', (line) => onLine('err', line))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 杀掉整棵进程树。
|
|
33
|
+
*
|
|
34
|
+
* Windows 用 `taskkill /T`:DSH 会再派生子进程(MCP、终端、子代理),只杀父进程会留一堆孤儿。
|
|
35
|
+
* 判据是**pid 必须来自我们自己 spawn 的那棵树**,绝不按端口或名字盲杀。
|
|
36
|
+
*/
|
|
37
|
+
export async function killTree(pid, timeoutMs = 15_000) {
|
|
38
|
+
if (!pid) return
|
|
39
|
+
if (process.platform === 'win32') {
|
|
40
|
+
await execFileAsync('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, timeout: timeoutMs })
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
try {
|
|
44
|
+
process.kill(pid, 'SIGTERM')
|
|
45
|
+
} catch {
|
|
46
|
+
/* 已经没了 */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 日志脱敏(纯逻辑层)
|
|
3
|
+
*
|
|
4
|
+
* 为什么要独立成模块:脱敏是**判据**(什么算敏感、打到什么程度),
|
|
5
|
+
* 它跟「环形缓冲怎么存」、「日志怎么推给面板」是两件事。
|
|
6
|
+
* 混在一起时,改一个打码规则要去翻 500 行的看管者。
|
|
7
|
+
*
|
|
8
|
+
* 三类必打码:
|
|
9
|
+
* 1. URL 里的 token(实验室每次启动都会打一行带 token 的 URL);
|
|
10
|
+
* 2. Windows 用户目录(`C:\Users\<name>`);
|
|
11
|
+
* 3. 键值形态的 api key / secret / password。
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const TOKEN_IN_URL = /([?&]token=)[A-Za-z0-9_-]+/gu
|
|
15
|
+
const WINDOWS_USER_DIR = /([A-Za-z]:\\Users\\)[^\\/\s]+/gu
|
|
16
|
+
const SECRET_PAIR = /("?(?:api[_-]?key|apikey|token|secret|password|passwd|credential|authorization|key)"?\s*[:=]\s*")([^"]+)(")/giu
|
|
17
|
+
|
|
18
|
+
export function redactLine(line) {
|
|
19
|
+
return String(line ?? '')
|
|
20
|
+
.replace(TOKEN_IN_URL, '$1***')
|
|
21
|
+
.replace(WINDOWS_USER_DIR, '$1***')
|
|
22
|
+
.replace(SECRET_PAIR, '$1***$3')
|
|
23
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 持久状态
|
|
3
|
+
*
|
|
4
|
+
* `labs.json` 里只存**静态**字段(名字、版本、路径、profile)。端口、token、pid 一律不落盘:
|
|
5
|
+
* - 端口每次启动都会变(`--port 0` 由系统分配);
|
|
6
|
+
* - token 是每次启动现生成的,落盘等于白送一份凭据到磁盘上;
|
|
7
|
+
* - pid 落盘的价值只有「孤儿探测」,用 `startedAt` 一起存才判得准,M2 再补。
|
|
8
|
+
*
|
|
9
|
+
* 这里的函数都是纯的(不碰 fs):读写由 supervisor 负责,方便单测穷举迁移。
|
|
10
|
+
*/
|
|
11
|
+
import { STATUS } from './constants.js'
|
|
12
|
+
import { profileNameFor } from './naming.js'
|
|
13
|
+
|
|
14
|
+
const SCHEMA_VERSION = 1
|
|
15
|
+
|
|
16
|
+
/** 空状态。 */
|
|
17
|
+
export function emptyState() {
|
|
18
|
+
return { schemaVersion: SCHEMA_VERSION, labs: [] }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 解析磁盘内容:坏文件不许让插件起不来,一律降级成空状态并说明原因。 */
|
|
22
|
+
export function parseState(text) {
|
|
23
|
+
if (typeof text !== 'string' || text.trim() === '') return { state: emptyState(), problem: 'empty' }
|
|
24
|
+
let raw
|
|
25
|
+
try {
|
|
26
|
+
raw = JSON.parse(text)
|
|
27
|
+
} catch {
|
|
28
|
+
return { state: emptyState(), problem: 'invalid-json' }
|
|
29
|
+
}
|
|
30
|
+
if (!raw || typeof raw !== 'object' || raw.schemaVersion !== SCHEMA_VERSION || !Array.isArray(raw.labs)) {
|
|
31
|
+
return { state: emptyState(), problem: 'unknown-schema' }
|
|
32
|
+
}
|
|
33
|
+
const labs = raw.labs
|
|
34
|
+
.filter((lab) => lab && typeof lab.id === 'string')
|
|
35
|
+
.map((lab) => ({
|
|
36
|
+
id: lab.id,
|
|
37
|
+
name: typeof lab.name === 'string' ? lab.name : lab.id,
|
|
38
|
+
version: typeof lab.version === 'string' ? lab.version : 'host',
|
|
39
|
+
profile: typeof lab.profile === 'string' ? lab.profile : profileNameFor(lab.id),
|
|
40
|
+
createdAt: typeof lab.createdAt === 'string' ? lab.createdAt : null,
|
|
41
|
+
}))
|
|
42
|
+
return { state: { schemaVersion: SCHEMA_VERSION, labs }, problem: null }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 写盘时机用。 */
|
|
46
|
+
export function serializeState(state) {
|
|
47
|
+
return JSON.stringify({ schemaVersion: SCHEMA_VERSION, labs: state.labs }, null, 2)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function findLab(state, id) {
|
|
51
|
+
return state.labs.find((lab) => lab.id === id) || null
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 新增一个实验室(id 已存在则抛,调用方负责先查)。 */
|
|
55
|
+
export function addLab(state, lab) {
|
|
56
|
+
if (findLab(state, lab.id)) throw new Error(`实验室 ${lab.id} 已存在`)
|
|
57
|
+
state.labs.push({
|
|
58
|
+
id: lab.id,
|
|
59
|
+
name: lab.name,
|
|
60
|
+
version: lab.version,
|
|
61
|
+
profile: lab.profile,
|
|
62
|
+
createdAt: lab.createdAt || new Date().toISOString(),
|
|
63
|
+
})
|
|
64
|
+
return state
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function removeLab(state, id) {
|
|
68
|
+
state.labs = state.labs.filter((lab) => lab.id !== id)
|
|
69
|
+
return state
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 面板视图:静态字段 + 运行时快照(运行时由调用方合并)。 */
|
|
73
|
+
export function describeLab(lab, runtime) {
|
|
74
|
+
const live = runtime && typeof runtime === 'object' ? runtime : {}
|
|
75
|
+
return {
|
|
76
|
+
id: lab.id,
|
|
77
|
+
name: lab.name,
|
|
78
|
+
version: lab.version,
|
|
79
|
+
profile: lab.profile,
|
|
80
|
+
createdAt: lab.createdAt,
|
|
81
|
+
status: live.status || STATUS.created,
|
|
82
|
+
port: live.port ?? null,
|
|
83
|
+
url: live.url || null,
|
|
84
|
+
token: live.token || null,
|
|
85
|
+
pid: live.pid ?? null,
|
|
86
|
+
startedAt: live.startedAt || null,
|
|
87
|
+
exit: live.exit || null,
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-rig · 实验室体检(IO 层,只读)
|
|
3
|
+
*
|
|
4
|
+
* 为什么先做它:实验室要面对各种稀奇古怪的插件,最值钱的不是「点它」,是「看清它」。
|
|
5
|
+
* 而「看清它」大部分**不需要**实验室配合 —— profile 声明、工作区文件、启动日志里的
|
|
6
|
+
* 加载失败,全在磁盘上;进程/端口状态在宿主自己手里。
|
|
7
|
+
*
|
|
8
|
+
* 报告分四块,各自有明确的证据来源,读不到就说读不到:
|
|
9
|
+
* 1. declared —— profile 声明了哪些 bundle / 依赖(`profiles/<名>/package.json`)
|
|
10
|
+
* 2. patched —— 组合补丁里的行(`profiles/<名>/cordis.patch.yml`)
|
|
11
|
+
* 3. runtime —— 状态 / pid / 端口 / 退出码(宿主运行时表)
|
|
12
|
+
* 4. logFacts —— 启动期被禁用或加载失败的插件行(从宿主捕获的 stderr 里解析)
|
|
13
|
+
* 外加 workspace 顶层文件树。
|
|
14
|
+
*
|
|
15
|
+
* 一条纪律:**这里给出的每条都是「我看到了什么」,不是「应该是什么」**。
|
|
16
|
+
* 读失败就写 `null` 与原因,绝不编一个空数组冒充「没有」。
|
|
17
|
+
*/
|
|
18
|
+
import { readdir, readFile } from 'node:fs/promises'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
|
|
21
|
+
const DEPTH_LIMIT = 2
|
|
22
|
+
const ENTRY_LIMIT = 80
|
|
23
|
+
|
|
24
|
+
/** 读 JSON;失败返回 `{value:null, error}`,不抛。 */
|
|
25
|
+
async function readJsonSafe(file) {
|
|
26
|
+
try {
|
|
27
|
+
return { value: JSON.parse(await readFile(file, 'utf8')), error: null }
|
|
28
|
+
} catch (err) {
|
|
29
|
+
return { value: null, error: String(err?.code || err?.message || err) }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function readTextSafe(file) {
|
|
34
|
+
try {
|
|
35
|
+
return { value: await readFile(file, 'utf8'), error: null }
|
|
36
|
+
} catch (err) {
|
|
37
|
+
return { value: null, error: String(err?.code || err?.message || err) }
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 工作区顶层(最多两层)文件树,只报名字与类型。 */
|
|
42
|
+
async function listWorkspace(dir, depth = 0, prefix = '') {
|
|
43
|
+
if (depth > DEPTH_LIMIT) return []
|
|
44
|
+
let names = []
|
|
45
|
+
try {
|
|
46
|
+
names = await readdir(dir, { withFileTypes: true })
|
|
47
|
+
} catch {
|
|
48
|
+
return []
|
|
49
|
+
}
|
|
50
|
+
const out = []
|
|
51
|
+
for (const entry of names.sort((a, b) => a.name.localeCompare(b.name)).slice(0, ENTRY_LIMIT)) {
|
|
52
|
+
if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === 'browser-profile') continue
|
|
53
|
+
const rel = prefix ? `${prefix}/${entry.name}` : entry.name
|
|
54
|
+
out.push({ path: rel, dir: entry.isDirectory() })
|
|
55
|
+
if (entry.isDirectory()) out.push(...(await listWorkspace(join(dir, entry.name), depth + 1, rel)))
|
|
56
|
+
if (out.length > ENTRY_LIMIT) break
|
|
57
|
+
}
|
|
58
|
+
return out.slice(0, ENTRY_LIMIT)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 从 `cordis.patch.yml` 里抠出 `- id / name` 对(组合补丁是声明式文本,不需要全量 YAML 解析)。 */
|
|
62
|
+
export function parsePatchRows(text) {
|
|
63
|
+
if (typeof text !== 'string') return []
|
|
64
|
+
const rows = []
|
|
65
|
+
let current = null
|
|
66
|
+
for (const raw of text.split(/\r?\n/u)) {
|
|
67
|
+
const line = raw.replace(/#.*$/u, '')
|
|
68
|
+
const idMatch = /^\s*-\s*id:\s*(.+)$/u.exec(line)
|
|
69
|
+
if (idMatch) {
|
|
70
|
+
if (current) rows.push(current)
|
|
71
|
+
current = { id: idMatch[1].trim().replace(/^['"]|['"]$/gu, ''), name: null }
|
|
72
|
+
continue
|
|
73
|
+
}
|
|
74
|
+
const nameMatch = /^\s*name:\s*(.+)$/u.exec(line)
|
|
75
|
+
if (nameMatch && current && !current.name) current.name = nameMatch[1].trim().replace(/^['"]|['"]$/gu, '')
|
|
76
|
+
}
|
|
77
|
+
if (current) rows.push(current)
|
|
78
|
+
return rows
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 从宿主捕获的启动日志里解析「被禁用 / 加载失败」的插件行。 */
|
|
82
|
+
export function parseLogFacts(entries) {
|
|
83
|
+
const denied = new Map()
|
|
84
|
+
const failures = []
|
|
85
|
+
for (const entry of entries || []) {
|
|
86
|
+
const text = String(entry.text || '')
|
|
87
|
+
const denying = /disabling profile plugin row "([^"]+)":\s*(.*)$/u.exec(text)
|
|
88
|
+
if (denying) {
|
|
89
|
+
// 同 id 只留**第一条**:后出现的往往是「已禁用」的重复提示,信息量更少。
|
|
90
|
+
if (!denied.has(denying[1])) denied.set(denying[1], denying[2].slice(0, 240))
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
if (/^(Error|error):|Cannot find package|ERR_MODULE_NOT_FOUND|failed to load/u.test(text)) {
|
|
94
|
+
failures.push(text.slice(0, 240))
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return { denied: [...denied.entries()].map(([id, reason]) => ({ id, reason })), failures: failures.slice(0, 12) }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 组装一份报告。所有输入都从外面传进来,方便测试与替换。
|
|
102
|
+
*
|
|
103
|
+
* @returns {Promise<object>}
|
|
104
|
+
*/
|
|
105
|
+
export async function buildLabReport({ lab, runtime, labPaths, logEntries }) {
|
|
106
|
+
const profileDir = join(labPaths.home, 'profiles', lab.profile)
|
|
107
|
+
const pkg = await readJsonSafe(join(profileDir, 'package.json'))
|
|
108
|
+
const patch = await readTextSafe(join(profileDir, 'cordis.patch.yml'))
|
|
109
|
+
const declared = pkg.value
|
|
110
|
+
? {
|
|
111
|
+
bundles: Array.isArray(pkg.value.dsh?.profile?.bundles) ? pkg.value.dsh.profile.bundles : [],
|
|
112
|
+
dependencies: Object.keys(pkg.value.dependencies || {}),
|
|
113
|
+
error: null,
|
|
114
|
+
}
|
|
115
|
+
: { bundles: [], dependencies: [], error: pkg.error }
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
lab: { id: lab.id, name: lab.name, version: lab.version, profile: lab.profile },
|
|
119
|
+
runtime: {
|
|
120
|
+
status: runtime?.status ?? 'unknown',
|
|
121
|
+
pid: runtime?.pid ?? null,
|
|
122
|
+
port: runtime?.port ?? null,
|
|
123
|
+
startedAt: runtime?.startedAt ?? null,
|
|
124
|
+
exit: runtime?.exit ?? null,
|
|
125
|
+
},
|
|
126
|
+
declared,
|
|
127
|
+
patched: {
|
|
128
|
+
rows: patch.value ? parsePatchRows(patch.value) : [],
|
|
129
|
+
error: patch.error,
|
|
130
|
+
},
|
|
131
|
+
logFacts: parseLogFacts(logEntries),
|
|
132
|
+
workspace: await listWorkspace(labPaths.workspace),
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** 把报告压成一段给人/模型读的文本(工具回执用)。 */
|
|
137
|
+
export function renderReport(report) {
|
|
138
|
+
const lines = []
|
|
139
|
+
const { lab, runtime, declared, patched, logFacts, workspace } = report
|
|
140
|
+
lines.push(`实验室 ${lab.id}(${lab.name}) · ${runtime.status} · profile=${lab.profile}`)
|
|
141
|
+
lines.push(
|
|
142
|
+
` 进程:${runtime.pid ?? '—'} 端口 ${runtime.port ?? '—'} 退出 ${runtime.exit ? `code=${runtime.exit.code ?? 'null'}` : '—'}`,
|
|
143
|
+
)
|
|
144
|
+
lines.push(` 声明:${declared.bundles.length} 个 bundle${declared.error ? `(读不到:${declared.error})` : ''}`)
|
|
145
|
+
if (declared.bundles.length) lines.push(` ${declared.bundles.join(', ')}`)
|
|
146
|
+
lines.push(` 补丁行:${patched.rows.length} 条${patched.error ? `(读不到:${patched.error})` : ''}`)
|
|
147
|
+
if (patched.rows.length) {
|
|
148
|
+
lines.push(` ${patched.rows.slice(0, 12).map((r) => r.id).join(', ')}${patched.rows.length > 12 ? ' …' : ''}`)
|
|
149
|
+
}
|
|
150
|
+
if (logFacts.denied.length) {
|
|
151
|
+
lines.push(` 启动期被禁用:${logFacts.denied.length} 行(这些在实验室里是**没有生效**的)`)
|
|
152
|
+
for (const item of logFacts.denied.slice(0, 8)) lines.push(` ${item.id} — ${item.reason}`)
|
|
153
|
+
}
|
|
154
|
+
if (logFacts.failures.length) {
|
|
155
|
+
lines.push(` 启动期错误:${logFacts.failures.length} 条`)
|
|
156
|
+
for (const line of logFacts.failures.slice(0, 5)) lines.push(` ${line}`)
|
|
157
|
+
}
|
|
158
|
+
lines.push(` 工作区:${workspace.length} 项`)
|
|
159
|
+
for (const item of workspace.slice(0, 16)) lines.push(` ${item.dir ? '▸' : '·'} ${item.path}`)
|
|
160
|
+
if (workspace.length > 16) lines.push(` …另有 ${workspace.length - 16} 项`)
|
|
161
|
+
return lines.join('\n')
|
|
162
|
+
}
|