dsh-rig 0.1.3 → 0.1.5

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.
@@ -1,14 +1,12 @@
1
1
  /**
2
- * dsh-rig · 进程看管(IO 层 · 唯一写盘点)
2
+ * dsh-rig · 进程看管(IO 层)
3
3
  *
4
- * 只做三件事:把实验室拉起来、看着它、把它收干净。拼命令在 `spawn-plan.js`、判隔离在
5
- * `naming.js`、日志在 `log-buffer.js`、瞬时状态在 `runtime.js`、端口在 `port.js`、探针在
6
- * `probe.js`、一次性命令在 `seed.js`、界面驱动在 `ui-session.js`、版本切换在 `versioning.js`。
7
- *
8
- * 刻意不做:常驻健康轮询(只在启动阶段探到活,之后靠 `exit` 判死 —— 否则「卡住」和「在忙」
9
- * 长得一样);不持久化 token / pid(端口固定并落盘,为了 origin 稳定)。
4
+ * 只做三件事:把它拉起来、看着它、把它收干净。拼命令在 spawn-plan.js、判隔离在 naming.js、日志在 log-buffer.js、
5
+ * 瞬时状态在 runtime.js、端口在 port.js、探针在 probe.js、界面驱动在 ui-session.js、落盘与跨进程合并在 state-store.js。
6
+ * 刻意不做常驻健康轮询(「卡住」和「在忙」长得一样);不持久化 token / pid(端口固定并落盘,为了 origin 稳定)。
10
7
  */
11
- import { mkdir, readFile, writeFile, rename, rm } from 'node:fs/promises'
8
+ import { mkdir, rm } from 'node:fs/promises'
9
+ import { randomBytes } from 'node:crypto'
12
10
  import { join } from 'node:path'
13
11
  import { DEFAULTS, STATUS } from './constants.js'
14
12
  import { labPaths } from './layout.js'
@@ -21,8 +19,10 @@ import { planVersionChange } from './versioning.js'
21
19
  import { copyCredentials, runOnce } from './seed.js'
22
20
  import { attachLines, killTree, spawnChild } from './process.js'
23
21
  import { probeOnce } from './probe.js'
24
- import { addLab, describeLab, emptyState, findLab, parseState, removeLab, serializeState } from './registry.js'
22
+ import { addLab, describeLab, emptyState, findLab, removeLab } from './registry.js'
25
23
  import { createRuntimeTable } from './runtime.js'
24
+ import { LabStateStore } from './state-store.js'
25
+ import { isForeign } from './merge.js'
26
26
  import { UiSessions } from './ui-session.js'
27
27
  import { buildLabReport } from './report.js'
28
28
 
@@ -35,6 +35,8 @@ export class LabSupervisor {
35
35
  #env
36
36
  #log
37
37
  #config
38
+ #store
39
+ #hostId
38
40
  #state = emptyState()
39
41
  #rt
40
42
  #ui
@@ -50,12 +52,13 @@ export class LabSupervisor {
50
52
  this.#env = opts.env || {}
51
53
  this.#log = typeof opts.log === 'function' ? opts.log : () => {}
52
54
  this.#config = { ...DEFAULTS, ...(opts.config || {}) }
55
+ this.#store = new LabStateStore({ file: labPaths(this.#root, null).labsFile, log: (line) => this.#log(line) })
56
+ this.#hostId = randomBytes(6).toString('hex')
53
57
  this.#rt = createRuntimeTable({
54
58
  logRingLines: this.#config.logRingLines,
55
59
  log: (line) => this.#log(line),
56
60
  onEvent: opts.onEvent,
57
61
  })
58
- // 后端偏好:配置优先,其次环境变量(调试时一条 export 就能强制走 CDP)。
59
62
  const backendPreference = this.#config.uiBackend || this.#env.DSH_RIG_UI_BACKEND || 'auto'
60
63
  this.#ui = new UiSessions({ log: (line) => this.#log(line), preference: backendPreference })
61
64
  }
