@capyclaw/rsp-suite 0.1.0 → 0.1.1
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/dsh-suite.json +13 -3
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +72 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/ledger.mjs +151 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/contract/rsp-contract.json +102 -13
- package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/skills/remote-screen/SKILL.md +13 -2
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/contract/capabilities.json +32 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/client.mjs +238 -11
- package/node_modules/@capyclaw/rsp-workbench/lib/host.mjs +51 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/tools.mjs +116 -16
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/workbench.mjs +21 -2
- package/node_modules/@capyclaw/rsp-workbench/plugin.mjs +17 -0
- package/{workbench → node_modules/@capyclaw/rsp-workbench}/ui/index.html +113 -10
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +597 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/suite-kit/README.md +289 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
- package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
- package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
- package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
- package/node_modules/@capyclaw/suite-kit/package.json +58 -0
- package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
- package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
- package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
- package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
- package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
- package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
- package/node_modules/@capyclaw/suite-kit/src/host.mjs +251 -0
- package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
- package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
- package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
- package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
- package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
- package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
- package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
- package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
- package/node_modules/ws/LICENSE +20 -0
- package/node_modules/ws/README.md +539 -0
- package/node_modules/ws/browser.js +8 -0
- package/node_modules/ws/index.js +22 -0
- package/node_modules/ws/lib/buffer-util.js +142 -0
- package/node_modules/ws/lib/constants.js +19 -0
- package/node_modules/ws/lib/event-target.js +292 -0
- package/node_modules/ws/lib/extension.js +203 -0
- package/node_modules/ws/lib/limiter.js +55 -0
- package/node_modules/ws/lib/permessage-deflate.js +530 -0
- package/node_modules/ws/lib/receiver.js +751 -0
- package/node_modules/ws/lib/sender.js +610 -0
- package/node_modules/ws/lib/stream.js +161 -0
- package/node_modules/ws/lib/subprotocol.js +62 -0
- package/node_modules/ws/lib/validation.js +152 -0
- package/node_modules/ws/lib/websocket-server.js +562 -0
- package/node_modules/ws/lib/websocket.js +1440 -0
- package/node_modules/ws/package.json +74 -0
- package/node_modules/ws/wrapper.mjs +21 -0
- package/package.json +22 -9
- package/workbench/lib/host.mjs +0 -111
- package/workbench/plugin.mjs +0 -2
- package/workbench/scripts/build-contract.mjs +0 -41
- package/workbench/scripts/drive.mjs +0 -66
- package/workbench/test/client.test.mjs +0 -218
- package/workbench/test/frames-prune.test.mjs +0 -49
- package/workbench/test/h264.test.mjs +0 -101
- package/workbench/test/live-persistent-smoke.mjs +0 -29
- package/workbench/test/live-smoke.mjs +0 -109
- package/workbench/test/mock-server.mjs +0 -194
- package/workbench/test/persistence.test.mjs +0 -177
- package/workbench/test/persistent.test.mjs +0 -160
- package/workbench/test/session-mode.test.mjs +0 -118
- package/workbench/test/workbench.test.mjs +0 -385
- package/workbench/verify-e2e.mjs +0 -44
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/README.md +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/cordis.patch.yml +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/package.json +0 -0
- /package/{skill → node_modules/@capyclaw/rsp-skill-remote-screen}/plugin.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/descriptors.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/manager.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/lib/session-mode.mjs +0 -0
- /package/{workbench → node_modules/@capyclaw/rsp-workbench}/package.json +0 -0
|
@@ -20,6 +20,24 @@ const ACK_TIMEOUT_MS = 5000
|
|
|
20
20
|
const MOVE_MIN_GAP_MS = 16 // §5.1 合并 move ≤ 60/s
|
|
21
21
|
const RECONNECT_MIN_MS = 1000 // §8 退避 1s→5s
|
|
22
22
|
const RECONNECT_MAX_MS = 5000
|
|
23
|
+
const KEY_CODES = new Set([
|
|
24
|
+
...Array.from({ length: 26 }, (_, i) => 'Key' + String.fromCharCode(65 + i)),
|
|
25
|
+
...Array.from({ length: 10 }, (_, i) => 'Digit' + i),
|
|
26
|
+
'Minus', 'Equal', 'BracketLeft', 'BracketRight', 'Backslash', 'Semicolon', 'Quote', 'Comma', 'Period', 'Slash', 'Backquote',
|
|
27
|
+
'Enter', 'Tab', 'Space', 'Backspace', 'Escape', 'CapsLock', 'Delete', 'Insert', 'Home', 'End', 'PageUp', 'PageDown',
|
|
28
|
+
'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'ShiftLeft', 'ShiftRight', 'ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'MetaLeft', 'MetaRight',
|
|
29
|
+
...Array.from({ length: 20 }, (_, i) => 'F' + (i + 1)), ...Array.from({ length: 10 }, (_, i) => 'Numpad' + i),
|
|
30
|
+
'NumpadDivide', 'NumpadMultiply', 'NumpadSubtract', 'NumpadAdd', 'NumpadEnter', 'NumpadDecimal',
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
// S4: 自动降档阶梯(低→高)。运行时调参只动 h264 通道三参;被控端按 features.quality 门控。
|
|
34
|
+
export const QUALITY_LADDER = [
|
|
35
|
+
{ bitrateKbps: 500, h264Fps: 15, h264MaxWidth: 960 }, // low
|
|
36
|
+
{ bitrateKbps: 1000, h264Fps: 30, h264MaxWidth: 1280 }, // smooth
|
|
37
|
+
{ bitrateKbps: 2000, h264Fps: 30, h264MaxWidth: 1920 }, // balanced
|
|
38
|
+
{ bitrateKbps: 4000, h264Fps: 60, h264MaxWidth: 1920 }, // hd
|
|
39
|
+
{ bitrateKbps: 8000, h264Fps: 60, h264MaxWidth: 3840 }, // uhd
|
|
40
|
+
]
|
|
23
41
|
|
|
24
42
|
/** 从 JPEG 字节解析像素尺寸(扫 SOF 段),无需图像库。返回 {width,height} 或 null。 */
|
|
25
43
|
export function jpegSize(buf) {
|
|
@@ -113,10 +131,15 @@ export class RspClient extends EventEmitter {
|
|
|
113
131
|
this.controlState = 'idle'
|
|
114
132
|
this.controlMode = 'ws' // ws|post
|
|
115
133
|
this._seq = 0
|
|
116
|
-
this._pending =
|
|
134
|
+
this._pending = new Map() // seq -> {seq,resolve,reject,timer}(流水线多事件在途)
|
|
117
135
|
this._pressedKeys = new Set()
|
|
118
136
|
this._pressedButtons = new Set()
|
|
119
137
|
this._lastMoveAt = 0
|
|
138
|
+
// S4: 操控 ack 往返时延(EMA α=0.2),供 status() 与自动降档用。
|
|
139
|
+
this._rttEma = 0
|
|
140
|
+
this._rttLast = 0
|
|
141
|
+
this._rttSamples = 0
|
|
142
|
+
this._aq = null // 自动降档状态(enableAutoQuality 开启)
|
|
120
143
|
this._screenRetry = 0
|
|
121
144
|
this._screenTimer = null
|
|
122
145
|
this._authFailed = false
|
|
@@ -282,11 +305,21 @@ export class RspClient extends EventEmitter {
|
|
|
282
305
|
ws.on('message', (data, isBinary) => {
|
|
283
306
|
if (isBinary) return
|
|
284
307
|
let msg; try { msg = JSON.parse(data.toString()) } catch { return }
|
|
285
|
-
if (msg.kind === 'ack'
|
|
286
|
-
const p = this._pending
|
|
308
|
+
if (msg.kind === 'ack') {
|
|
309
|
+
const p = this._pending.get(msg.seq)
|
|
310
|
+
if (p) {
|
|
311
|
+
this._pending.delete(msg.seq); clearTimeout(p.timer)
|
|
312
|
+
const rttMs = p.t0 != null ? performance.now() - p.t0 : null
|
|
313
|
+
if (rttMs != null) this._recordRtt(rttMs)
|
|
314
|
+
// 透传 quality 快照(cmd:'quality' 的 ack 携带),供 rsp_quality 回显。
|
|
315
|
+
p.resolve({ ok: true, seq: msg.seq, quality: msg.quality, batch: msg.batch, wake: msg.wake, rttMs })
|
|
316
|
+
}
|
|
287
317
|
} else if (msg.kind === 'error') {
|
|
288
|
-
const err = new Error(msg.message || 'bad_event'); err.code = msg.code || 'bad_event'
|
|
289
|
-
|
|
318
|
+
const err = new Error(msg.message || 'bad_event'); err.code = msg.code || 'bad_event'; if (msg.batch) err.batch = msg.batch
|
|
319
|
+
// Error frames carry no seq: reject the oldest in-flight event (FIFO), which
|
|
320
|
+
// is the one the agent rejected (it processes messages in arrival order).
|
|
321
|
+
const oldest = this._pending.keys().next().value
|
|
322
|
+
if (oldest != null) { const p = this._pending.get(oldest); this._pending.delete(oldest); clearTimeout(p.timer); p.reject(err) }
|
|
290
323
|
else this.emit('error', { code: err.code, message: err.message })
|
|
291
324
|
}
|
|
292
325
|
})
|
|
@@ -294,7 +327,7 @@ export class RspClient extends EventEmitter {
|
|
|
294
327
|
this.controlWs = null
|
|
295
328
|
// §5.5 被控端按连接自动补 up;本地状态同步清空
|
|
296
329
|
this._pressedKeys.clear(); this._pressedButtons.clear()
|
|
297
|
-
if (this._pending) { const p
|
|
330
|
+
if (this._pending.size) { for (const [, p] of this._pending) { clearTimeout(p.timer); p.reject(new Error(`control.ws 关闭(${code})`)) } this._pending.clear() }
|
|
298
331
|
if (this.closed) { this.controlState = 'closed'; return }
|
|
299
332
|
if (code === 4001) { this._authFailed = true; this.controlState = 'auth-error'; this.emit('auth-error', { channel: 'control' }); return }
|
|
300
333
|
if (code === 4003) { this.controlMode = 'post'; this.controlState = 'disabled'; return }
|
|
@@ -318,11 +351,92 @@ export class RspClient extends EventEmitter {
|
|
|
318
351
|
}
|
|
319
352
|
}
|
|
320
353
|
|
|
354
|
+
async sendBatch(events, options = {}) {
|
|
355
|
+
if (!Array.isArray(events) || events.length < 1 || events.length > 64) throw badArg('batch events must contain 1..64 events')
|
|
356
|
+
const moveIntervalMs = options.moveIntervalMs ?? 0
|
|
357
|
+
if (!Number.isInteger(moveIntervalMs) || moveIntervalMs < 0 || moveIntervalMs > 100) throw badArg('batch moveIntervalMs must be an integer in [0,100]')
|
|
358
|
+
const normalizeOne = (ev) => {
|
|
359
|
+
if (ev?.cmd === 'key' && Array.isArray(ev.modifiers) && ev.modifiers.length) {
|
|
360
|
+
const map = { cmd: 'MetaLeft', ctrl: 'ControlLeft', alt: 'AltLeft', shift: 'ShiftLeft' }
|
|
361
|
+
const mods = ev.modifiers.map((m) => map[m]).filter(Boolean)
|
|
362
|
+
if (!mods.length) return [ev]
|
|
363
|
+
return ev.action === 'down'
|
|
364
|
+
? [...mods.map((code) => ({ cmd: 'key', action: 'down', code })), { cmd: 'key', action: 'down', code: ev.code }]
|
|
365
|
+
: [{ cmd: 'key', action: 'up', code: ev.code }, ...[...mods].reverse().map((code) => ({ cmd: 'key', action: 'up', code }))]
|
|
366
|
+
}
|
|
367
|
+
return [ev]
|
|
368
|
+
}
|
|
369
|
+
const normalized = events.map(normalizeOne).flat()
|
|
370
|
+
const pressed = new Set(this._pressedKeys)
|
|
371
|
+
const buttons = new Set(this._pressedButtons)
|
|
372
|
+
for (const ev of normalized) {
|
|
373
|
+
if (!ev || !['key', 'mouse', 'text'].includes(ev.cmd)) throw badArg('unsupported batch event')
|
|
374
|
+
if (ev.cmd === 'text' && (typeof ev.text !== 'string' || ev.text.length > MAX_TEXT_UNITS)) throw badArg('text too long')
|
|
375
|
+
if (ev.cmd === 'key') {
|
|
376
|
+
if (!['down', 'up'].includes(ev.action) || !KEY_CODES.has(ev.code)) throw badArg('bad key event')
|
|
377
|
+
if (ev.action === 'down') pressed.add(ev.code); else pressed.delete(ev.code)
|
|
378
|
+
}
|
|
379
|
+
if (ev.cmd === 'mouse') {
|
|
380
|
+
if (!['move', 'down', 'up', 'click', 'scroll'].includes(ev.action) || (ev.action !== 'scroll' && (!Number.isFinite(ev.x) || !Number.isFinite(ev.y)))) throw badArg('bad mouse event')
|
|
381
|
+
const b = ev.button || 'left'
|
|
382
|
+
if (ev.action === 'down') buttons.add(b); else if (ev.action === 'up' || ev.action === 'click') buttons.delete(b)
|
|
383
|
+
}
|
|
384
|
+
const bytes = Buffer.byteLength(JSON.stringify(ev), 'utf8')
|
|
385
|
+
if (bytes > MAX_EVENT_BYTES) throw badArg('事件超过 64KiB')
|
|
386
|
+
}
|
|
387
|
+
if (Buffer.byteLength(JSON.stringify({ events: normalized }), 'utf8') > 60000) throw badArg('batch payload exceeds 60KiB')
|
|
388
|
+
if (this.closed || this._authFailed) throw badArg('client unavailable')
|
|
389
|
+
// Preserve held-input tracking across a failed batch ack; the batch may have
|
|
390
|
+
// reached the agent even if its response was lost.
|
|
391
|
+
this._pressedKeys = pressed
|
|
392
|
+
this._pressedButtons = buttons
|
|
393
|
+
try {
|
|
394
|
+
let result
|
|
395
|
+
try {
|
|
396
|
+
result = await this.sendEvent({ cmd: 'batch', events: normalized, ...(moveIntervalMs ? { moveIntervalMs } : {}) })
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (err.batch?.processed != null && err.batch.processed !== normalized.length) {
|
|
399
|
+
err.code = 'partial_batch'
|
|
400
|
+
err.message = `helper processed ${err.batch.processed}/${normalized.length} batch events${err.message ? `: ${err.message}` : ''}`
|
|
401
|
+
}
|
|
402
|
+
throw err
|
|
403
|
+
}
|
|
404
|
+
if (result.batch?.processed != null && result.batch.processed !== normalized.length) {
|
|
405
|
+
const e = new Error(`helper processed ${result.batch.processed}/${normalized.length} batch events`)
|
|
406
|
+
e.batch = result.batch
|
|
407
|
+
e.code = 'partial_batch'
|
|
408
|
+
throw e
|
|
409
|
+
}
|
|
410
|
+
return { ...result, count: normalized.length, batched: true }
|
|
411
|
+
} catch (err) {
|
|
412
|
+
// Older RSP/1 agents reject unknown cmd:'batch' before injection; safely
|
|
413
|
+
// fall back only for that explicit validation response, never on timeout.
|
|
414
|
+
if (err?.code !== 'bad_event') throw err
|
|
415
|
+
for (const ev of normalized) await this.sendEvent(ev)
|
|
416
|
+
return { ok: true, count: normalized.length, via: 'ws', batched: false, fallback: true }
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
321
420
|
/** 注入一个事件(自包含)。mouse move 限速;key/mouse 记录按下态。返回 {ok,seq?,via}。 */
|
|
322
421
|
async sendEvent(ev) {
|
|
323
422
|
if (this.closed) throw badArg('client 已关闭')
|
|
324
423
|
if (this._authFailed) { const e = new Error('鉴权失败,请重新提供令牌'); e.code = 'unauthorized'; throw e }
|
|
325
424
|
if (!ev || typeof ev !== 'object' || !ev.cmd) throw badArg('事件必须含 cmd')
|
|
425
|
+
// 快捷键修饰键展开:被控端助手只认物理键码(不解析 modifiers),所以控制端把
|
|
426
|
+
// modifiers 拆成真实的修饰键 down/up 事件。down=先按修饰键再按主键;up=先抬主键
|
|
427
|
+
// 再抬修饰键(逆序),与「down KeyA modifiers=[cmd] 再 up」的成对用法吻合。
|
|
428
|
+
if (ev.cmd === 'key' && Array.isArray(ev.modifiers) && ev.modifiers.length) {
|
|
429
|
+
const MODCODE = { cmd: 'MetaLeft', ctrl: 'ControlLeft', alt: 'AltLeft', shift: 'ShiftLeft' }
|
|
430
|
+
const mods = ev.modifiers.map((m) => MODCODE[m]).filter(Boolean)
|
|
431
|
+
const main = { cmd: 'key', action: ev.action, code: ev.code }
|
|
432
|
+
if (ev.action === 'down') {
|
|
433
|
+
for (const c of mods) await this.sendEvent({ cmd: 'key', action: 'down', code: c })
|
|
434
|
+
return await this.sendEvent(main)
|
|
435
|
+
}
|
|
436
|
+
const r = await this.sendEvent(main)
|
|
437
|
+
for (const c of [...mods].reverse()) await this.sendEvent({ cmd: 'key', action: 'up', code: c })
|
|
438
|
+
return r
|
|
439
|
+
}
|
|
326
440
|
// move 限速(§5.1 ≤60/s)
|
|
327
441
|
if (ev.cmd === 'mouse' && ev.action === 'move') {
|
|
328
442
|
const wait = this._lastMoveAt + MOVE_MIN_GAP_MS - Date.now()
|
|
@@ -345,20 +459,27 @@ export class RspClient extends EventEmitter {
|
|
|
345
459
|
const payload = { ...ev, seq }
|
|
346
460
|
return new Promise((resolve, reject) => {
|
|
347
461
|
const timer = setTimeout(() => {
|
|
348
|
-
|
|
462
|
+
const p = this._pending.get(seq)
|
|
463
|
+
if (p) { this._pending.delete(seq); reject(new Error('ack 超时(5s)')) }
|
|
349
464
|
}, ACK_TIMEOUT_MS)
|
|
350
|
-
|
|
465
|
+
// Pipelined control: multiple events may be in flight at once, each matched by
|
|
466
|
+
// seq. The old single _pending slot serialized bursts (a rapid move stream or
|
|
467
|
+
// click+move waited one full ack RTT per event). The agent already processes
|
|
468
|
+
// messages concurrently and acks per-seq, so a Map is safe and lowers RTT.
|
|
469
|
+
this._pending.set(seq, { seq, resolve, reject, timer, t0: performance.now() })
|
|
351
470
|
try { this.controlWs.send(JSON.stringify(payload)) }
|
|
352
|
-
catch (err) { this._pending
|
|
471
|
+
catch (err) { this._pending.delete(seq); clearTimeout(timer); reject(err) }
|
|
353
472
|
})
|
|
354
473
|
}
|
|
355
474
|
|
|
356
475
|
async _sendPost(ev) {
|
|
476
|
+
const t0 = performance.now()
|
|
357
477
|
const res = await this.fetch(this._url('/control'), {
|
|
358
478
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(ev),
|
|
359
479
|
})
|
|
360
480
|
let body = null; try { body = await res.json() } catch { /* ignore */ }
|
|
361
|
-
|
|
481
|
+
this._recordRtt(performance.now() - t0)
|
|
482
|
+
if (res.status === 200 && body && body.ok) return { ok: true, quality: body.quality, wake: body.wake }
|
|
362
483
|
const code = body?.error?.code || httpCodeToError(res.status)
|
|
363
484
|
const err = new Error(body?.error?.message || `POST /control 返回 ${res.status}`)
|
|
364
485
|
err.code = code; throw err
|
|
@@ -382,6 +503,107 @@ export class RspClient extends EventEmitter {
|
|
|
382
503
|
for (const button of buttons) { try { await this.sendEvent({ cmd: 'mouse', action: 'up', x: 0, y: 0, button }) } catch { /* best effort */ } }
|
|
383
504
|
}
|
|
384
505
|
|
|
506
|
+
_recordRtt(ms) {
|
|
507
|
+
if (!(ms >= 0)) return
|
|
508
|
+
this._rttLast = ms
|
|
509
|
+
this._rttSamples++
|
|
510
|
+
this._rttEma = this._rttEma ? this._rttEma * 0.8 + ms * 0.2 : ms
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* S1: 运行时画质调参(被控端原子换档,画面不中断)。仅 h264 通道三参 + jpeg 三参。
|
|
515
|
+
* 被控端不支持(features.quality=false,旧版 agent)时抛 unsupported。返回 ack 的 quality 快照。
|
|
516
|
+
*/
|
|
517
|
+
async setQuality(params = {}) {
|
|
518
|
+
if (!this.info?.features?.quality) { const e = new Error('被控端不支持运行时调参(features.quality)'); e.code = 'unsupported'; throw e }
|
|
519
|
+
const ev = { cmd: 'quality' }
|
|
520
|
+
for (const k of ['bitrateKbps', 'h264Fps', 'h264MaxWidth', 'jpegFps', 'jpegQuality', 'maxWidth']) {
|
|
521
|
+
if (typeof params[k] === 'number' && Number.isFinite(params[k])) ev[k] = params[k]
|
|
522
|
+
}
|
|
523
|
+
if (Object.keys(ev).length === 1) throw badArg('至少提供一个画质参数')
|
|
524
|
+
const r = await this.sendEvent(ev)
|
|
525
|
+
// Keep the cached info snapshot live so rsp_status/status() reflects the applied quality.
|
|
526
|
+
if (r?.quality && this.info) this.info.quality = r.quality
|
|
527
|
+
// 手动换档后同步自动降档的当前档位,避免 auto 从旧档继续阶梯。手动抬高时把基线
|
|
528
|
+
// 也抬到新档(用户的手动选择成为新的恢复上限);并清零延迟累计防止立刻误触发。
|
|
529
|
+
if (this._aq && r?.quality && typeof r.quality.bitrateKbps === 'number') {
|
|
530
|
+
const lvl = this._levelForBitrate(r.quality.bitrateKbps)
|
|
531
|
+
this._aq.level = lvl
|
|
532
|
+
if (lvl > this._aq.baselineLevel) this._aq.baselineLevel = lvl
|
|
533
|
+
this._aq.highSince = 0
|
|
534
|
+
this._aq.lowSince = 0
|
|
535
|
+
}
|
|
536
|
+
return r
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 强制唤醒被控端显示器(点亮已息屏/睡眠的屏幕)。需被控端 features.wake(新版 agent)。
|
|
541
|
+
* 旧 agent 不支持时抛 unsupported。holdMs=点亮后保持唤醒的毫秒数(0..30000,默认 2000)。
|
|
542
|
+
* 返回 { ok, wake:{platform,method,holdMs,ok,error?}, via }。
|
|
543
|
+
*/
|
|
544
|
+
async wake(opts = {}) {
|
|
545
|
+
if (!this.info?.features?.wake) { const e = new Error('被控端不支持强制唤醒(features.wake)'); e.code = 'unsupported'; throw e }
|
|
546
|
+
const ev = { cmd: 'wake' }
|
|
547
|
+
if (typeof opts.holdMs === 'number' && Number.isFinite(opts.holdMs)) ev.holdMs = opts.holdMs
|
|
548
|
+
const r = await this.sendEvent(ev)
|
|
549
|
+
return { ok: r?.wake?.ok !== false, wake: r?.wake ?? null, via: r.via }
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** 阶梯中码率不超过 bitrate 的最高档索引。 */
|
|
553
|
+
_levelForBitrate(bitrate) {
|
|
554
|
+
let lvl = 0
|
|
555
|
+
for (let i = 0; i < QUALITY_LADDER.length; i++) if (QUALITY_LADDER[i].bitrateKbps <= bitrate) lvl = i
|
|
556
|
+
return lvl
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* S4: 自动降档(opt-in)。以操控 ack RTT 为信号:持续高延迟→沿阶梯降一档;持续健康→
|
|
561
|
+
* 升回但不超过启用时的基线。仅在被控端支持 features.quality 时生效。RTT 由操控流量驱动,
|
|
562
|
+
* 纯观看(无输入)时不更新——此时可手动 rsp_quality。
|
|
563
|
+
*/
|
|
564
|
+
enableAutoQuality(opts = {}) {
|
|
565
|
+
if (!this.info?.features?.quality) { const e = new Error('被控端不支持运行时调参,无法自动降档'); e.code = 'unsupported'; throw e }
|
|
566
|
+
this.disableAutoQuality()
|
|
567
|
+
const o = {
|
|
568
|
+
highRttMs: opts.highRttMs ?? 200,
|
|
569
|
+
lowRttMs: opts.lowRttMs ?? 120,
|
|
570
|
+
degradeAfterMs: opts.degradeAfterMs ?? 5000,
|
|
571
|
+
recoverAfterMs: opts.recoverAfterMs ?? 30000,
|
|
572
|
+
tickMs: opts.tickMs ?? 1000,
|
|
573
|
+
}
|
|
574
|
+
const baseline = this.info?.quality ?? null
|
|
575
|
+
// 基线档位:阶梯中码率不超过基线的最高档(无基线时从 balanced 起)。
|
|
576
|
+
let baselineLevel = 2
|
|
577
|
+
if (baseline && typeof baseline.bitrateKbps === 'number') baselineLevel = this._levelForBitrate(baseline.bitrateKbps)
|
|
578
|
+
const aq = { opts: o, baseline, baselineLevel, level: baselineLevel, highSince: 0, lowSince: 0, changes: 0, timer: null }
|
|
579
|
+
aq.timer = setInterval(() => this._aqTick(), o.tickMs)
|
|
580
|
+
aq.timer.unref?.()
|
|
581
|
+
this._aq = aq
|
|
582
|
+
return { enabled: true, baselineLevel, level: aq.level }
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
disableAutoQuality() {
|
|
586
|
+
if (this._aq?.timer) clearInterval(this._aq.timer)
|
|
587
|
+
this._aq = null
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
_aqTick() {
|
|
591
|
+
const aq = this._aq
|
|
592
|
+
if (!aq || this.closed || this._authFailed) return
|
|
593
|
+
const rtt = this._rttEma
|
|
594
|
+
const step = aq.opts.tickMs
|
|
595
|
+
if (rtt > aq.opts.highRttMs) aq.highSince += step; else aq.highSince = 0
|
|
596
|
+
if (rtt > 0 && rtt < aq.opts.lowRttMs) aq.lowSince += step; else aq.lowSince = 0
|
|
597
|
+
let next = null
|
|
598
|
+
if (aq.highSince >= aq.opts.degradeAfterMs && aq.level > 0) { next = aq.level - 1; aq.highSince = 0 }
|
|
599
|
+
else if (aq.lowSince >= aq.opts.recoverAfterMs && aq.level < aq.baselineLevel) { next = aq.level + 1; aq.lowSince = 0 }
|
|
600
|
+
if (next == null) return
|
|
601
|
+
aq.level = next
|
|
602
|
+
aq.changes++
|
|
603
|
+
this.setQuality(QUALITY_LADDER[next]).catch((e) => this.log('autoQuality 调参失败:' + e.message))
|
|
604
|
+
this.emit('auto-quality', { level: next, quality: QUALITY_LADDER[next], rttEma: +rtt.toFixed(1) })
|
|
605
|
+
}
|
|
606
|
+
|
|
385
607
|
/** 等待一帧比 since 更新的帧(fresh 截图用)。超时返回最近帧。 */
|
|
386
608
|
async waitFrame(since = Date.now(), timeoutMs = 2000) {
|
|
387
609
|
if (this.lastFrame && this.lastFrame.at >= since) return this.lastFrame
|
|
@@ -405,6 +627,10 @@ export class RspClient extends EventEmitter {
|
|
|
405
627
|
controlState: this.controlState,
|
|
406
628
|
controlMode: this.controlMode,
|
|
407
629
|
controlEnabled: this.info?.control?.enabled ?? null,
|
|
630
|
+
controlRttMs: { ema: +this._rttEma.toFixed(1), last: +this._rttLast.toFixed(1), samples: this._rttSamples },
|
|
631
|
+
quality: this.info?.quality ?? null,
|
|
632
|
+
features: this.info?.features ?? null,
|
|
633
|
+
autoQuality: this._aq ? { enabled: true, level: this._aq.level, baselineLevel: this._aq.baselineLevel, changes: this._aq.changes } : { enabled: false },
|
|
408
634
|
hello: this.hello,
|
|
409
635
|
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
636
|
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,
|
|
@@ -425,10 +651,11 @@ export class RspClient extends EventEmitter {
|
|
|
425
651
|
|
|
426
652
|
async disconnect() {
|
|
427
653
|
if (this.closed) return
|
|
654
|
+
this.disableAutoQuality()
|
|
428
655
|
try { await this.releaseAll() } catch { /* best effort */ }
|
|
429
656
|
this.closed = true
|
|
430
657
|
if (this._screenTimer) { clearTimeout(this._screenTimer); this._screenTimer = null }
|
|
431
|
-
if (this._pending) { const p
|
|
658
|
+
if (this._pending.size) { for (const [, p] of this._pending) { clearTimeout(p.timer); p.reject(new Error('client 关闭')) } this._pending.clear() }
|
|
432
659
|
try { this.screenWs?.close(1000) } catch { /* ignore */ }
|
|
433
660
|
try { this.controlWs?.close(1000) } catch { /* ignore */ }
|
|
434
661
|
try { this.h264Ws?.close(1000) } catch { /* ignore */ }
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rsp-workbench cordis 宿主入口:把可单测核心接进 DSH。
|
|
3
|
+
* 公共胶水(safeGet/断言/缺服务降级/probe 兜底/__host__/portal/工具注册/描述符/逆序释放)
|
|
4
|
+
* 收敛到 @capyclaw/suite-kit/host 的 mountSuiteWorkbench(P1-9);本文件只保留 rsp 差异:
|
|
5
|
+
* manager.close disposer、会话模式守卫 bindToolsToSessionMode、常驻连接 startPersistent、
|
|
6
|
+
* __host__.protocol/status 字段。路由冲突只警告退出本条目,绝不升级为宿主崩溃。
|
|
7
|
+
*/
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { mountSuiteWorkbench, resolveWorkStore } from '@capyclaw/suite-kit/host'
|
|
11
|
+
import { createRspWorkbench } from './workbench.mjs'
|
|
12
|
+
import { RSP_DESCRIPTORS } from './descriptors.mjs'
|
|
13
|
+
import { bindToolsToSessionMode } from './session-mode.mjs'
|
|
14
|
+
|
|
15
|
+
export const name = 'rsp-workbench'
|
|
16
|
+
export const inject = ['webServer']
|
|
17
|
+
|
|
18
|
+
export function apply(ctx, config = {}) {
|
|
19
|
+
const hostDir = config.hostDir || path.join(os.homedir(), '.dsh-rsp')
|
|
20
|
+
return mountSuiteWorkbench(ctx, config, {
|
|
21
|
+
ns: name,
|
|
22
|
+
suite: 'rsp',
|
|
23
|
+
mountPath: '/capyclaw/rsp',
|
|
24
|
+
title: 'RSP 远程屏幕工作台',
|
|
25
|
+
descriptors: RSP_DESCRIPTORS,
|
|
26
|
+
// 原实现无条件 publish(不探测 registerCapabilityDescriptor),保持等价。
|
|
27
|
+
descriptorsRequired: true,
|
|
28
|
+
|
|
29
|
+
createWorkbench: ({ toolHost, serviceHost, config, mountPath }) => createRspWorkbench({
|
|
30
|
+
toolHost, serviceHost,
|
|
31
|
+
config: { mountPath, version: config.version || '0.1.0', hostDir },
|
|
32
|
+
}),
|
|
33
|
+
|
|
34
|
+
afterListen: ({ ctx, workbench, push }) => {
|
|
35
|
+
push(() => { workbench.manager.close().catch(() => {}) })
|
|
36
|
+
// 会话模式守卫:非 read 工具执行前把「调用者会话」钉到 rsp 工作台
|
|
37
|
+
// (与 ppt/browser/canvas 同语义)。认领成功后 portal-hud 会把查看器摆到主区,
|
|
38
|
+
// 于是 AI 一动手,人在主区就能看到实时画面并随时介入。
|
|
39
|
+
// workStore 可选:优先 foundation os.works 能力面,回退裸服务;缺席跳过守卫。
|
|
40
|
+
bindToolsToSessionMode(workbench.registry, { getWorkStore: () => resolveWorkStore(ctx) })
|
|
41
|
+
},
|
|
42
|
+
|
|
43
|
+
afterTools: ({ workbench, log }) => {
|
|
44
|
+
// 持久化连接态:激活即连记住的 active 目标(进程级常驻、跨会话共享、掉线退避重试)。
|
|
45
|
+
// 新会话/宿主重启后 rsp_status 与主区查看器缺省即「已连接」,无需每次 rsp_connect。
|
|
46
|
+
try { workbench.manager.startPersistent() } catch (e) { log.warn('rsp-workbench: 常驻连接启动失败:', e?.message || e) }
|
|
47
|
+
},
|
|
48
|
+
|
|
49
|
+
hostInfo: (workbench) => ({ protocol: 'rsp/1', status: workbench.manager.status() }),
|
|
50
|
+
})
|
|
51
|
+
}
|
|
@@ -18,6 +18,16 @@ const MODIFIERS = new Set(['cmd', 'ctrl', 'alt', 'shift'])
|
|
|
18
18
|
const MOUSE_ACTIONS = new Set(['move', 'down', 'up', 'click', 'scroll'])
|
|
19
19
|
const BUTTONS = new Set(['left', 'right', 'middle'])
|
|
20
20
|
|
|
21
|
+
// S1: 画质档位(与 client.mjs QUALITY_LADDER 对齐)。preset 选档,显式参数覆盖。
|
|
22
|
+
const QUALITY_PRESETS = {
|
|
23
|
+
low: { bitrateKbps: 500, h264Fps: 15, h264MaxWidth: 960 },
|
|
24
|
+
smooth: { bitrateKbps: 1000, h264Fps: 30, h264MaxWidth: 1280 },
|
|
25
|
+
balanced: { bitrateKbps: 2000, h264Fps: 30, h264MaxWidth: 1920 },
|
|
26
|
+
hd: { bitrateKbps: 4000, h264Fps: 60, h264MaxWidth: 1920 },
|
|
27
|
+
uhd: { bitrateKbps: 8000, h264Fps: 60, h264MaxWidth: 3840 },
|
|
28
|
+
}
|
|
29
|
+
const QUALITY_KNOBS = ['bitrateKbps', 'h264Fps', 'h264MaxWidth', 'jpegFps', 'jpegQuality', 'maxWidth']
|
|
30
|
+
|
|
21
31
|
// ---- 输出辅助 ----
|
|
22
32
|
function ok(text, extra) { return { content: [{ type: 'text', text }], isError: false, ...(extra || {}) } }
|
|
23
33
|
function okBlocks(blocks) { return { content: blocks, isError: false } }
|
|
@@ -36,6 +46,7 @@ function hintFor(code) {
|
|
|
36
46
|
no_frame: '先调用 rsp_screen 获取画面,再用帧像素坐标操控。',
|
|
37
47
|
no_dimensions: '尚未收到 hello/info 尺寸;先 rsp_screen 或 rsp_status。',
|
|
38
48
|
bad_event: '检查事件字段是否符合 RSP/1 §5。',
|
|
49
|
+
unsupported: '被控端为旧版 agent,不支持运行时调参/自动降档;升级 rsp-agent-win 并重启宿主后重试。',
|
|
39
50
|
})[code] || ''
|
|
40
51
|
}
|
|
41
52
|
|
|
@@ -220,6 +231,11 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
220
231
|
const a = args || {}
|
|
221
232
|
if (a.fresh) await client.waitFrame(Date.now(), a.waitMs ?? 2000)
|
|
222
233
|
else if (!client.lastFrame) await client.waitFrame(Date.now(), a.waitMs ?? 2000)
|
|
234
|
+
// 黑屏自愈:仍无帧且被控端支持强制唤醒 → 唤醒后再等一帧。
|
|
235
|
+
// (新 agent 在观众接入黑屏时已自动唤醒;此处兜底连接时序/旧连接。)
|
|
236
|
+
if (!client.lastFrame && client.info?.features?.wake) {
|
|
237
|
+
try { await client.wake(); await client.waitFrame(Date.now(), a.waitMs ?? 3000) } catch { /* best effort */ }
|
|
238
|
+
}
|
|
223
239
|
return await screenResult(client, manager, { save: a.save })
|
|
224
240
|
} catch (e) { return errToResult(e) }
|
|
225
241
|
},
|
|
@@ -292,13 +308,14 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
292
308
|
|
|
293
309
|
const dragTool = defineTool({
|
|
294
310
|
name: 'rsp_drag', kind: 'write', since,
|
|
295
|
-
description: '拖拽:从 (fromX,fromY) 按住拖到 (toX,toY) 再抬起,中间插值 move
|
|
311
|
+
description: '拖拽:从 (fromX,fromY) 按住拖到 (toX,toY) 再抬起,中间插值 move(拖拽语义)。一次批量发送;默认 moveIntervalMs=16 提供约 60Hz 平滑轨迹。坐标默认最近帧像素(space=frame)。steps 默认 12,最大 60。',
|
|
296
312
|
inputSchema: {
|
|
297
313
|
type: 'object',
|
|
298
314
|
properties: {
|
|
299
315
|
fromX: { type: 'number' }, fromY: { type: 'number' }, toX: { type: 'number' }, toY: { type: 'number' },
|
|
300
316
|
steps: { type: 'integer', description: '中间 move 步数 2…60,默认 12' },
|
|
301
317
|
button: { type: 'string', enum: ['left', 'right', 'middle'], description: '默认 left' },
|
|
318
|
+
moveIntervalMs: { type: 'integer', description: '每个中间 move 后的被控端等待,0–100ms;默认 16ms,最长累计等待 2s' },
|
|
302
319
|
space: { type: 'string', enum: ['frame', 'logical'], description: '默认 frame' },
|
|
303
320
|
},
|
|
304
321
|
required: ['fromX', 'fromY', 'toX', 'toY'], additionalProperties: false,
|
|
@@ -312,25 +329,32 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
312
329
|
const to = toLogical(client, a.toX, a.toY, space)
|
|
313
330
|
const steps = clamp(Math.trunc(a.steps ?? 12), 2, 60)
|
|
314
331
|
const button = a.button || 'left'
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
332
|
+
const moveIntervalMs = a.moveIntervalMs ?? 16
|
|
333
|
+
if (!Number.isInteger(moveIntervalMs) || moveIntervalMs < 0 || moveIntervalMs > 100) return fail('bad_event', 'moveIntervalMs 必须是 0–100 的整数')
|
|
334
|
+
if (steps * moveIntervalMs > 2000) return fail('bad_event', 'drag pacing duration exceeds 2000ms')
|
|
335
|
+
const events = [
|
|
336
|
+
{ cmd: 'mouse', action: 'down', x: from.x, y: from.y, button },
|
|
337
|
+
...Array.from({ length: steps }, (_, i) => {
|
|
338
|
+
const t = (i + 1) / steps
|
|
339
|
+
return { cmd: 'mouse', action: 'move', x: from.x + (to.x - from.x) * t, y: from.y + (to.y - from.y) * t, button }
|
|
340
|
+
}),
|
|
341
|
+
{ cmd: 'mouse', action: 'up', x: to.x, y: to.y, button },
|
|
342
|
+
]
|
|
343
|
+
const r = await client.sendBatch(events, { moveIntervalMs })
|
|
344
|
+
return ok(JSON.stringify({ ok: true, from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y }, steps, button, moveIntervalMs, batched: r.batched }))
|
|
322
345
|
} catch (e) { return errToResult(e) }
|
|
323
346
|
},
|
|
324
347
|
})
|
|
325
348
|
|
|
326
349
|
const batchTool = defineTool({
|
|
327
350
|
name: 'rsp_batch', kind: 'write', since,
|
|
328
|
-
description: '
|
|
351
|
+
description: '按序提交多个输入事件,通常一次控制确认。连续鼠标轨迹可设 moveIntervalMs(0–100ms)让被控端按节奏注入;最多 64 个事件、总节奏等待不超过 2s。gapMs>0 仍可选逐事件 ACK 间隔;screenshot=true 末尾抓帧。',
|
|
329
352
|
inputSchema: {
|
|
330
353
|
type: 'object',
|
|
331
354
|
properties: {
|
|
332
355
|
events: { type: 'array', description: '事件数组(mouse/key/text)', items: { type: 'object' } },
|
|
333
|
-
|
|
356
|
+
moveIntervalMs: { type: 'integer', description: 'batch 内每个鼠标 move 后的等待,0–100ms;最多累计 2s。用于连续轨迹,默认 0' },
|
|
357
|
+
gapMs: { type: 'integer', description: '兼容模式:逐事件发送时的间隔毫秒,默认 0' },
|
|
334
358
|
screenshot: { type: 'boolean', description: '末尾抓一帧新画面,默认 false' },
|
|
335
359
|
space: { type: 'string', enum: ['frame', 'logical'], description: 'mouse 坐标空间默认值,默认 frame' },
|
|
336
360
|
},
|
|
@@ -343,15 +367,30 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
343
367
|
const events = Array.isArray(a.events) ? a.events : []
|
|
344
368
|
if (!events.length) return fail('bad_event', 'events 不能为空')
|
|
345
369
|
const gap = Math.max(0, Math.trunc(a.gapMs ?? 0))
|
|
370
|
+
const moveIntervalMs = a.moveIntervalMs ?? 0
|
|
371
|
+
if (!Number.isInteger(moveIntervalMs) || moveIntervalMs < 0 || moveIntervalMs > 100) return fail('bad_event', 'moveIntervalMs 必须是 0–100 的整数')
|
|
346
372
|
const defaultSpace = a.space === 'logical' ? 'logical' : 'frame'
|
|
347
373
|
const injected = []
|
|
374
|
+
const normalized = []
|
|
375
|
+
if (events.length > 64) return fail('bad_event', 'batch 最多 64 个事件')
|
|
348
376
|
for (const raw of events) {
|
|
349
377
|
const withSpace = (raw && raw.cmd !== 'key' && raw.cmd !== 'text' && raw.space === undefined) ? { ...raw, space: defaultSpace } : raw
|
|
350
378
|
const ev = normalizeBatchEvent(withSpace, client)
|
|
351
|
-
if (ev.cmd === 'text') {
|
|
352
|
-
|
|
379
|
+
if (ev.cmd === 'text') {
|
|
380
|
+
for (const c of splitText(ev.text)) normalized.push({ cmd: 'text', text: c })
|
|
381
|
+
} else normalized.push(ev)
|
|
353
382
|
injected.push(ev.cmd + (ev.action ? ':' + ev.action : ''))
|
|
354
|
-
|
|
383
|
+
}
|
|
384
|
+
if (gap > 0 && moveIntervalMs > 0) return fail('bad_event', 'gapMs 与 moveIntervalMs 不能同时使用')
|
|
385
|
+
if (gap > 0) {
|
|
386
|
+
for (const ev of normalized) {
|
|
387
|
+
await client.sendEvent(ev)
|
|
388
|
+
await new Promise((r) => setTimeout(r, gap))
|
|
389
|
+
}
|
|
390
|
+
injected.splice(0, injected.length, ...normalized.map((ev) => ev.cmd + (ev.action ? ':' + ev.action : '')))
|
|
391
|
+
} else {
|
|
392
|
+
if (normalized.filter((ev) => ev.cmd === 'mouse' && ev.action === 'move').length * moveIntervalMs > 2000) return fail('bad_event', 'batch pacing duration exceeds 2000ms')
|
|
393
|
+
await client.sendBatch(normalized, { moveIntervalMs })
|
|
355
394
|
}
|
|
356
395
|
if (a.screenshot) {
|
|
357
396
|
await client.waitFrame(Date.now(), 2000)
|
|
@@ -363,6 +402,67 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
363
402
|
},
|
|
364
403
|
})
|
|
365
404
|
|
|
405
|
+
const qualityTool = defineTool({
|
|
406
|
+
name: 'rsp_quality', kind: 'control', since,
|
|
407
|
+
description: '运行时调节被控端画质(原子换档,画面不中断)。preset 选档(low/smooth/balanced/hd/uhd),或用显式 bitrateKbps/h264Fps/h264MaxWidth/jpegFps/jpegQuality/maxWidth 覆盖。auto=true 开启按操控 RTT 自动降档(持续高延迟降一档、持续健康升回、不超基线),auto=false 关闭。需被控端支持 features.quality(新版 agent)。返回生效画质快照 + 当前 RTT。',
|
|
408
|
+
inputSchema: {
|
|
409
|
+
type: 'object',
|
|
410
|
+
properties: {
|
|
411
|
+
preset: { type: 'string', enum: ['low', 'smooth', 'balanced', 'hd', 'uhd'], description: '画质档位' },
|
|
412
|
+
bitrateKbps: { type: 'number', description: 'h264 码率 100–50000 kbps' },
|
|
413
|
+
h264Fps: { type: 'number', description: 'h264 帧率 1–120' },
|
|
414
|
+
h264MaxWidth: { type: 'number', description: 'h264 最大宽 320–7680(gpuDirect 原生分辨率下忽略)' },
|
|
415
|
+
jpegFps: { type: 'number', description: 'JPEG 帧率 1–120' },
|
|
416
|
+
jpegQuality: { type: 'number', description: 'JPEG 质量 1–31(越小越好)' },
|
|
417
|
+
maxWidth: { type: 'number', description: 'JPEG 最大宽 320–7680' },
|
|
418
|
+
auto: { type: 'boolean', description: 'true=开启自动降档,false=关闭;省略则不变' },
|
|
419
|
+
},
|
|
420
|
+
additionalProperties: false,
|
|
421
|
+
},
|
|
422
|
+
handler: async (args, ctx) => {
|
|
423
|
+
try {
|
|
424
|
+
const client = await manager.requireClient(sessionFromExec(ctx))
|
|
425
|
+
const a = args || {}
|
|
426
|
+
if (a.auto === true) client.enableAutoQuality()
|
|
427
|
+
else if (a.auto === false) client.disableAutoQuality()
|
|
428
|
+
const params = { ...(a.preset ? QUALITY_PRESETS[a.preset] : {}) }
|
|
429
|
+
for (const k of QUALITY_KNOBS) if (typeof a[k] === 'number') params[k] = a[k]
|
|
430
|
+
let quality
|
|
431
|
+
if (Object.keys(params).length) { const r = await client.setQuality(params); quality = r.quality ?? null }
|
|
432
|
+
else { const fresh = await client.fetchInfo(); quality = fresh.quality ?? null }
|
|
433
|
+
const st = client.status()
|
|
434
|
+
return ok(JSON.stringify({ ok: true, quality, autoQuality: st.autoQuality, controlRttMs: st.controlRttMs }))
|
|
435
|
+
} catch (e) { return errToResult(e) }
|
|
436
|
+
},
|
|
437
|
+
})
|
|
438
|
+
|
|
439
|
+
const wakeTool = defineTool({
|
|
440
|
+
name: 'rsp_wake', kind: 'control', since,
|
|
441
|
+
description: '强制唤醒被控端显示器:点亮已息屏/睡眠的屏幕(macOS caffeinate -u / Windows 一次性 SetThreadExecutionState),随后保持防熄屏。与「防熄屏」不同——它能唤不醒已经黑屏的设备。需被控端 features.wake(新版 agent),旧 agent 报 unsupported。holdMs=点亮后保持唤醒毫秒数(0–30000,默认 2000)。抓帧前若画面黑屏可先调它;新 agent 在观众接入黑屏时也会自动唤醒。screenshot=true 唤醒后抓帧验证。返回唤醒结果快照。',
|
|
442
|
+
inputSchema: {
|
|
443
|
+
type: 'object',
|
|
444
|
+
properties: {
|
|
445
|
+
holdMs: { type: 'integer', description: '点亮后保持唤醒的毫秒数 0–30000,默认 2000' },
|
|
446
|
+
screenshot: { type: 'boolean', description: '唤醒后抓一帧新画面验证,默认 false' },
|
|
447
|
+
waitMs: { type: 'integer', description: 'screenshot 时等待新帧的上限毫秒,默认 3000' },
|
|
448
|
+
},
|
|
449
|
+
additionalProperties: false,
|
|
450
|
+
},
|
|
451
|
+
handler: async (args, ctx) => {
|
|
452
|
+
try {
|
|
453
|
+
const client = await manager.requireClient(sessionFromExec(ctx))
|
|
454
|
+
const a = args || {}
|
|
455
|
+
const r = await client.wake({ holdMs: a.holdMs })
|
|
456
|
+
if (a.screenshot) {
|
|
457
|
+
await client.waitFrame(Date.now(), a.waitMs ?? 3000)
|
|
458
|
+
const sr = await screenResult(client, manager, { save: true })
|
|
459
|
+
return okBlocks([{ type: 'text', text: JSON.stringify({ ok: r.ok, wake: r.wake, via: r.via }) }, ...sr.content])
|
|
460
|
+
}
|
|
461
|
+
return ok(JSON.stringify({ ok: r.ok, wake: r.wake, via: r.via }))
|
|
462
|
+
} catch (e) { return errToResult(e) }
|
|
463
|
+
},
|
|
464
|
+
})
|
|
465
|
+
|
|
366
466
|
return [
|
|
367
467
|
defineCapability({
|
|
368
468
|
id: 'rsp.session', title: 'RSP 会话', description: '连接/断开被控端、查看契约与状态。',
|
|
@@ -376,10 +476,10 @@ export function createRspCapabilities({ toolHost, manager, config = {} }) {
|
|
|
376
476
|
features: ['screen'], tools: [screenTool],
|
|
377
477
|
}),
|
|
378
478
|
defineCapability({
|
|
379
|
-
id: 'rsp.control', title: 'RSP 操控', description: '
|
|
479
|
+
id: 'rsp.control', title: 'RSP 操控', description: '向被控端注入鼠标/键盘/文本/拖拽/批量输入(只写),运行时调节画质,并强制唤醒已息屏的显示器。',
|
|
380
480
|
tags: ['rsp', 'remote-screen', 'control'], requires: [], provides: {},
|
|
381
|
-
features: ['mouse', 'key', 'text', 'drag', 'batch'],
|
|
382
|
-
tools: [mouseTool, keyTool, textTool, dragTool, batchTool],
|
|
481
|
+
features: ['mouse', 'key', 'text', 'drag', 'batch', 'quality', 'wake'],
|
|
482
|
+
tools: [mouseTool, keyTool, textTool, dragTool, batchTool, qualityTool, wakeTool],
|
|
383
483
|
}),
|
|
384
484
|
]
|
|
385
485
|
}
|
|
@@ -24,6 +24,25 @@ function statusFor(code) {
|
|
|
24
24
|
return 500
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/**
|
|
28
|
+
* H.264 代理背压:浏览器消费慢时 res 缓冲无界增长会拖垮工作台进程内存。
|
|
29
|
+
* 超过上限即断开该慢消费者(对齐被控端 agent 侧 64MB terminate 策略),
|
|
30
|
+
* 而非无条件 res.write。导出以便单测。
|
|
31
|
+
* @param {object} res node ServerResponse(需 writableLength/write/destroy)
|
|
32
|
+
* @param {() => void} cleanup 摘监听并结束响应
|
|
33
|
+
* @param {number} [maxBuffered] 缓冲上限字节
|
|
34
|
+
*/
|
|
35
|
+
export function h264ProxyChunk(res, cleanup, maxBuffered = 64 * 1024 * 1024) {
|
|
36
|
+
return (chunk) => {
|
|
37
|
+
if (res.writableLength > maxBuffered) {
|
|
38
|
+
cleanup();
|
|
39
|
+
try { res.destroy() } catch { /* ignore */ }
|
|
40
|
+
return
|
|
41
|
+
}
|
|
42
|
+
try { res.write(chunk) } catch { /* ignore */ }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
27
46
|
/**
|
|
28
47
|
* @param {{ toolHost:object, serviceHost:object, manager?:object,
|
|
29
48
|
* config?:{ mountPath?:string, version?:string, uiDir?:string, hostDir?:string } }} deps
|
|
@@ -143,9 +162,9 @@ export function createRspWorkbench({ toolHost, serviceHost, manager, config = {}
|
|
|
143
162
|
}
|
|
144
163
|
res.writeHead(200, { 'content-type': 'application/octet-stream', 'cache-control': 'no-store', 'x-rsp-format': 'h264' })
|
|
145
164
|
for (const head of client.h264Head) { try { res.write(head) } catch { /* ignore */ } }
|
|
146
|
-
const onChunk = (chunk) => { try { res.write(chunk) } catch { /* ignore */ } }
|
|
147
|
-
client.on('h264', onChunk)
|
|
148
165
|
const cleanup = () => { client.off('h264', onChunk); try { res.end() } catch { /* ignore */ } }
|
|
166
|
+
const onChunk = h264ProxyChunk(res, cleanup)
|
|
167
|
+
client.on('h264', onChunk)
|
|
149
168
|
// 只监听 res close:Node 里 req 的 'close' 在请求体读完即触发(GET 无体→立刻),
|
|
150
169
|
// 监听它会把长连接流在发完 head 后马上掐断。
|
|
151
170
|
res.on('close', cleanup)
|