dsh-rig 0.1.5 → 0.2.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,415 @@
1
+ /**
2
+ * dsh-rig-mirror · 宿主半(跑在**实验室**那个 DSH 实例里,往外推帧、接收输入)
3
+ *
4
+ * 方向固定为「插件当客户端」:实验室主动连宿主,理由是宿主不该反向连进实验室——
5
+ * 实验室的端口每次重启都换,而宿主的地址由实验室启动参数给定,一次写好就稳定。
6
+ *
7
+ * ── 通道(二选一,已选 WebSocket)─────────────────────────────────────────────
8
+ * 用 **Node 内建的全局 `WebSocket`**(undici,Node ≥ 22 自带;本机宿主运行时实测
9
+ * `runtime/versions.json` = node 24.21.0,`typeof WebSocket === 'function'`)。零依赖:
10
+ * 不 import `node:` 内建,也不 import `ws`。另外两条路不选:手写 `node:http` upgrade
11
+ * 客户端要自己算 Sec-WebSocket-Key、逐帧掩码、拼帧头、处理分片与 ping/pong;HTTP POST
12
+ * 分片推帧每帧一次请求 + chunked 头,输入还得另开长轮询,帧率 5/s 时开销比帧本身还大。
13
+ *
14
+ * ── 一条必须在 README 里写清的边界(骨架期实测)────────────────────────────────
15
+ * 正式版 DSH 桌面**不是**「插件跑在 Electron 主进程」:主进程 `resources/app/lib/main.js`
16
+ * 只做壳,它 spawn 一个**纯 Node** 宿主进程(`@deepseek-ai/dsh-desktop-host`)来装 DSH
17
+ * 与插件。于是插件里 `process.versions.electron` 是 undefined,`webContents` 拿不到 ——
18
+ * `capturePage()` 只有本模块跑在 Electron 进程里时才成立。下面把它实现完整,**拿不到时
19
+ * 明确说出来**,不假装能推帧。接法(CDP / 桌面壳桥)在 README「还没做什么」里。
20
+ */
21
+ import {
22
+ DEFAULT_BACKOFF_MS,
23
+ DEFAULT_INTERVAL_MS,
24
+ FRAME_MIME,
25
+ JPEG_QUALITY,
26
+ MAX_BUFFERED_BYTES,
27
+ MAX_EDGE,
28
+ PROTOCOL_VERSION,
29
+ decodeMessage,
30
+ encodeMessage,
31
+ fitWithin,
32
+ mirrorUrl,
33
+ normalizeInput,
34
+ validateFrame,
35
+ } from '../contract.js'
36
+
37
+ export const name = 'dsh-rig-mirror'
38
+
39
+ /** 三级验证的第三级看这行(宿主启动日志里出现即说明插件真的被 apply 了)。 */
40
+ export const MIRROR_STAGE = 'skeleton-1'
41
+
42
+ const OPEN = 1
43
+ const STATS_EVERY_MS = 60_000
44
+
45
+ const log = (line) => console.log(`[dsh-rig-mirror] ${line}`)
46
+
47
+ /**
48
+ * 从 config / 环境变量里算出要连的地址。
49
+ * 优先整条 `mirrorUrl`;否则用 `hostPort` + `labId` 现拼(宿主端口在实验室启动时才知道)。
50
+ * 两样都没有就返回 null —— 插件待机,不报错(骨架装进任何 profile 都不该炸)。
51
+ */
52
+ export function resolveTarget(config = {}, env = {}) {
53
+ const direct = config.mirrorUrl || env.DSH_RIG_MIRROR_URL || ''
54
+ const token = String(config.token || env.DSH_RIG_MIRROR_TOKEN || '')
55
+ if (direct) return { url: String(direct), labId: String(config.labId || env.DSH_RIG_LAB_ID || '') }
56
+ const port = Number(config.hostPort || env.DSH_RIG_MIRROR_PORT || 0)
57
+ const labId = String(config.labId || env.DSH_RIG_LAB_ID || '').trim()
58
+ if (!Number.isInteger(port) || port <= 0 || labId === '') return null
59
+ return { url: mirrorUrl(`http://127.0.0.1:${port}`, labId, token), labId }
60
+ }
61
+
62
+ /**
63
+ * 输入帧 → Electron `sendInputEvent` 的事件序列。纯函数,不碰 Electron,能单独测。
64
+ * 一次 click 展开成 down+up 两条:Electron 没有「合成点击」这个事件类型。
65
+ */
66
+ export function toElectronInputEvents(input) {
67
+ if (input.type === 'key') {
68
+ const type = input.action === 'char' ? 'char' : input.action === 'up' ? 'keyUp' : 'keyDown'
69
+ const event = { type, keyCode: input.key }
70
+ for (const modifier of input.modifiers ?? []) event[modifier] = true
71
+ return [event]
72
+ }
73
+ if (input.type === 'wheel') {
74
+ return [{ type: 'mouseWheel', x: input.x, y: input.y, deltaX: input.deltaX ?? 0, deltaY: input.delta ?? 0 }]
75
+ }
76
+ const press = { x: input.x, y: input.y, button: input.button, clickCount: input.clickCount }
77
+ if (input.action === 'move') return [{ type: 'mouseMove', x: input.x, y: input.y }]
78
+ if (input.action === 'down') return [{ type: 'mouseDown', ...press }]
79
+ if (input.action === 'up') return [{ type: 'mouseUp', ...press }]
80
+ return [{ type: 'mouseDown', ...press }, { type: 'mouseUp', ...press }]
81
+ }
82
+
83
+ /**
84
+ * 解析屏幕来源。只有 Electron 进程里可能成功(见文件头),失败返回 `{ ok: false, reason }`。
85
+ */
86
+ async function createElectronSurface({ maxEdge = MAX_EDGE, quality = JPEG_QUALITY } = {}) {
87
+ if (!process.versions.electron) {
88
+ return { ok: false, reason: 'process.versions.electron 缺失:本进程是纯 Node 宿主,不是 Electron' }
89
+ }
90
+ let electron
91
+ try {
92
+ electron = await import('electron')
93
+ } catch (error) {
94
+ return { ok: false, reason: `import('electron') 失败:${error?.message ?? error}` }
95
+ }
96
+ const manager = electron?.webContents
97
+ if (typeof manager?.getAllWebContents !== 'function') return { ok: false, reason: 'electron.webContents 不可用' }
98
+ const page = manager
99
+ .getAllWebContents()
100
+ .find((item) => item.getType?.() === 'window' && item.isDestroyed?.() !== true)
101
+ if (!page) return { ok: false, reason: '没有可截图的窗口 webContents(窗口可能还没建)' }
102
+
103
+ const isVisible = () => {
104
+ if (page.isDestroyed?.()) return false
105
+ const window = typeof page.getOwnerBrowserWindow === 'function' ? page.getOwnerBrowserWindow() : null
106
+ if (!window) return true
107
+ if (window.isMinimized?.()) return false
108
+ if (typeof window.isVisible === 'function' && !window.isVisible()) return false
109
+ return true
110
+ }
111
+
112
+ const capture = async () => {
113
+ if (page.isDestroyed?.()) return null
114
+ const image = await page.capturePage()
115
+ if (!image || image.isEmpty?.()) return null
116
+ const size = image.getSize()
117
+ const fit = fitWithin(size.width, size.height, maxEdge)
118
+ const scaled =
119
+ fit.w === size.width && fit.h === size.height
120
+ ? image
121
+ : image.resize({ width: fit.w, height: fit.h, quality: 'good' })
122
+ return { bytes: scaled.toJPEG(quality), w: fit.w, h: fit.h }
123
+ }
124
+
125
+ const sendInput = (input) => {
126
+ if (page.isDestroyed?.()) return false
127
+ for (const event of toElectronInputEvents(input)) page.sendInputEvent(event)
128
+ return true
129
+ }
130
+
131
+ return { ok: true, kind: 'electron', capture, sendInput, isVisible }
132
+ }
133
+
134
+ /** 一次镜像会话:连接、推帧、收输入、重连、暂停、销毁。 */
135
+ class MirrorSession {
136
+ constructor({ target, config = {} }) {
137
+ this.target = target
138
+ this.config = config
139
+ this.surface = null
140
+ this.socket = null
141
+ this.timer = null
142
+ this.reconnectTimer = null
143
+ this.statsTimer = null
144
+ this.backoffIndex = 0
145
+ this.seq = 0
146
+ this.capturing = false
147
+ this.pending = null
148
+ this.paused = false
149
+ this.disposed = false
150
+ this.stats = { sent: 0, dropped: 0, inputs: 0, reconnects: 0, errors: 0 }
151
+ this.intervalMs = Math.max(50, Number(config.intervalMs) || DEFAULT_INTERVAL_MS)
152
+ this.backoff = Array.isArray(config.backoffMs) && config.backoffMs.length > 0 ? config.backoffMs : DEFAULT_BACKOFF_MS
153
+ }
154
+
155
+ async start() {
156
+ const options = { maxEdge: Number(this.config.maxEdge) || MAX_EDGE, quality: Number(this.config.quality) || JPEG_QUALITY }
157
+ // config.surface 是留好的接缝:接 CDP 适配器或测试替身,形状同 createElectronSurface 的返回值。
158
+ this.surface = typeof this.config.surface === 'function' ? await this.config.surface(options) : await createElectronSurface(options)
159
+ // 帧源不可用时也照连:让宿主看见「插件在、通道通、只是没有帧源」,比静默好排查。
160
+ if (!this.surface.ok) log(`帧源不可用:${this.surface.reason}`)
161
+ if (this.disposed) return
162
+ this.connect()
163
+ this.statsTimer = setInterval(() => this.report(), STATS_EVERY_MS)
164
+ this.statsTimer?.unref?.()
165
+ }
166
+
167
+ connect() {
168
+ if (this.disposed) return
169
+ const Impl = this.config.webSocket ?? globalThis.WebSocket
170
+ if (typeof Impl !== 'function') {
171
+ log('本运行时没有全局 WebSocket(需要 Node ≥ 22);不装依赖、不推帧,插件待机')
172
+ return
173
+ }
174
+ let socket
175
+ try {
176
+ socket = new Impl(this.target.url)
177
+ } catch (error) {
178
+ log(`建立连接失败:${error?.message ?? error}`)
179
+ this.scheduleReconnect()
180
+ return
181
+ }
182
+ this.socket = socket
183
+ if ('binaryType' in socket) socket.binaryType = 'arraybuffer'
184
+
185
+ socket.onopen = () => {
186
+ if (this.disposed) return
187
+ this.backoffIndex = 0
188
+ log(`已连上 ${this.target.url}`)
189
+ this.send({
190
+ t: 'hello',
191
+ protocolVersion: PROTOCOL_VERSION,
192
+ plugin: name,
193
+ stage: MIRROR_STAGE,
194
+ surface: this.surface?.ok ? this.surface.kind : 'none',
195
+ reason: this.surface?.ok ? undefined : this.surface?.reason,
196
+ })
197
+ if (this.surface?.ok) {
198
+ if (this.paused) this.send({ t: 'status', paused: true, reason: 'hidden' })
199
+ this.startTicking()
200
+ }
201
+ }
202
+ socket.onmessage = (event) => {
203
+ if (typeof event.data === 'string') this.handleText(event.data)
204
+ // 宿主不会往插件发二进制;收到就当没看见(不打死连接)。
205
+ }
206
+ socket.onerror = () => { this.stats.errors += 1 }
207
+ socket.onclose = (event) => {
208
+ if (this.disposed) return
209
+ this.stopTicking()
210
+ log(`连接断开(code=${event?.code ?? '?'}),${this.nextDelay()}ms 后重连`)
211
+ this.scheduleReconnect()
212
+ }
213
+ }
214
+
215
+ nextDelay() {
216
+ const list = this.backoff
217
+ const index = Math.min(this.backoffIndex, list.length - 1)
218
+ return list[index]
219
+ }
220
+
221
+ scheduleReconnect() {
222
+ if (this.disposed || this.reconnectTimer !== null) return
223
+ const delay = this.nextDelay()
224
+ this.backoffIndex = Math.min(this.backoffIndex + 1, this.backoff.length - 1)
225
+ this.stats.reconnects += 1
226
+ this.reconnectTimer = setTimeout(() => {
227
+ this.reconnectTimer = null
228
+ this.connect()
229
+ }, delay)
230
+ this.reconnectTimer?.unref?.()
231
+ }
232
+
233
+ startTicking() {
234
+ if (this.timer !== null || this.disposed) return
235
+ this.timer = setInterval(() => void this.tick(), this.intervalMs)
236
+ this.timer?.unref?.()
237
+ }
238
+
239
+ stopTicking() {
240
+ if (this.timer === null) return
241
+ clearInterval(this.timer)
242
+ this.timer = null
243
+ }
244
+
245
+ /** 一拍:可见才截、上一拍没回来就跳过(不排队——排队就是内存堆积)。 */
246
+ async tick() {
247
+ if (this.disposed || !this.surface?.ok || this.capturing) return
248
+ const visible = this.surface.isVisible()
249
+ if (!visible) {
250
+ if (!this.paused) {
251
+ this.paused = true
252
+ this.pending = null
253
+ log('窗口最小化/隐藏,暂停推帧')
254
+ this.send({ t: 'status', paused: true, reason: 'hidden' })
255
+ }
256
+ return
257
+ }
258
+ if (this.paused) {
259
+ this.paused = false
260
+ log('窗口恢复,继续推帧')
261
+ this.send({ t: 'status', paused: false })
262
+ }
263
+ this.capturing = true
264
+ try {
265
+ const shot = await this.surface.capture()
266
+ if (shot) this.queue(shot)
267
+ } catch (error) {
268
+ this.stats.errors += 1
269
+ log(`截帧失败:${error?.message ?? error}`)
270
+ } finally {
271
+ this.capturing = false
272
+ }
273
+ }
274
+
275
+ /** 队列只留 1 帧:新的顶掉旧的(丢旧不丢新,画面永远是最新的那一张)。 */
276
+ queue(shot) {
277
+ if (this.pending !== null) this.stats.dropped += 1
278
+ this.pending = shot
279
+ this.flush()
280
+ }
281
+
282
+ flush() {
283
+ const socket = this.socket
284
+ if (this.pending === null || this.disposed) return
285
+ if (!socket || socket.readyState !== OPEN) return
286
+ if (typeof socket.bufferedAmount === 'number' && socket.bufferedAmount > MAX_BUFFERED_BYTES) {
287
+ // 发不动就丢:宁可画面卡一拍,也不要缓冲区吃满宿主内存。
288
+ this.pending = null
289
+ this.stats.dropped += 1
290
+ return
291
+ }
292
+ const shot = this.pending
293
+ this.pending = null
294
+ const frame = { seq: this.seq, mime: FRAME_MIME, bytes: shot.bytes.length, w: shot.w, h: shot.h }
295
+ const verdict = validateFrame(frame)
296
+ if (!verdict.ok) {
297
+ this.stats.dropped += 1
298
+ log(`帧元数据不合法(丢):${verdict.error}`)
299
+ return
300
+ }
301
+ const head = encodeMessage({ t: 'frame', ...verdict.frame })
302
+ if (head === null) {
303
+ this.stats.dropped += 1
304
+ return
305
+ }
306
+ try {
307
+ socket.send(head)
308
+ socket.send(shot.bytes)
309
+ this.seq += 1
310
+ this.stats.sent += 1
311
+ } catch (error) {
312
+ this.stats.errors += 1
313
+ log(`推帧失败:${error?.message ?? error}`)
314
+ }
315
+ }
316
+
317
+ send(message) {
318
+ const socket = this.socket
319
+ if (!socket || socket.readyState !== OPEN) return false
320
+ const text = encodeMessage(message)
321
+ if (text === null) return false
322
+ try {
323
+ socket.send(text)
324
+ return true
325
+ } catch {
326
+ return false
327
+ }
328
+ }
329
+
330
+ handleText(text) {
331
+ const decoded = decodeMessage(text)
332
+ if (!decoded.ok) {
333
+ this.stats.errors += 1
334
+ return
335
+ }
336
+ const { message } = decoded
337
+ if (message.t === 'bye') {
338
+ log('宿主要求断开,稍后重连')
339
+ try {
340
+ this.socket?.close(1000, 'bye')
341
+ } catch {
342
+ /* 已经关了 */
343
+ }
344
+ return
345
+ }
346
+ if (message.t !== 'input') return
347
+ const normalized = normalizeInput(message.input ?? message)
348
+ if (!normalized.ok) {
349
+ this.stats.errors += 1
350
+ log(`输入不合法(丢):${normalized.error}`)
351
+ return
352
+ }
353
+ if (!this.surface?.ok) {
354
+ this.stats.dropped += 1
355
+ return
356
+ }
357
+ try {
358
+ if (this.surface.sendInput(normalized.input)) this.stats.inputs += 1
359
+ } catch (error) {
360
+ this.stats.errors += 1
361
+ log(`注入输入失败:${error?.message ?? error}`)
362
+ }
363
+ }
364
+
365
+ report() {
366
+ const { sent, dropped, inputs, reconnects, errors } = this.stats
367
+ if (sent === 0 && inputs === 0 && errors === 0) return
368
+ log(`统计 60s:帧 ${sent} · 丢 ${dropped} · 输入 ${inputs} · 重连 ${reconnects} · 错误 ${errors}`)
369
+ }
370
+
371
+ /** 幂等:清定时器、关连接、断开事件。宿主停用插件或退出时调用。 */
372
+ dispose() {
373
+ if (this.disposed) return
374
+ this.disposed = true
375
+ this.stopTicking()
376
+ if (this.reconnectTimer !== null) clearTimeout(this.reconnectTimer)
377
+ if (this.statsTimer !== null) clearInterval(this.statsTimer)
378
+ this.reconnectTimer = null
379
+ this.statsTimer = null
380
+ this.pending = null
381
+ const socket = this.socket
382
+ this.socket = null
383
+ if (socket) {
384
+ socket.onopen = null
385
+ socket.onmessage = null
386
+ socket.onerror = null
387
+ socket.onclose = null
388
+ try {
389
+ if (socket.readyState === OPEN) socket.close(1000, 'dispose')
390
+ } catch {
391
+ /* 已经关了 */
392
+ }
393
+ }
394
+ log(`已卸载(帧 ${this.stats.sent} · 输入 ${this.stats.inputs})`)
395
+ }
396
+ }
397
+
398
+ /**
399
+ * 插件入口。**软依赖**:这里不需要任何宿主服务(不 inject webServer / tools),
400
+ * 所以装在哪个 profile 里都不会因为缺服务而待机 —— 它只往外连一条 ws。
401
+ */
402
+ export function apply(ctx, config = {}) {
403
+ const target = resolveTarget(config, process.env)
404
+ if (target === null) {
405
+ log('没有配置宿主地址(config.mirrorUrl / DSH_RIG_MIRROR_URL,或 hostPort+labId)—— 待机')
406
+ return
407
+ }
408
+ log(`加载 · stage=${MIRROR_STAGE} · target=${target.url}`)
409
+ const session = new MirrorSession({ target, config })
410
+ const dispose = () => session.dispose()
411
+ void session.start().catch((error) => log(`启动失败:${error?.stack ?? error}`))
412
+
413
+ if (typeof ctx?.effect === 'function') ctx.effect(() => dispose, 'dsh-rig-mirror')
414
+ else if (typeof ctx?.on === 'function') ctx.on('dispose', dispose)
415
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "name": "dsh-rig-mirror",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "./host.js",
7
+ "peerDependencies": {
8
+ "@deepseek-ai/cordis": "~4.1.0"
9
+ }
10
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * dsh-rig · 画面镜像(IO 层)
3
+ *
4
+ * 每个实验室一条 CDP 会话,帧推给所有订阅者(面板的 SSE),输入从订阅者回传到实验室。
5
+ *
6
+ * 三层分工:
7
+ * - `cdp.js` 只认 CDP 协议(连、发命令、收事件);
8
+ * - 这里管**生命周期与分发**(谁在看、帧给谁、断了怎么办);
9
+ * - 路由层只做「把 HTTP 请求翻译成这里的方法调用」,不认识 CDP。
10
+ *
11
+ * 为什么帧是「推」而不是「拉」:`Page.captureScreenshot` 在窗口被遮挡时会一直等,
12
+ * 而 screencast 由渲染进程主动出帧。详见 cdp.js 里 `startScreencast` 的注释。
13
+ *
14
+ * 背压策略:每个订阅者只留**最新一帧**。慢的订阅者丢旧帧而不是排队 ——
15
+ * 画面落后几帧无所谓,排队把内存吃光才是事故。
16
+ */
17
+ import { openCdp } from './cdp.js'
18
+
19
+ /** 一个实验室的镜像状态。 */
20
+ class Mirror {
21
+ constructor(id, log) {
22
+ this.id = id
23
+ this.log = log
24
+ this.session = null
25
+ this.subs = new Set()
26
+ this.lastFrame = null
27
+ this.frames = 0
28
+ this.startedAt = Date.now()
29
+ this.closing = false
30
+ }
31
+ }
32
+
33
+ export class MirrorHub {
34
+ #mirrors = new Map()
35
+ #log
36
+
37
+ constructor(options = {}) {
38
+ this.#log = typeof options.log === 'function' ? options.log : () => {}
39
+ }
40
+
41
+ /** 这个实验室现在有没有画面可看。 */
42
+ status(id) {
43
+ const mirror = this.#mirrors.get(id)
44
+ return {
45
+ attached: Boolean(mirror && mirror.session && !mirror.session.closed),
46
+ viewers: mirror ? mirror.subs.size : 0,
47
+ frames: mirror ? mirror.frames : 0,
48
+ since: mirror ? mirror.startedAt : null,
49
+ }
50
+ }
51
+
52
+ /**
53
+ * 连上实验室的 CDP 并开始出帧。重复调用是幂等的(已经连上就直接复用)。
54
+ *
55
+ * @param {string} id 实验室 id
56
+ * @param {{port: number}} options CDP 端口(桌面壳的 `--remote-debugging-port`)
57
+ */
58
+ async attach(id, options) {
59
+ const existing = this.#mirrors.get(id)
60
+ if (existing?.session && !existing.session.closed) return this.status(id)
61
+ if (existing?.session) existing.session.close()
62
+
63
+ const mirror = existing || new Mirror(id, this.#log)
64
+ mirror.closing = false
65
+ mirror.startedAt = Date.now()
66
+ mirror.frames = 0
67
+ mirror.lastFrame = null
68
+ this.#mirrors.set(id, mirror)
69
+
70
+ this.#log(`[dsh-rig] 连接实验室 ${id} 的 CDP(端口 ${options.port})`)
71
+ const session = await openCdp({ port: options.port, log: this.#log })
72
+ mirror.session = session
73
+
74
+ await session.startScreencast({
75
+ quality: 60,
76
+ maxWidth: 1280,
77
+ maxHeight: 800,
78
+ onFrame: (frame) => {
79
+ mirror.frames += 1
80
+ mirror.lastFrame = frame
81
+ for (const sub of mirror.subs) {
82
+ try {
83
+ sub(frame)
84
+ } catch (err) {
85
+ this.#log(`[dsh-rig] 一个订阅者吞帧失败,已移除:${err?.message ?? err}`)
86
+ mirror.subs.delete(sub)
87
+ }
88
+ }
89
+ },
90
+ })
91
+ this.#log(`[dsh-rig] 实验室 ${id} 开始出帧`)
92
+ return this.status(id)
93
+ }
94
+
95
+ /** 订阅帧。返回取消订阅函数。没有订阅者时仍持续出帧(代价很小,且能立刻给新订阅者一帧)。 */
96
+ subscribe(id, fn) {
97
+ const mirror = this.#mirrors.get(id)
98
+ if (!mirror) throw new Error(`实验室 ${id} 没有镜像会话:先 attach`)
99
+ mirror.subs.add(fn)
100
+ if (mirror.lastFrame) {
101
+ try {
102
+ fn(mirror.lastFrame)
103
+ } catch {
104
+ /* 第一个订阅者立刻失败就当它没订阅 */
105
+ mirror.subs.delete(fn)
106
+ }
107
+ }
108
+ return () => mirror.subs.delete(fn)
109
+ }
110
+
111
+ /** 把输入转给实验室。事件形状见 contract.js 的 `normalizeInput`。 */
112
+ async input(id, event) {
113
+ const mirror = this.#mirrors.get(id)
114
+ if (!mirror?.session || mirror.session.closed) throw new Error(`实验室 ${id} 没有镜像会话`)
115
+ const session = mirror.session
116
+ switch (event.type) {
117
+ case 'mouse':
118
+ await session.pointer({ type: event.action, x: event.x, y: event.y, button: event.button, clickCount: event.clickCount })
119
+ return true
120
+ case 'wheel':
121
+ await session.wheel({ x: event.x, y: event.y, deltaX: event.deltaX, deltaY: event.deltaY })
122
+ return true
123
+ case 'text':
124
+ await session.text(event.text)
125
+ return true
126
+ case 'key':
127
+ await session.key({ key: event.key, code: event.code, windowsVirtualKeyCode: event.windowsVirtualKeyCode, modifiers: event.modifiers })
128
+ return true
129
+ default:
130
+ throw new Error(`未知输入类型 ${event.type}`)
131
+ }
132
+ }
133
+
134
+ /** 当前视口(客户端按它把像素坐标换成 CSS 坐标)。 */
135
+ async viewport(id) {
136
+ const mirror = this.#mirrors.get(id)
137
+ if (!mirror?.session) return null
138
+ return mirror.session.viewport(true).catch(() => null)
139
+ }
140
+
141
+ /** 断开并停止出帧。 */
142
+ detach(id) {
143
+ const mirror = this.#mirrors.get(id)
144
+ if (!mirror) return false
145
+ mirror.closing = true
146
+ mirror.subs.clear()
147
+ try {
148
+ mirror.session?.close()
149
+ } catch {
150
+ /* 已经断了 */
151
+ }
152
+ this.#mirrors.delete(id)
153
+ this.#log(`[dsh-rig] 实验室 ${id} 的镜像已断开`)
154
+ return true
155
+ }
156
+
157
+ /** 插件卸载:全部断开。 */
158
+ disposeAll() {
159
+ for (const id of [...this.#mirrors.keys()]) this.detach(id)
160
+ }
161
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-rig",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
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",