dsh-rig 0.0.0 → 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.
@@ -0,0 +1,106 @@
1
+ /**
2
+ * dsh-rig · 运行时表(纯逻辑层)
3
+ *
4
+ * 每个实验室的**瞬时**状态:状态机、日志环形缓冲、事件扇出。
5
+ * 这些数据都不落盘(端口/token/pid 每次启动都变),所以和 `registry.js` 的持久状态分开。
6
+ *
7
+ * 为什么单独成模块:看管者(supervisor)要的是「把实验室拉起来、看着、收干净」,
8
+ * 而「谁在什么状态、日志留给谁、事件怎么扇出去」是另一件事 —— 它还**不需要 IO**,
9
+ * 因此可以在这里被穷举断言。
10
+ */
11
+ import { STATUS, canTransition, isLive } from './constants.js'
12
+ import { appendLine, createLogBuffer, sliceSince } from './log-buffer.js'
13
+
14
+ /**
15
+ * @param {object} p
16
+ * @param {number} p.logRingLines 每个实验室保留多少行日志
17
+ * @param {(line: string) => void} [p.log] 宿主日志(状态机违规这类内部异常)
18
+ * @param {(event: object) => void} [p.onEvent] 额外的扇出(HTTP 层不用它,工具层可能用)
19
+ */
20
+ export function createRuntimeTable({ logRingLines, log, onEvent }) {
21
+ const map = new Map()
22
+ const subs = new Set()
23
+ const warn = typeof log === 'function' ? log : () => {}
24
+ const external = typeof onEvent === 'function' ? onEvent : () => {}
25
+
26
+ function emit(event) {
27
+ try {
28
+ external(event)
29
+ } catch {
30
+ /* 外部订阅者出错不能拖垮运行时 */
31
+ }
32
+ for (const fn of subs) {
33
+ try {
34
+ fn(event)
35
+ } catch {
36
+ /* 同上 */
37
+ }
38
+ }
39
+ }
40
+
41
+ function of(id) {
42
+ let rt = map.get(id)
43
+ if (!rt) {
44
+ rt = {
45
+ status: STATUS.created,
46
+ child: null,
47
+ pid: null,
48
+ port: null,
49
+ url: null,
50
+ token: null,
51
+ startedAt: null,
52
+ exit: null,
53
+ buffer: createLogBuffer(logRingLines),
54
+ }
55
+ map.set(id, rt)
56
+ }
57
+ return rt
58
+ }
59
+
60
+ return {
61
+ of,
62
+ emit,
63
+ /** 订阅事件;返回退订函数。 */
64
+ subscribe(fn) {
65
+ subs.add(fn)
66
+ return () => subs.delete(fn)
67
+ },
68
+ /** 追加一行日志(自动脱敏、自动截断),并发一条 log 事件。 */
69
+ pushLog(id, stream, raw) {
70
+ const entry = appendLine(of(id).buffer, stream, raw)
71
+ if (entry) emit({ type: 'log', id, entry })
72
+ return entry
73
+ },
74
+ /** 迁移状态。非法迁移**只记一笔不改**:被绕过的状态机必须看得见。 */
75
+ setStatus(id, next, extra = {}) {
76
+ const rt = of(id)
77
+ const from = rt.status
78
+ if (from === next) return
79
+ if (!canTransition(from, next)) {
80
+ warn(`[dsh-rig] 非法状态迁移 ${from} → ${next} (${id})`)
81
+ return
82
+ }
83
+ rt.status = next
84
+ Object.assign(rt, extra)
85
+ emit({ type: 'status', id, status: next, at: new Date().toISOString() })
86
+ },
87
+ logs(id, since = 0) {
88
+ const rt = map.get(id)
89
+ if (!rt) return { entries: [], seq: 0 }
90
+ return { entries: sliceSince(rt.buffer, since), seq: rt.buffer.seq }
91
+ },
92
+ get(id) {
93
+ return map.get(id)
94
+ },
95
+ drop(id) {
96
+ map.delete(id)
97
+ },
98
+ /** 还活着的实验室 id(收工时按这个清单停)。 */
99
+ liveIds() {
100
+ return [...map.entries()].filter(([, rt]) => isLive(rt.status)).map(([id]) => id)
101
+ },
102
+ dispose() {
103
+ subs.clear()
104
+ },
105
+ }
106
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * dsh-rig · 一次性子进程与凭据复制(IO 层)
3
+ *
4
+ * 两件「跑一次就完事」的事都在这儿:
5
+ * 1. 建 profile(`--from-default-profile web --dump-config`,只算不建、不起服务);
6
+ * 2. 把宿主凭据复制进实验室 home。
7
+ *
8
+ * 为什么和 `supervisor.js` 分开:看管者管的是「持续活着的进程」(spawn/kill/探活/日志),
9
+ * 这里管的是「跑一次、等它退出的命令」。两者混在一起时,看管者会为了一个一次性动作长出一堆分支。
10
+ */
11
+ import { spawn } from 'node:child_process'
12
+ import { copyFile } from 'node:fs/promises'
13
+ import { createInterface } from 'node:readline'
14
+ import { join } from 'node:path'
15
+
16
+ /** 建 profile 的默认超时。只算不建,正常几秒内就退。 */
17
+ const SEED_TIMEOUT_MS = 90_000
18
+
19
+ /**
20
+ * 跑一个一次性子进程,逐行回调 stdout/stderr,等它退出。
21
+ * **不抛**:失败只是「日志里多一行」,由调用方决定要不要中止。
22
+ *
23
+ * @returns {Promise<{code: number|null, timedOut: boolean}>}
24
+ */
25
+ export function runOnce(plan, { onLine, timeoutMs = SEED_TIMEOUT_MS } = {}) {
26
+ return new Promise((resolve) => {
27
+ let child
28
+ try {
29
+ child = spawn(plan.command, plan.args, { cwd: plan.cwd, env: plan.env, windowsHide: true })
30
+ } catch (err) {
31
+ onLine?.('rig', `启动失败:${err?.message ?? err}`)
32
+ resolve({ code: null, timedOut: false, error: String(err?.message ?? err) })
33
+ return
34
+ }
35
+ let settled = false
36
+ const finish = (value) => {
37
+ if (settled) return
38
+ settled = true
39
+ resolve(value)
40
+ }
41
+ const timer = setTimeout(() => {
42
+ onLine?.('rig', `超时(${Math.round(timeoutMs / 1000)}s),已终止`)
43
+ try {
44
+ child.kill()
45
+ } catch {
46
+ /* ignore */
47
+ }
48
+ finish({ code: null, timedOut: true })
49
+ }, timeoutMs)
50
+
51
+ if (child.stdout) createInterface({ input: child.stdout }).on('line', (line) => onLine?.('out', line))
52
+ if (child.stderr) createInterface({ input: child.stderr }).on('line', (line) => onLine?.('err', line))
53
+ child.on('error', (err) => {
54
+ clearTimeout(timer)
55
+ onLine?.('rig', `子进程错误:${err?.message ?? err}`)
56
+ finish({ code: null, timedOut: false, error: String(err?.message ?? err) })
57
+ })
58
+ child.on('exit', (code) => {
59
+ clearTimeout(timer)
60
+ finish({ code: code ?? null, timedOut: false })
61
+ })
62
+ })
63
+ }
64
+
65
+ /**
66
+ * 宿主凭据 → 实验室 home。
67
+ *
68
+ * 为什么走文件不走环境变量:环境变量会被子进程里的任何东西读走(包括实验室里正在开发的插件),
69
+ * 而 DSH 自己就是从 `<DSH_HOME>/.credentials.yaml` 取的。显式、可关、可清除。
70
+ *
71
+ * @returns {Promise<boolean>} 复制成功与否(不抛)
72
+ */
73
+ export async function copyCredentials({ fromHome, toHome }) {
74
+ try {
75
+ await copyFile(join(fromHome, '.credentials.yaml'), join(toHome, '.credentials.yaml'))
76
+ return true
77
+ } catch {
78
+ return false
79
+ }
80
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * dsh-rig · 子进程启动参数
3
+ *
4
+ * 纯函数:给什么算什么,不读环境、不碰磁盘。好处是「不继承凭据」这条能被单测钉死。
5
+ *
6
+ * 两条硬约束:
7
+ * 1. **env 白名单**,不整份继承。任何 `*_KEY` / `*_TOKEN` / `*_SECRET` / `*_PASSWORD`
8
+ * 一律不进实验室 —— 实验室里的智能体是「可能不稳定」的东西,不该顺手拿到宿主的凭据。
9
+ * 实验室需要的模型凭据走**文件通道**(宿主的 `.credentials.yaml` → 实验室 home),
10
+ * 那是显式的、用户可关的,不是偷偷塞环境变量。
11
+ * 2. **桌面版是 Electron**:`process.execPath` 指向 Electron 本体,必须带
12
+ * `ELECTRON_RUN_AS_NODE=1` 才会当 node 用(官方 locate-docs 里同一个手法)。
13
+ */
14
+
15
+ /** 允许继承的环境变量名(大小写不敏感匹配)。 */
16
+ const ENV_ALLOW = [
17
+ 'PATH',
18
+ 'PATHEXT',
19
+ 'COMSPEC',
20
+ 'SYSTEMROOT',
21
+ 'SYSTEMDRIVE',
22
+ 'WINDIR',
23
+ 'TEMP',
24
+ 'TMP',
25
+ 'HOME',
26
+ 'USERPROFILE',
27
+ 'APPDATA',
28
+ 'LOCALAPPDATA',
29
+ 'PROGRAMDATA',
30
+ 'PROGRAMFILES',
31
+ 'PROGRAMFILES(X86)',
32
+ 'NUMBER_OF_PROCESSORS',
33
+ 'PROCESSOR_ARCHITECTURE',
34
+ 'OS',
35
+ 'LANG',
36
+ 'LC_ALL',
37
+ 'TZ',
38
+ ]
39
+
40
+ /** 出现这些片段的变量一律丢弃(白名单之外再兜一层)。 */
41
+ const ENV_DENY = /(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|_AUTH)/iu
42
+
43
+ /**
44
+ * 从宿主 env 里挑出实验室该有的那几项。
45
+ * @param {Record<string, string|undefined>} source
46
+ * @param {Record<string, string>} extra 额外注入(DSH_HOME 等)
47
+ */
48
+ export function sanitizeEnv(source, extra = {}) {
49
+ const allow = new Set(ENV_ALLOW)
50
+ const out = {}
51
+ for (const [name, value] of Object.entries(source || {})) {
52
+ if (typeof value !== 'string') continue
53
+ const upper = name.toUpperCase()
54
+ if (ENV_DENY.test(upper)) continue
55
+ if (!allow.has(upper)) continue
56
+ out[name] = value
57
+ }
58
+ for (const [name, value] of Object.entries(extra)) {
59
+ if (typeof value === 'string') out[name] = value
60
+ }
61
+ return out
62
+ }
63
+
64
+ /**
65
+ * 组装一次启动计划。
66
+ *
67
+ * @param {object} p
68
+ * @param {string} p.execPath 宿主进程的可执行文件(Electron 或 node)
69
+ * @param {boolean} p.isElectron process.versions.electron 是否为真
70
+ * @param {string} p.coreBin DSH 的 lib/bin.js 绝对路径
71
+ * @param {string} p.profile profile 名(rig-<id>)
72
+ * @param {string} p.cwd 实验室工作区
73
+ * @param {string} p.home 实验室 DSH_HOME
74
+ * @param {Record<string,string|undefined>} p.env 宿主 env
75
+ * @param {string} [p.version] 记入日志用,不进 argv
76
+ */
77
+ export function buildStartPlan({ execPath, isElectron, coreBin, profile, cwd, home, env }) {
78
+ if (!execPath) throw new Error('buildStartPlan: 缺少 execPath')
79
+ if (!coreBin) throw new Error('buildStartPlan: 缺少 coreBin')
80
+ if (!profile) throw new Error('buildStartPlan: 缺少 profile')
81
+
82
+ // ⚠️ 不能写 `web` 子命令:`dsh web` 本身就是 `--profile web` 的别名,
83
+ // 再叠一个 `--profile rig-xxx` 会被 CLI 判成「select a profile only once」并直接退出
84
+ // (2026-11-21 实测:exit 1,面板显示「已崩溃」)。
85
+ // 自定义 profile 的正确起法是只给 --profile,web 服务由 profile 模板决定。
86
+ const args = [coreBin, '--profile', profile, '--port', '0', '--no-open', '--host', '127.0.0.1']
87
+ const extra = {
88
+ DSH_HOME: home,
89
+ DSH_TELEMETRY_DISABLED: '1',
90
+ }
91
+ if (isElectron) extra.ELECTRON_RUN_AS_NODE = '1'
92
+
93
+ return {
94
+ command: execPath,
95
+ args,
96
+ cwd,
97
+ env: sanitizeEnv(env, extra),
98
+ }
99
+ }
100
+
101
+ /** 建 profile 的计划(只在第一次创建实验室时跑一次)。 */
102
+ export function buildSeedPlan({ execPath, isElectron, coreBin, profile, cwd, home, env, fromProfile = 'web' }) {
103
+ const args = [coreBin, '--profile', profile, '--from-default-profile', fromProfile, '--dump-config']
104
+ const extra = { DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1' }
105
+ if (isElectron) extra.ELECTRON_RUN_AS_NODE = '1'
106
+ return { command: execPath, args, cwd, env: sanitizeEnv(env, extra) }
107
+ }
108
+
109
+ /** 从实验室 stdout 里抓 URL 与 token。抓不到返回 null,由调用方走兜底。 */
110
+ export function parseLabUrl(line) {
111
+ const m = /http:\/\/127\.0\.0\.1:(\d+)\/\?token=([A-Za-z0-9_-]+)/u.exec(String(line || ''))
112
+ if (!m) return null
113
+ return { port: Number(m[1]), token: m[2], url: m[0] }
114
+ }