@@ -65,33 +68,26 @@ export class LabSupervisor {
65
68
  return this.#rt.subscribe(fn)
66
69
  }
67
70
 
68
- // ── 持久状态 ────────────────────────────────────────────────────────
71
+ /** 广播「看这个实验室」:智能体首次驱动时,面板据此自动展开右栏(不抢焦点,每个会话只展开一次)。 */
72
+ announce(id, sessionId) { this.#rt.emit({ type: 'open-lab', id, sessionId: sessionId || null }) }
73
+
74
+ // ── 持久状态(落盘与跨进程合并都在 state-store 里) ──────────────────
69
75
  async load() {
70
- const { labsFile, root } = labPaths(this.#root, null)
71
- await mkdir(root, { recursive: true })
72
- let text = ''
73
- try {
74
- text = await readFile(labsFile, 'utf8')
75
- } catch {
76
- this.#state = emptyState()
77
- return this.#state
78
- }
79
- const { state, problem } = parseState(text)
76
+ await mkdir(this.#root, { recursive: true })
77
+ const { state, problem } = await this.#store.load()
80
78
  if (problem) this.#log(`[dsh-rig] labs.json 读不出(${problem}),按空状态处理`)
81
79
  this.#state = state
82
80
  return state
83
81
  }
84
82
 
83
+ /** 落盘:锁 → 读盘 → 合并 → 写。别的宿主进程管的实验室不会被这次写抹掉。 */
85
84
  async #save() {
86
- const { labsFile } = labPaths(this.#root, null)
87
- const tmp = `${labsFile}.tmp`
88
- await writeFile(tmp, serializeState(this.#state), 'utf8')
89
- await rename(tmp, labsFile)
85
+ this.#state = await this.#store.save(this.#state)
90
86
  }
91
87
 
92
88
  // ── 读取 ────────────────────────────────────────────────────────────
93
89
  list() {
94
- return this.#state.labs.map((lab) => describeLab(lab, this.#rt.get(lab.id)))
90
+ return this.#state.labs.map((lab) => ({ ...describeLab(lab, this.#rt.get(lab.id)), foreign: isForeign(lab, this.#hostId) }))
95
91
  }
96
92
 
97
93
  get(id) {
@@ -107,30 +103,24 @@ export class LabSupervisor {
107
103
  async report(id) {
108
104
  const lab = findLab(this.#state, id)
109
105
  if (!lab) throw new Error(`没有实验室 ${id}`)
110
- const paths = labPaths(this.#root, id)
111
- return buildLabReport({
112
- lab,
113
- runtime: this.#rt.get(id),
114
- labPaths: paths,
115
- logEntries: this.#rt.logs(id, 0).entries,
116
- })
106
+ return buildLabReport({ lab, runtime: this.#rt.get(id), labPaths: labPaths(this.#root, id), logEntries: this.#rt.logs(id, 0).entries })
107
+ }
108
+
109
+ /** 对实验室记录做一次纯变更并落盘 —— 占用声明这类小改写走这里,别另开一套写盘。 */
110
+ async mutate(id, fn) {
111
+ const lab = findLab(this.#state, id)
112
+ if (!lab) throw new Error(`没有实验室 ${id}`)
113
+ const result = fn(lab)
114
+ await this.#save()
115
+ this.#rt.emit({ type: 'labs', at: new Date().toISOString() })
116
+ return result
117
117
  }
118
118
 
119
119
  diagnostics() {
120
+ const { startTimeoutMs, logRingLines, maxLabs } = this.#config
120
121
  const sample = this.#state.labs[0]
121
- return buildDiagnostics({
122
- labRoot: this.#root,
123
- hostHome: this.#hostHome,
124
- hostProfile: this.#hostProfile,
125
- isElectron: this.#isElectron,
126
- env: this.#env,
127
- limits: {
128
- startTimeoutMs: this.#config.startTimeoutMs,
129
- logRingLines: this.#config.logRingLines,
130
- maxLabs: this.#config.maxLabs,
131
- },
132
- sampleLabHome: sample ? labPaths(this.#root, sample.id).home : null,
133
- })
122
+ const sampleLabHome = sample ? labPaths(this.#root, sample.id).home : null
123
+ return buildDiagnostics({ labRoot: this.#root, hostHome: this.#hostHome, hostProfile: this.#hostProfile, isElectron: this.#isElectron, env: this.#env, limits: { startTimeoutMs, logRingLines, maxLabs }, sampleLabHome })
134
124
  }
135
125
 
136
126
  // ── 界面驱动(让智能体像人一样操作实验室) ──────────────────────────
@@ -166,6 +156,8 @@ export class LabSupervisor {
166
156
  if (this.#state.labs.length >= this.#config.maxLabs) {
167
157
  throw new Error(`最多 ${this.#config.maxLabs} 个实验室;先销毁一个`)
168
158
  }
159
+ // 先把别的宿主进程写进去的实验室合进来,再挑 id —— 否则两边可能各建一个 lab1。
160
+ this.#state = await this.#store.refresh(this.#state)
169
161
  const id = nextLabId(this.#state.labs.map((lab) => lab.id))
170
162
  if (!id) throw new Error('没有可用 id')
171
163
 
@@ -183,6 +175,7 @@ export class LabSupervisor {
183
175
  version: typeof version === 'string' ? version : 'host',
184
176
  profile: profileNameFor(id),
185
177
  port: await pickFreePort(this.#config.basePort + this.#state.labs.length), // 固定端口 = 固定 origin(见 port.js)
178
+ hostId: this.#hostId,
186
179
  createdAt: new Date().toISOString(),
187
180
  }
188
181
  this.#rt.of(id)
@@ -225,7 +218,6 @@ export class LabSupervisor {
225
218
  })
226
219
  const result = await runOnce(plan, {
227
220
  onLine: (stream, line) => {
228
- // 建 profile 的输出里,只有「被禁用的插件行」值得留给人看,其余(整份 dump)丢掉。
229
221
  if (stream === 'err' && /disabling profile plugin row|incompatible with dsh/iu.test(line)) {
230
222
  this.#rt.pushLog(lab.id, 'seed', line)
231
223
  }
@@ -247,7 +239,6 @@ export class LabSupervisor {
247
239
  await mkdir(paths.home, { recursive: true })
248
240
  await mkdir(paths.workspace, { recursive: true })
249
241
 
250
- // 端口被占了就换一个并落盘 —— 只把「确认空闲的端口」交给子进程,解析出来的端口才稳定等于这条记录。
251
242
  if (!lab.port || !(await isPortFree(lab.port))) {
252
243
  lab.port = await pickFreePort(this.#config.basePort)
253
244
  await this.#save()
@@ -328,7 +319,6 @@ export class LabSupervisor {
328
319
  this.#rt.pushLog(id, 'rig', `就绪:${rt.url.replace(/token=[^&]+/u, 'token=***')}`)
329
320
  return
330
321
  }
331
- // 只记第一次失败:探针会连失败几百次,全记会把日志刷爆。
332
322
  if (firstFailure === '') {
333
323
  firstFailure = probe.reason || 'unknown'
334
324
  this.#rt.pushLog(id, 'rig', `探针未通过(${firstFailure}),继续等…`)
@@ -11,6 +11,7 @@
11
11
  * 那时会新增 `dispatch`,而不是改现有动作的语义。
12
12
  */
13
13
  import { renderReport } from '../lab/report.js'
14
+ import { guardDrive, isDriveAction } from '../lab/drive-guard.js'
14
15
 
15
16
  const text = (s) => [{ type: 'text', text: String(s ?? '') }]
16
17
 
@@ -38,7 +39,7 @@ export function createLabTool(supervisor, versionsApi) {
38
39
  version: { type: 'string', description: 'create 时的 DSH 版本:host 表示跟随宿主' },
39
40
  since: { type: 'integer', minimum: 0, description: 'logs 的起点序号,默认 0' },
40
41
  lines: { type: 'integer', minimum: 1, maximum: 200, description: 'logs 最多返回多少行,默认 40' },
41
-
42
+ force: { type: 'boolean', description: '实验室被别人驾驶时强行接手(会中断对方正在进行的操作)' },
42
43
  },
43
44
  required: ['action'],
44
45
  additionalProperties: false,
@@ -54,9 +55,11 @@ export function createLabTool(supervisor, versionsApi) {
54
55
  },
55
56
  },
56
57
  isConcurrencySafe: () => true,
57
- async execute(args) {
58
+ async execute(args, exec) {
58
59
  const action = String(args?.action || '')
59
60
  const id = String(args?.id || '')
61
+ // 会话身份:工具是「谁在驾驶」的唯一来源(面板走 HTTP 时自带 sessionId)。
62
+ const sessionId = exec?.agent?.session?.id ? String(exec.agent.session.id) : ''
60
63
  try {
61
64
  if (!ACTIONS.includes(action)) return { ok: false, error: `未知动作 ${action}` }
62
65
  if (action === 'list') {
@@ -66,9 +69,18 @@ export function createLabTool(supervisor, versionsApi) {
66
69
  }
67
70
  if (action === 'create') {
68
71
  const lab = await supervisor.create({ name: args?.name, version: args?.version || 'host' })
72
+ if (sessionId) await supervisor.mutate(lab.id, (record) => guardDrive(record, sessionId))
73
+ supervisor.announce(lab.id, sessionId)
69
74
  return { ok: true, text: `已创建:\n${renderLab(lab)}` }
70
75
  }
71
76
  if (id === '') return { ok: false, error: '这个动作需要 id' }
77
+ // 占用:动手才 claim。别人的实验室一律拒绝,拒绝文案带上占用者 id(用户可在面板接手)。
78
+ if (isDriveAction(action)) {
79
+ const verdict = await supervisor.mutate(id, (lab) => guardDrive(lab, sessionId, { force: Boolean(args?.force) }))
80
+ // **被拒绝也要广播**:拒绝文案让人「去面板里点接手」,那就把面板打开给他看。
81
+ supervisor.announce(id, sessionId)
82
+ if (!verdict.allow) return { ok: false, error: verdict.reason }
83
+ }
72
84
  if (action === 'status') {
73
85
  const lab = supervisor.get(id)
74
86
  if (!lab) return { ok: false, error: `没有实验室 ${id}` }
@@ -121,16 +133,16 @@ export function createLabTool(supervisor, versionsApi) {
121
133
  const lab = await supervisor.setVersion(id, String(args.version))
122
134
  return { ok: true, text: `已切到 ${lab.version},重启后生效:\n${renderLab(lab)}` }
123
135
  }
124
- if (action === 'start') {
125
- const lab = await supervisor.start(id)
136
+ if (action === 'start') {
137
+ const lab = await supervisor.start(id)
126
138
  return { ok: true, text: `已启动:\n${renderLab(lab)}` }
127
139
  }
128
140
  if (action === 'stop') {
129
141
  const lab = await supervisor.stop(id)
130
142
  return { ok: true, text: `已停止:\n${renderLab(lab)}` }
131
143
  }
132
- if (action === 'restart') {
133
- const lab = await supervisor.restart(id)
144
+ if (action === 'restart') {
145
+ const lab = await supervisor.restart(id)
134
146
  return { ok: true, text: `已重启:\n${renderLab(lab)}` }
135
147
  }
136
148
  if (action === 'destroy') {
@@ -11,6 +11,8 @@
11
11
  * 它和 `plugin_lab`(生命周期)分开而不是同一个工具加 action 枚举,也是同一个理由:
12
12
  * 生命周期的 schema 要一直留着,界面操作的不要。
13
13
  */
14
+ import { guardDrive } from '../lab/drive-guard.js'
15
+
14
16
  const text = (s) => [{ type: 'text', text: String(s ?? '') }]
15
17
 
16
18
  const ACTIONS = ['snapshot', 'screenshot', 'click', 'type', 'task']
@@ -31,6 +33,7 @@ export function createLabUiTool(supervisor) {
31
33
  text: { type: 'string', description: 'click 的按钮文字 / type 与 task 的内容' },
32
34
  submit: { type: 'boolean', description: 'type 后是否敲回车,默认 false' },
33
35
  limit: { type: 'integer', minimum: 1, maximum: 120, description: 'snapshot 最多列多少条,默认 40' },
36
+ force: { type: 'boolean', description: '实验室被别人驾驶时强行接手(会中断对方正在进行的操作)' },
34
37
  },
35
38
  required: ['action', 'id'],
36
39
  additionalProperties: false,
@@ -43,12 +46,16 @@ export function createLabUiTool(supervisor) {
43
46
  return text(v.text)
44
47
  },
45
48
  },
46
- async execute(args) {
49
+ async execute(args, exec) {
47
50
  const action = String(args?.action || '')
48
51
  const id = String(args?.id || '')
52
+ const sessionId = exec?.agent?.session?.id ? String(exec.agent.session.id) : ''
49
53
  try {
50
54
  if (!ACTIONS.includes(action)) return { ok: false, error: `未知动作 ${action}(可用:${ACTIONS.join(' / ')})` }
51
55
  if (id === '') return { ok: false, error: '需要 id' }
56
+ // 界面操作也是驾驶:别人的实验室不碰(拒绝文案带占用者 id)。
57
+ const verdict = await supervisor.mutate(id, (lab) => guardDrive(lab, sessionId, { force: Boolean(args?.force) }))
58
+ if (!verdict.allow) return { ok: false, error: verdict.reason }
52
59
  const result = await supervisor.ui(id, action, {
53
60
  text: args?.text,
54
61
  submit: Boolean(args?.submit),
@@ -11,10 +11,10 @@ import { createLabUiTool } from './lab-ui-tool.js'
11
11
 
12
12
  /**
13
13
  * @param {object} tools 宿主 tools 服务(inner ctx 上的)
14
- * @param {{supervisor: object, log?: (line: string) => void}} deps
14
+ * @param {{supervisor: object, versions?: object, titleOf?: (id: string) => string, log?: (line: string) => void}} deps
15
15
  * @returns {() => void} 卸载函数(注销两个工具并退订)
16
16
  */
17
- export function mountLabTools(tools, { supervisor, versions, log }) {
17
+ export function mountLabTools(tools, { supervisor, versions, titleOf, log }) {
18
18
  const say = typeof log === 'function' ? log : () => {}
19
19
  let disposeUi = null
20
20
 
@@ -39,7 +39,7 @@ export function mountLabTools(tools, { supervisor, versions, log }) {
39
39
  }
40
40
 
41
41
  try {
42
- tools.register(createLabTool(supervisor, versions))
42
+ tools.register(createLabTool(supervisor, versions, { titleOf }))
43
43
  say('[dsh-rig] plugin_lab 工具已注册')
44
44
  } catch (err) {
45
45
  say(`[dsh-rig] plugin_lab 注册失败:${err?.message ?? err}`)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-rig",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Right-sidebar plugin lab for DeepSeek Harness: a real, process-isolated DSH you can start, restart, version-switch, lock or take over — crashes stay inside the lab.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -59,7 +59,7 @@
59
59
  "react": "^18.0.0"
60
60
  },
61
61
  "scripts": {
62
- "test": "node --test test/pure.test.mjs test/probe.test.mjs test/structure.test.mjs test/report.test.mjs test/mount.test.mjs",
62
+ "test": "node --test test/pure.test.mjs test/probe.test.mjs test/structure.test.mjs test/report.test.mjs test/mount.test.mjs test/routes.test.mjs test/merge.test.mjs test/ownership.test.mjs",
63
63
  "check:client": "node --check lib/client.js",
64
64
  "check:host": "node --check lib/index.js"
65
65
  },