@capyclaw/rsp-suite 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/README.md +84 -2
- package/cordis.patch.yml +8 -0
- package/dsh-suite.json +81 -0
- package/package.json +39 -3
- package/skill/README.md +7 -0
- package/skill/contract/rsp-contract.json +389 -0
- package/skill/cordis.patch.yml +4 -0
- package/skill/package.json +33 -0
- package/skill/plugin.mjs +15 -0
- package/skill/skills/remote-screen/SKILL.md +120 -0
- package/workbench/contract/capabilities.json +171 -0
- package/workbench/lib/client.mjs +454 -0
- package/workbench/lib/descriptors.mjs +28 -0
- package/workbench/lib/host.mjs +111 -0
- package/workbench/lib/manager.mjs +333 -0
- package/workbench/lib/session-mode.mjs +68 -0
- package/workbench/lib/tools.mjs +385 -0
- package/workbench/lib/workbench.mjs +165 -0
- package/workbench/package.json +47 -0
- package/workbench/plugin.mjs +2 -0
- package/workbench/scripts/build-contract.mjs +41 -0
- package/workbench/scripts/drive.mjs +66 -0
- package/workbench/test/client.test.mjs +218 -0
- package/workbench/test/frames-prune.test.mjs +49 -0
- package/workbench/test/h264.test.mjs +101 -0
- package/workbench/test/live-persistent-smoke.mjs +29 -0
- package/workbench/test/live-smoke.mjs +109 -0
- package/workbench/test/mock-server.mjs +194 -0
- package/workbench/test/persistence.test.mjs +177 -0
- package/workbench/test/persistent.test.mjs +160 -0
- package/workbench/test/session-mode.test.mjs +118 -0
- package/workbench/test/workbench.test.mjs +385 -0
- package/workbench/ui/index.html +475 -0
- package/workbench/verify-e2e.mjs +44 -0
|
@@ -0,0 +1,454 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSP/1 控制端客户端(Remote Screen Protocol,第 1 版)。
|
|
3
|
+
*
|
|
4
|
+
* 严格实现 RSP/1 规范的控制端侧:
|
|
5
|
+
* - 画面通道:/screen.ws(TEXT hello + BINARY JPEG 帧),常驻 + 退避 1s→5s 重连;
|
|
6
|
+
* 另提供 /screen MJPEG 上游打开方法供查看器代理。
|
|
7
|
+
* - 操控通道:/control.ws(seq/ack,顺序注入)优先,POST /control 降级。
|
|
8
|
+
* - 鉴权:?token= 查询参数;401 / 关闭码 4001 → auth-error。
|
|
9
|
+
* - 坐标:上线一律逻辑点(hello width/height);帧像素→逻辑点换算在工具层做。
|
|
10
|
+
*
|
|
11
|
+
* 无 cordis 依赖,纯 Node(fetch + ws),可单测。
|
|
12
|
+
*/
|
|
13
|
+
import { EventEmitter } from 'node:events'
|
|
14
|
+
import WebSocket from 'ws'
|
|
15
|
+
|
|
16
|
+
export const PROTOCOL = 'rsp/1'
|
|
17
|
+
export const MAX_TEXT_UNITS = 4096 // §5.3 text 上限(UTF-16 码元)
|
|
18
|
+
export const MAX_EVENT_BYTES = 64 * 1024 // §5.4 单事件上限
|
|
19
|
+
const ACK_TIMEOUT_MS = 5000
|
|
20
|
+
const MOVE_MIN_GAP_MS = 16 // §5.1 合并 move ≤ 60/s
|
|
21
|
+
const RECONNECT_MIN_MS = 1000 // §8 退避 1s→5s
|
|
22
|
+
const RECONNECT_MAX_MS = 5000
|
|
23
|
+
|
|
24
|
+
/** 从 JPEG 字节解析像素尺寸(扫 SOF 段),无需图像库。返回 {width,height} 或 null。 */
|
|
25
|
+
export function jpegSize(buf) {
|
|
26
|
+
if (!buf || buf.length < 4 || buf[0] !== 0xff || buf[1] !== 0xd8) return null
|
|
27
|
+
let i = 2
|
|
28
|
+
while (i + 9 < buf.length) {
|
|
29
|
+
if (buf[i] !== 0xff) { i++; continue }
|
|
30
|
+
// 跳过填充 FF
|
|
31
|
+
while (i < buf.length && buf[i] === 0xff) i++
|
|
32
|
+
const marker = buf[i++]
|
|
33
|
+
if (marker === 0xd9 || marker === 0xda) break // EOI / SOS:尺寸必在 SOS 之前
|
|
34
|
+
if (marker === 0x00 || (marker >= 0xd0 && marker <= 0xd7)) continue // stuffed / RST
|
|
35
|
+
if (i + 2 > buf.length) break
|
|
36
|
+
const len = buf.readUInt16BE(i)
|
|
37
|
+
// SOF0..SOF15(除 C4/DHT、C8/JPG、CC/DAC)携带尺寸
|
|
38
|
+
const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc
|
|
39
|
+
if (isSof) {
|
|
40
|
+
if (i + 7 > buf.length) break
|
|
41
|
+
const height = buf.readUInt16BE(i + 3)
|
|
42
|
+
const width = buf.readUInt16BE(i + 5)
|
|
43
|
+
return { width, height }
|
|
44
|
+
}
|
|
45
|
+
i += len
|
|
46
|
+
}
|
|
47
|
+
return null
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 把长文本按 UTF-16 码元 ≤4096 分片(不切断代理对)。 */
|
|
51
|
+
export function splitText(text, limit = MAX_TEXT_UNITS) {
|
|
52
|
+
const out = []
|
|
53
|
+
let s = String(text)
|
|
54
|
+
while (s.length > limit) {
|
|
55
|
+
let cut = limit
|
|
56
|
+
// 避免在高位代理处切断
|
|
57
|
+
const code = s.charCodeAt(cut - 1)
|
|
58
|
+
if (code >= 0xd800 && code <= 0xdbff) cut -= 1
|
|
59
|
+
out.push(s.slice(0, cut))
|
|
60
|
+
s = s.slice(cut)
|
|
61
|
+
}
|
|
62
|
+
if (s.length) out.push(s)
|
|
63
|
+
return out
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function maskToken(token) {
|
|
67
|
+
if (!token) return null
|
|
68
|
+
const s = String(token)
|
|
69
|
+
if (s.length <= 8) return '****'
|
|
70
|
+
return s.slice(0, 4) + '…' + s.slice(-4)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function normalizeBase({ url, host, port }) {
|
|
74
|
+
if (url) {
|
|
75
|
+
const u = new URL(url)
|
|
76
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') throw badArg('url 必须是 http/https')
|
|
77
|
+
return (u.origin + u.pathname).replace(/\/+$/, '')
|
|
78
|
+
}
|
|
79
|
+
if (!host) throw badArg('需要 url 或 host')
|
|
80
|
+
const p = port ?? 8765
|
|
81
|
+
const h = String(host).replace(/^https?:\/\//, '').replace(/\/+$/, '')
|
|
82
|
+
return `http://${h.includes(':') ? `[${h}]` : h}:${p}`
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function badArg(message) { const e = new Error(message); e.code = 'bad_event'; return e }
|
|
86
|
+
|
|
87
|
+
export class RspClient extends EventEmitter {
|
|
88
|
+
/**
|
|
89
|
+
* @param {object} o
|
|
90
|
+
* @param {string} o.baseUrl http://host:port
|
|
91
|
+
* @param {string} o.token bearer 令牌
|
|
92
|
+
* @param {Function} [o.fetchImpl]
|
|
93
|
+
* @param {Function} [o.WebSocketImpl]
|
|
94
|
+
* @param {Function} [o.logger]
|
|
95
|
+
*/
|
|
96
|
+
constructor({ baseUrl, token, fetchImpl, WebSocketImpl, logger } = {}) {
|
|
97
|
+
super()
|
|
98
|
+
if (!baseUrl) throw badArg('baseUrl 必填')
|
|
99
|
+
if (!token) throw badArg('token 必填')
|
|
100
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '')
|
|
101
|
+
this.token = String(token)
|
|
102
|
+
this.fetch = fetchImpl || globalThis.fetch
|
|
103
|
+
this.WS = WebSocketImpl || WebSocket
|
|
104
|
+
this.log = logger || (() => {})
|
|
105
|
+
this.closed = false
|
|
106
|
+
this.info = null
|
|
107
|
+
this.hello = null
|
|
108
|
+
this.lastFrame = null // {width,height,bytes,at}
|
|
109
|
+
this.frameCount = 0
|
|
110
|
+
this.screenWs = null
|
|
111
|
+
this.controlWs = null
|
|
112
|
+
this.screenState = 'idle' // idle|connecting|open|reconnecting|closed|auth-error
|
|
113
|
+
this.controlState = 'idle'
|
|
114
|
+
this.controlMode = 'ws' // ws|post
|
|
115
|
+
this._seq = 0
|
|
116
|
+
this._pending = null // {seq,resolve,reject,timer}
|
|
117
|
+
this._pressedKeys = new Set()
|
|
118
|
+
this._pressedButtons = new Set()
|
|
119
|
+
this._lastMoveAt = 0
|
|
120
|
+
this._screenRetry = 0
|
|
121
|
+
this._screenTimer = null
|
|
122
|
+
this._authFailed = false
|
|
123
|
+
this.lastError = null
|
|
124
|
+
// 实时 H.264 增量通道(RSP/1 §7.3/§7.6,可选;被控端不提供时自动回退 JPEG)
|
|
125
|
+
this.h264Ws = null
|
|
126
|
+
this.h264State = 'idle' // idle|connecting|open|closed|unsupported
|
|
127
|
+
this.h264Hello = null
|
|
128
|
+
this.h264Head = [] // 最近 SPS/PPS/IDR,供新观众立即起播
|
|
129
|
+
this.h264Bytes = 0 // h264 通道累计接收字节(诊断用)
|
|
130
|
+
this.h264Nals = 0 // h264 通道累计 NAL 数(诊断用)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
get wsBase() { return this.baseUrl.replace(/^http/, 'ws') }
|
|
134
|
+
_url(path) { return `${this.baseUrl}${path}?token=${encodeURIComponent(this.token)}` }
|
|
135
|
+
_wsUrl(path) { return `${this.wsBase}${path}?token=${encodeURIComponent(this.token)}` }
|
|
136
|
+
|
|
137
|
+
/** 连接:拉 /info 校验协议,开 screen.ws(常驻)与 control.ws。返回 info。 */
|
|
138
|
+
async connect() {
|
|
139
|
+
if (this.closed) throw badArg('client 已关闭')
|
|
140
|
+
this._authFailed = false
|
|
141
|
+
const info = await this.fetchInfo()
|
|
142
|
+
this.info = info
|
|
143
|
+
if (info.protocol !== PROTOCOL) {
|
|
144
|
+
const e = new Error(`被控端协议为 ${info.protocol},本控制端仅支持 ${PROTOCOL}`)
|
|
145
|
+
e.code = 'protocol_mismatch'; throw e
|
|
146
|
+
}
|
|
147
|
+
const fmt = info.screen?.format
|
|
148
|
+
if (fmt && fmt !== 'jpeg') {
|
|
149
|
+
const e = new Error(`不支持的画面格式 ${fmt}(v1 仅 jpeg)`); e.code = 'unsupported_format'; throw e
|
|
150
|
+
}
|
|
151
|
+
this._openScreen()
|
|
152
|
+
this._openH264() // 尽力建立实时通道;失败/不支持则回退 JPEG,不致命
|
|
153
|
+
await this._openControl().catch((err) => {
|
|
154
|
+
// 操控 WS 建不起来不致命:降级 POST(sendEvent 时再试)
|
|
155
|
+
this.log('control.ws 建立失败,降级 POST:' + err.message)
|
|
156
|
+
this.controlMode = 'post'
|
|
157
|
+
this.controlState = 'post'
|
|
158
|
+
})
|
|
159
|
+
return info
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** 实时 H.264 增量通道:WS /screen.h264.ws。被控端未实现时握手 404/失败→unsupported,回退 JPEG。 */
|
|
163
|
+
_openH264() {
|
|
164
|
+
if (this.closed || this._authFailed) return
|
|
165
|
+
this.h264State = 'connecting'
|
|
166
|
+
let ws
|
|
167
|
+
try { ws = new this.WS(this._wsUrl('/screen.h264.ws')) } catch { this.h264State = 'unsupported'; return }
|
|
168
|
+
ws.binaryType = 'nodebuffer'
|
|
169
|
+
this.h264Ws = ws
|
|
170
|
+
ws.on('open', () => { this.h264State = 'open'; this.emit('h264-state', this.h264State) })
|
|
171
|
+
ws.on('message', (data, isBinary) => {
|
|
172
|
+
if (!isBinary) {
|
|
173
|
+
try {
|
|
174
|
+
const msg = JSON.parse(data.toString())
|
|
175
|
+
if (msg.kind === 'hello' && msg.format === 'h264') { this.h264Hello = msg; this.emit('h264-hello', msg) }
|
|
176
|
+
} catch { /* ignore */ }
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const t = h264NalType(data)
|
|
180
|
+
this.h264Bytes += data.length
|
|
181
|
+
this.h264Nals++
|
|
182
|
+
if (t === 7 || t === 8 || t === 5) {
|
|
183
|
+
// 累积 SPS/PPS/IDR 各一,按 SPS,PPS,IDR 规范顺序,供新观众立即起播
|
|
184
|
+
const rank = { 7: 0, 8: 1, 5: 2 }
|
|
185
|
+
this.h264Head = [...this.h264Head.filter((b) => h264NalType(b) !== t), data]
|
|
186
|
+
.sort((a, b) => rank[h264NalType(a)] - rank[h264NalType(b)])
|
|
187
|
+
}
|
|
188
|
+
this.emit('h264', data)
|
|
189
|
+
})
|
|
190
|
+
ws.on('close', (code) => {
|
|
191
|
+
this.h264Ws = null
|
|
192
|
+
this.h264State = (code === 4001) ? 'closed' : (this.h264State === 'open' ? 'closed' : 'unsupported')
|
|
193
|
+
this.emit('h264-state', this.h264State)
|
|
194
|
+
})
|
|
195
|
+
ws.on('error', () => { /* close 会跟进 */ })
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async fetchInfo() {
|
|
199
|
+
const res = await this.fetch(this._url('/info'), { headers: { accept: 'application/json' } })
|
|
200
|
+
if (res.status === 401) { const e = new Error('令牌缺失或错误(401)'); e.code = 'unauthorized'; throw e }
|
|
201
|
+
if (!res.ok) { const e = new Error(`/info 返回 ${res.status}`); e.code = 'engine_unavailable'; throw e }
|
|
202
|
+
return res.json()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// ---- 画面通道 ----
|
|
206
|
+
_openScreen() {
|
|
207
|
+
if (this.closed || this._authFailed) return
|
|
208
|
+
this.screenState = 'connecting'
|
|
209
|
+
const ws = new this.WS(this._wsUrl('/screen.ws'))
|
|
210
|
+
ws.binaryType = 'nodebuffer'
|
|
211
|
+
this.screenWs = ws
|
|
212
|
+
ws.on('open', () => { this.screenState = 'open'; this._screenRetry = 0; this.emit('screen-state', this.screenState) })
|
|
213
|
+
ws.on('message', (data, isBinary) => {
|
|
214
|
+
if (!isBinary) {
|
|
215
|
+
try {
|
|
216
|
+
const msg = JSON.parse(data.toString())
|
|
217
|
+
if (msg.kind === 'hello') {
|
|
218
|
+
this.hello = { width: msg.width, height: msg.height, fps: msg.fps, format: msg.format, protocol: msg.protocol }
|
|
219
|
+
if (msg.format && msg.format !== 'jpeg') {
|
|
220
|
+
this.lastError = { code: 'unsupported_format', message: `hello.format=${msg.format}` }
|
|
221
|
+
this.emit('error', this.lastError)
|
|
222
|
+
}
|
|
223
|
+
this.emit('hello', this.hello)
|
|
224
|
+
}
|
|
225
|
+
// 未知 kind 忽略(§7)
|
|
226
|
+
} catch (e) { this.log('screen TEXT 解析失败:' + e.message) }
|
|
227
|
+
return
|
|
228
|
+
}
|
|
229
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(data)
|
|
230
|
+
const size = jpegSize(buf) || { width: this.hello?.width ?? 0, height: this.hello?.height ?? 0 }
|
|
231
|
+
this.lastFrame = { width: size.width, height: size.height, bytes: buf, at: Date.now() }
|
|
232
|
+
this.frameCount++
|
|
233
|
+
this.emit('frame', this.lastFrame)
|
|
234
|
+
})
|
|
235
|
+
ws.on('close', (code) => {
|
|
236
|
+
this.screenWs = null
|
|
237
|
+
if (this.closed) { this.screenState = 'closed'; this.emit('screen-state', this.screenState); return }
|
|
238
|
+
if (code === 4001) { this._authFailed = true; this.screenState = 'auth-error'; this.emit('auth-error', { channel: 'screen' }); this.emit('screen-state', this.screenState); return }
|
|
239
|
+
this.screenState = 'reconnecting'
|
|
240
|
+
this.emit('screen-state', this.screenState)
|
|
241
|
+
this._scheduleScreenReconnect()
|
|
242
|
+
})
|
|
243
|
+
ws.on('error', (err) => { this.log('screen.ws error: ' + err.message); this.lastError = { code: 'ws_error', message: err.message } })
|
|
244
|
+
// ws 自动回 Pong(§4.1.6)
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
_scheduleScreenReconnect() {
|
|
248
|
+
if (this.closed || this._authFailed) return
|
|
249
|
+
const delay = Math.min(RECONNECT_MAX_MS, RECONNECT_MIN_MS * Math.pow(2, this._screenRetry))
|
|
250
|
+
this._screenRetry++
|
|
251
|
+
this._screenTimer = setTimeout(() => { this._screenTimer = null; this._openScreen() }, delay)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 打开上游 MJPEG 流(供查看器代理)。返回 {res, abort};调用方负责 pipe 与清理。 */
|
|
255
|
+
async openMjpeg() {
|
|
256
|
+
const ac = new AbortController()
|
|
257
|
+
const res = await this.fetch(this._url('/screen'), { signal: ac.signal, headers: { accept: 'multipart/x-mixed-replace' } })
|
|
258
|
+
if (res.status === 401) { const e = new Error('令牌缺失或错误(401)'); e.code = 'unauthorized'; throw e }
|
|
259
|
+
if (res.status === 503) { const e = new Error('引擎未就绪(503)'); e.code = 'engine_unavailable'; throw e }
|
|
260
|
+
if (!res.ok) { const e = new Error(`/screen 返回 ${res.status}`); e.code = 'engine_unavailable'; throw e }
|
|
261
|
+
return { res, abort: () => ac.abort() }
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---- 操控通道 ----
|
|
265
|
+
_openControl() {
|
|
266
|
+
if (this.closed) return Promise.reject(badArg('client 已关闭'))
|
|
267
|
+
if (this.info && this.info.control && this.info.control.enabled === false) {
|
|
268
|
+
const e = new Error('操控通道被禁用(control.enabled=false)'); e.code = 'forbidden'; return Promise.reject(e)
|
|
269
|
+
}
|
|
270
|
+
return new Promise((resolve, reject) => {
|
|
271
|
+
this.controlState = 'connecting'
|
|
272
|
+
const ws = new this.WS(this._wsUrl('/control.ws'))
|
|
273
|
+
this.controlWs = ws
|
|
274
|
+
let settled = false
|
|
275
|
+
const fail = (err) => { if (settled) return; settled = true; this.controlWs = null; this.controlState = 'idle'; reject(err) }
|
|
276
|
+
ws.on('open', () => {
|
|
277
|
+
if (settled) return; settled = true
|
|
278
|
+
this.controlMode = 'ws'; this.controlState = 'open'
|
|
279
|
+
this.emit('control-state', this.controlState)
|
|
280
|
+
resolve()
|
|
281
|
+
})
|
|
282
|
+
ws.on('message', (data, isBinary) => {
|
|
283
|
+
if (isBinary) return
|
|
284
|
+
let msg; try { msg = JSON.parse(data.toString()) } catch { return }
|
|
285
|
+
if (msg.kind === 'ack' && this._pending && msg.seq === this._pending.seq) {
|
|
286
|
+
const p = this._pending; this._pending = null; clearTimeout(p.timer); p.resolve({ ok: true, seq: msg.seq })
|
|
287
|
+
} else if (msg.kind === 'error') {
|
|
288
|
+
const err = new Error(msg.message || 'bad_event'); err.code = msg.code || 'bad_event'
|
|
289
|
+
if (this._pending) { const p = this._pending; this._pending = null; clearTimeout(p.timer); p.reject(err) }
|
|
290
|
+
else this.emit('error', { code: err.code, message: err.message })
|
|
291
|
+
}
|
|
292
|
+
})
|
|
293
|
+
ws.on('close', (code) => {
|
|
294
|
+
this.controlWs = null
|
|
295
|
+
// §5.5 被控端按连接自动补 up;本地状态同步清空
|
|
296
|
+
this._pressedKeys.clear(); this._pressedButtons.clear()
|
|
297
|
+
if (this._pending) { const p = this._pending; this._pending = null; clearTimeout(p.timer); p.reject(new Error(`control.ws 关闭(${code})`)) }
|
|
298
|
+
if (this.closed) { this.controlState = 'closed'; return }
|
|
299
|
+
if (code === 4001) { this._authFailed = true; this.controlState = 'auth-error'; this.emit('auth-error', { channel: 'control' }); return }
|
|
300
|
+
if (code === 4003) { this.controlMode = 'post'; this.controlState = 'disabled'; return }
|
|
301
|
+
this.controlState = 'idle' // 懒重连:下次 sendEvent 再建
|
|
302
|
+
this.emit('control-state', this.controlState)
|
|
303
|
+
})
|
|
304
|
+
ws.on('error', (err) => { this.log('control.ws error: ' + err.message); fail(err) })
|
|
305
|
+
// 握手被拒(4003/503/401)时 ws 触发 error+close
|
|
306
|
+
setTimeout(() => { if (!settled) fail(new Error('control.ws 握手超时')) }, ACK_TIMEOUT_MS).unref?.()
|
|
307
|
+
})
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async _ensureControl() {
|
|
311
|
+
if (this.controlMode === 'post') return 'post'
|
|
312
|
+
if (this.controlWs && this.controlWs.readyState === 1) return 'ws'
|
|
313
|
+
try { await this._openControl(); return 'ws' }
|
|
314
|
+
catch (err) {
|
|
315
|
+
if (err.code === 'forbidden') throw err
|
|
316
|
+
this.controlMode = 'post'; this.controlState = 'post'
|
|
317
|
+
return 'post'
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 注入一个事件(自包含)。mouse move 限速;key/mouse 记录按下态。返回 {ok,seq?,via}。 */
|
|
322
|
+
async sendEvent(ev) {
|
|
323
|
+
if (this.closed) throw badArg('client 已关闭')
|
|
324
|
+
if (this._authFailed) { const e = new Error('鉴权失败,请重新提供令牌'); e.code = 'unauthorized'; throw e }
|
|
325
|
+
if (!ev || typeof ev !== 'object' || !ev.cmd) throw badArg('事件必须含 cmd')
|
|
326
|
+
// move 限速(§5.1 ≤60/s)
|
|
327
|
+
if (ev.cmd === 'mouse' && ev.action === 'move') {
|
|
328
|
+
const wait = this._lastMoveAt + MOVE_MIN_GAP_MS - Date.now()
|
|
329
|
+
if (wait > 0) await sleep(wait)
|
|
330
|
+
this._lastMoveAt = Date.now()
|
|
331
|
+
}
|
|
332
|
+
const bytes = Buffer.byteLength(JSON.stringify(ev), 'utf8')
|
|
333
|
+
if (bytes > MAX_EVENT_BYTES) { const e = new Error('事件超过 64KiB'); e.code = 'too_large'; throw e }
|
|
334
|
+
|
|
335
|
+
const via = await this._ensureControl()
|
|
336
|
+
let result
|
|
337
|
+
if (via === 'ws') result = await this._sendWs(ev)
|
|
338
|
+
else result = await this._sendPost(ev)
|
|
339
|
+
this._trackPressed(ev)
|
|
340
|
+
return { ...result, via }
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
_sendWs(ev) {
|
|
344
|
+
const seq = ++this._seq
|
|
345
|
+
const payload = { ...ev, seq }
|
|
346
|
+
return new Promise((resolve, reject) => {
|
|
347
|
+
const timer = setTimeout(() => {
|
|
348
|
+
if (this._pending && this._pending.seq === seq) { this._pending = null; reject(new Error('ack 超时(5s)')) }
|
|
349
|
+
}, ACK_TIMEOUT_MS)
|
|
350
|
+
this._pending = { seq, resolve, reject, timer }
|
|
351
|
+
try { this.controlWs.send(JSON.stringify(payload)) }
|
|
352
|
+
catch (err) { this._pending = null; clearTimeout(timer); reject(err) }
|
|
353
|
+
})
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
async _sendPost(ev) {
|
|
357
|
+
const res = await this.fetch(this._url('/control'), {
|
|
358
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(ev),
|
|
359
|
+
})
|
|
360
|
+
let body = null; try { body = await res.json() } catch { /* ignore */ }
|
|
361
|
+
if (res.status === 200 && body && body.ok) return { ok: true }
|
|
362
|
+
const code = body?.error?.code || httpCodeToError(res.status)
|
|
363
|
+
const err = new Error(body?.error?.message || `POST /control 返回 ${res.status}`)
|
|
364
|
+
err.code = code; throw err
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
_trackPressed(ev) {
|
|
368
|
+
if (ev.cmd === 'key') {
|
|
369
|
+
if (ev.action === 'down') this._pressedKeys.add(ev.code)
|
|
370
|
+
else if (ev.action === 'up') this._pressedKeys.delete(ev.code)
|
|
371
|
+
} else if (ev.cmd === 'mouse') {
|
|
372
|
+
const b = ev.button || 'left'
|
|
373
|
+
if (ev.action === 'down') this._pressedButtons.add(b)
|
|
374
|
+
else if (ev.action === 'up' || ev.action === 'click') this._pressedButtons.delete(b)
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/** 尽力补发所有按下态的 up(POST 模式无服务端跟踪时尤其需要)。 */
|
|
379
|
+
async releaseAll() {
|
|
380
|
+
const keys = [...this._pressedKeys], buttons = [...this._pressedButtons]
|
|
381
|
+
for (const code of keys) { try { await this.sendEvent({ cmd: 'key', action: 'up', code }) } catch { /* best effort */ } }
|
|
382
|
+
for (const button of buttons) { try { await this.sendEvent({ cmd: 'mouse', action: 'up', x: 0, y: 0, button }) } catch { /* best effort */ } }
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** 等待一帧比 since 更新的帧(fresh 截图用)。超时返回最近帧。 */
|
|
386
|
+
async waitFrame(since = Date.now(), timeoutMs = 2000) {
|
|
387
|
+
if (this.lastFrame && this.lastFrame.at >= since) return this.lastFrame
|
|
388
|
+
return new Promise((resolve) => {
|
|
389
|
+
let done = false
|
|
390
|
+
const finish = (f) => { if (done) return; done = true; clearTimeout(timer); this.off('frame', onFrame); resolve(f) }
|
|
391
|
+
const onFrame = (f) => finish(f)
|
|
392
|
+
const timer = setTimeout(() => finish(this.lastFrame), timeoutMs)
|
|
393
|
+
this.on('frame', onFrame)
|
|
394
|
+
if (this.lastFrame && this.lastFrame.at >= since) finish(this.lastFrame)
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
status() {
|
|
399
|
+
return {
|
|
400
|
+
baseUrl: this.baseUrl,
|
|
401
|
+
token: maskToken(this.token),
|
|
402
|
+
protocol: this.info?.protocol ?? null,
|
|
403
|
+
connected: this.screenState === 'open',
|
|
404
|
+
screenState: this.screenState,
|
|
405
|
+
controlState: this.controlState,
|
|
406
|
+
controlMode: this.controlMode,
|
|
407
|
+
controlEnabled: this.info?.control?.enabled ?? null,
|
|
408
|
+
hello: this.hello,
|
|
409
|
+
logical: this.hello ? { width: this.hello.width, height: this.hello.height } : (this.info?.screen ? { width: this.info.screen.width, height: this.info.screen.height } : null),
|
|
410
|
+
lastFrame: this.lastFrame ? { width: this.lastFrame.width, height: this.lastFrame.height, at: this.lastFrame.at, ageMs: Date.now() - this.lastFrame.at, bytes: this.lastFrame.bytes.length } : null,
|
|
411
|
+
frameCount: this.frameCount,
|
|
412
|
+
viewers: this.info?.viewers ?? null,
|
|
413
|
+
engine: this.info?.engine ?? null,
|
|
414
|
+
pressedKeys: [...this._pressedKeys],
|
|
415
|
+
pressedButtons: [...this._pressedButtons],
|
|
416
|
+
authFailed: this._authFailed,
|
|
417
|
+
lastError: this.lastError,
|
|
418
|
+
h264: this.h264State === 'open',
|
|
419
|
+
h264State: this.h264State,
|
|
420
|
+
h264Hello: this.h264Hello,
|
|
421
|
+
h264Bytes: this.h264Bytes,
|
|
422
|
+
h264Nals: this.h264Nals,
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async disconnect() {
|
|
427
|
+
if (this.closed) return
|
|
428
|
+
try { await this.releaseAll() } catch { /* best effort */ }
|
|
429
|
+
this.closed = true
|
|
430
|
+
if (this._screenTimer) { clearTimeout(this._screenTimer); this._screenTimer = null }
|
|
431
|
+
if (this._pending) { const p = this._pending; this._pending = null; clearTimeout(p.timer); p.reject(new Error('client 关闭')) }
|
|
432
|
+
try { this.screenWs?.close(1000) } catch { /* ignore */ }
|
|
433
|
+
try { this.controlWs?.close(1000) } catch { /* ignore */ }
|
|
434
|
+
try { this.h264Ws?.close(1000) } catch { /* ignore */ }
|
|
435
|
+
this.screenWs = null; this.controlWs = null; this.h264Ws = null
|
|
436
|
+
this.screenState = 'closed'; this.controlState = 'closed'; this.h264State = 'closed'
|
|
437
|
+
this.emit('screen-state', this.screenState)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Annex-B NAL 类型(跳过 3/4 字节起始码)。 */
|
|
442
|
+
function h264NalType(buf) {
|
|
443
|
+
let i = 0
|
|
444
|
+
if (buf[0] === 0 && buf[1] === 0 && buf[2] === 0 && buf[3] === 1) i = 4
|
|
445
|
+
else if (buf[0] === 0 && buf[1] === 0 && buf[2] === 1) i = 3
|
|
446
|
+
return buf[i] & 0x1f
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function httpCodeToError(status) {
|
|
450
|
+
return ({ 401: 'unauthorized', 403: 'forbidden', 400: 'bad_event', 413: 'too_large', 404: 'not_found', 503: 'engine_unavailable' })[status] || 'engine_unavailable'
|
|
451
|
+
}
|
|
452
|
+
function sleep(ms) { return new Promise((r) => setTimeout(r, ms)) }
|
|
453
|
+
|
|
454
|
+
export { maskToken, normalizeBase }
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSP 能力描述符:契约真源在 contract/capabilities.json。
|
|
3
|
+
* 登记进公共描述符面,供 conductor 等编排器发现(controlMode:'interface')。
|
|
4
|
+
*/
|
|
5
|
+
import { readFileSync } from 'node:fs'
|
|
6
|
+
import path from 'node:path'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
|
|
9
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url))
|
|
10
|
+
const contract = JSON.parse(readFileSync(path.join(HERE, '..', 'contract', 'capabilities.json'), 'utf8'))
|
|
11
|
+
|
|
12
|
+
export const RSP_CONTRACT_VERSION = contract.contractVersion
|
|
13
|
+
export const RSP_DESCRIPTORS = Object.freeze(contract.capabilities.map((d) => Object.freeze({ ...d })))
|
|
14
|
+
|
|
15
|
+
export function registerRspDescriptors(toolHost, { baseUrl = '', validate } = {}) {
|
|
16
|
+
if (!toolHost?.registerCapabilityDescriptor) throw new Error('toolHost 缺少描述符面(需 @capyclaw/tool-host >= 0.2.0)')
|
|
17
|
+
const registered = []
|
|
18
|
+
for (const descriptor of RSP_DESCRIPTORS) {
|
|
19
|
+
if (typeof validate === 'function') {
|
|
20
|
+
const verdict = validate(descriptor)
|
|
21
|
+
if (verdict && verdict.ok === false) {
|
|
22
|
+
throw new Error(`rsp 描述符不合法 ${descriptor.name}: ${(verdict.errors || []).join('; ')}`)
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
registered.push(toolHost.registerCapabilityDescriptor(descriptor, { baseUrl }))
|
|
26
|
+
}
|
|
27
|
+
return registered
|
|
28
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rsp-workbench cordis 宿主入口:把可单测核心接进 DSH。
|
|
3
|
+
* 模式沿用 conductor/browser embedded-host:inject=['webServer'],其余服务 safeGet 优雅降级。
|
|
4
|
+
* 路由冲突只警告退出本条目,绝不升级为宿主崩溃;app.listen 的 rejection 必须 .catch 兜底。
|
|
5
|
+
*/
|
|
6
|
+
import os from 'node:os'
|
|
7
|
+
import path from 'node:path'
|
|
8
|
+
import { assertServiceApi } from '@capyclaw/plugin-kit/service/api'
|
|
9
|
+
import { validateCapabilityDescriptor } from '@capyclaw/suite-kit/capability'
|
|
10
|
+
import { createRspWorkbench } from './workbench.mjs'
|
|
11
|
+
import { RSP_DESCRIPTORS } from './descriptors.mjs'
|
|
12
|
+
import { bindToolsToSessionMode } from './session-mode.mjs'
|
|
13
|
+
|
|
14
|
+
export const name = 'rsp-workbench'
|
|
15
|
+
export const inject = ['webServer']
|
|
16
|
+
|
|
17
|
+
function safeGet(ctx, serviceName) {
|
|
18
|
+
try { return ctx.reflect?.get?.(serviceName) ?? ctx[serviceName] } catch { return null }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function apply(ctx, config = {}) {
|
|
22
|
+
const log = {
|
|
23
|
+
info: (...a) => (ctx.logger?.info ? ctx.logger.info(...a) : console.log('[rsp]', ...a)),
|
|
24
|
+
warn: (...a) => (ctx.logger?.warn ? ctx.logger.warn(...a) : console.warn('[rsp]', ...a)),
|
|
25
|
+
}
|
|
26
|
+
const mountPath = config.mountPath || '/capyclaw/rsp'
|
|
27
|
+
const hostDir = config.hostDir || path.join(os.homedir(), '.dsh-rsp')
|
|
28
|
+
const disposers = []
|
|
29
|
+
|
|
30
|
+
try {
|
|
31
|
+
const toolHost = safeGet(ctx, 'toolHost')
|
|
32
|
+
const serviceHost = safeGet(ctx, 'serviceHost')
|
|
33
|
+
if (!toolHost || !serviceHost) {
|
|
34
|
+
log.warn('缺少 toolHost/serviceHost 公共服务,rsp-suite 未激活(请安装对应基础套件)')
|
|
35
|
+
return () => {}
|
|
36
|
+
}
|
|
37
|
+
assertServiceApi(toolHost, { name: 'toolHost', major: 1 })
|
|
38
|
+
assertServiceApi(serviceHost, { name: 'serviceHost', major: 1 })
|
|
39
|
+
|
|
40
|
+
const workbench = createRspWorkbench({
|
|
41
|
+
toolHost, serviceHost,
|
|
42
|
+
config: { mountPath, version: config.version || '0.1.0', hostDir },
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
const webServer = safeGet(ctx, 'webServer')
|
|
46
|
+
|
|
47
|
+
// 前缀路由全局唯一:先探占位,冲突只警告退出本条目,绝不把路由冲突升级成宿主崩溃。
|
|
48
|
+
if (webServer && typeof webServer.register === 'function') {
|
|
49
|
+
let taken = false
|
|
50
|
+
try {
|
|
51
|
+
const probe = webServer.register({ kind: 'prefix', path: mountPath, handler: () => {} })
|
|
52
|
+
if (typeof probe === 'function') probe()
|
|
53
|
+
} catch { taken = true }
|
|
54
|
+
if (taken) {
|
|
55
|
+
log.warn(`rsp-workbench: 路由前缀 ${mountPath} 已被占用,本条目不挂载(不影响其它插件)`)
|
|
56
|
+
return () => {}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const listenOpts = webServer ? { webServer, basePath: mountPath } : { port: config.port || 0 }
|
|
61
|
+
const listening = workbench.app.listen(listenOpts)
|
|
62
|
+
if (listening && typeof listening.catch === 'function') {
|
|
63
|
+
listening.catch((err) => {
|
|
64
|
+
log.warn(`rsp-workbench: 挂载 ${mountPath} 失败,本条目不生效:`, err?.message || err)
|
|
65
|
+
try { workbench.app.close() } catch { /* 忽略 */ }
|
|
66
|
+
})
|
|
67
|
+
}
|
|
68
|
+
disposers.push(() => workbench.app.close())
|
|
69
|
+
disposers.push(() => { workbench.manager.close().catch(() => {}) })
|
|
70
|
+
|
|
71
|
+
// 会话模式守卫:非 read 工具执行前把「调用者会话」钉到 rsp 工作台
|
|
72
|
+
// (与 ppt/browser/canvas 同语义)。认领成功后 portal-hud 会把查看器摆到主区,
|
|
73
|
+
// 于是 AI 一动手,人在主区就能看到实时画面并随时介入。
|
|
74
|
+
bindToolsToSessionMode(workbench.registry, { getWorkStore: () => safeGet(ctx, 'workStore') })
|
|
75
|
+
|
|
76
|
+
// 原生工具面:safeGet 解析 tools 服务后传平对象,避免 cordis 未 inject 禁访问 ctx.tools。
|
|
77
|
+
const tools = safeGet(ctx, 'tools')
|
|
78
|
+
if (tools?.register) {
|
|
79
|
+
const { registerWithDsh } = toolHost
|
|
80
|
+
disposers.push(registerWithDsh({ tools }, workbench.registry))
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// 持久化连接态:激活即连记住的 active 目标(进程级常驻、跨会话共享、掉线退避重试)。
|
|
84
|
+
// 新会话/宿主重启后 rsp_status 与主区查看器缺省即「已连接」,无需每次 rsp_connect。
|
|
85
|
+
try { workbench.manager.startPersistent() } catch (e) { log.warn('rsp-workbench: 常驻连接启动失败:', e?.message || e) }
|
|
86
|
+
|
|
87
|
+
workbench.publishDescriptors(workbench.app.url, { validate: validateCapabilityDescriptor })
|
|
88
|
+
disposers.push(() => { for (const d of RSP_DESCRIPTORS) toolHost.unregisterCapabilityDescriptor?.(d.name) })
|
|
89
|
+
|
|
90
|
+
if (webServer?.register) {
|
|
91
|
+
const p = `${mountPath}/__host__`
|
|
92
|
+
const off = webServer.register({
|
|
93
|
+
kind: 'exact', path: p,
|
|
94
|
+
handler: (req, res) => {
|
|
95
|
+
res.writeHead(200, { 'content-type': 'application/json' })
|
|
96
|
+
res.end(JSON.stringify({ ok: true, name, mountPath, url: workbench.app.url, protocol: 'rsp/1', status: workbench.manager.status() }))
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
if (typeof off === 'function') disposers.push(off)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const portal = safeGet(ctx, 'portal')
|
|
103
|
+
portal?.recordActivity?.({ id: 'rsp-workbench', url: workbench.app.url, title: 'RSP 远程屏幕工作台', kind: 'service' })
|
|
104
|
+
|
|
105
|
+
log.info(`rsp-workbench 已挂载 ${mountPath} → ${workbench.app.url}`)
|
|
106
|
+
return () => { for (const d of disposers.reverse()) { try { d() } catch { /* 忽略重复释放 */ } } }
|
|
107
|
+
} catch (err) {
|
|
108
|
+
log.warn('rsp-workbench 激活失败:', err?.stack || err)
|
|
109
|
+
return () => { for (const d of disposers.reverse()) { try { d() } catch { /* noop */ } } }
|
|
110
|
+
}
|
|
111
|
+
}
|