@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,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSP 连接管理器:每会话独立 RspClient + 跨会话共享的「目标保险库」。
|
|
3
|
+
* 范式对齐 browser-suite 的 login-vault / session-engines:
|
|
4
|
+
* - 共享的是「记住的连接信息」(别名/基址/令牌,可复制可合并),不是连接本身;
|
|
5
|
+
* 一个被控端同一时刻可被多个会话各自连一条通道,互不抢画面。
|
|
6
|
+
* - 每个会话(调用者 session id)持有自己的 client;无会话上下文的调用方
|
|
7
|
+
* (HTTP/MCP/查看器)落在 DEFAULT_BUCKET,互不干扰。
|
|
8
|
+
* - 保险库落盘 hostDir/targets.json:带版本、原子写(tmp+rename)、合并而非覆盖、
|
|
9
|
+
* v1 单目标格式自动迁移;会话首次动作时按其记住的目标懒自动重连(如同登录态注入)。
|
|
10
|
+
*
|
|
11
|
+
* 安全边界:令牌与 browser login-vault 的 cookie 同级明文落盘(hostDir 为用户本机目录),
|
|
12
|
+
* 不扩大暴露面但也不应同步到任何共享位置;DSH_RSP_TARGET_VAULT=false 可整机关闭持久化。
|
|
13
|
+
* 无 cordis 依赖。
|
|
14
|
+
*/
|
|
15
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync, renameSync } from 'node:fs'
|
|
16
|
+
import path from 'node:path'
|
|
17
|
+
import { RspClient, normalizeBase, maskToken } from './client.mjs'
|
|
18
|
+
|
|
19
|
+
export const VAULT_VERSION = 2
|
|
20
|
+
/** 无会话上下文调用方(HTTP/MCP/GUI 默认)的桶名。 */
|
|
21
|
+
export const DEFAULT_BUCKET = '__default__'
|
|
22
|
+
/** 进程级常驻连接桶:激活即连记住的 active 目标,跨会话共享、掉线自动重试。 */
|
|
23
|
+
export const PERSISTENT_BUCKET = '__persistent__'
|
|
24
|
+
const MAX_TARGETS = 50
|
|
25
|
+
const MAX_SESSIONS = 200
|
|
26
|
+
|
|
27
|
+
export function vaultEnabled() { return process.env.DSH_RSP_TARGET_VAULT !== 'false' }
|
|
28
|
+
|
|
29
|
+
/** 读保险库;缺失/损坏/版本不符都收敛成空库或迁移结果,绝不抛。 */
|
|
30
|
+
export function loadVault(file) {
|
|
31
|
+
const empty = { version: VAULT_VERSION, targets: {}, sessions: {}, active: null, updatedAt: null }
|
|
32
|
+
if (!file || !existsSync(file)) return empty
|
|
33
|
+
try {
|
|
34
|
+
const data = JSON.parse(readFileSync(file, 'utf8'))
|
|
35
|
+
if (!data || typeof data !== 'object') return empty
|
|
36
|
+
if (data.version === VAULT_VERSION) {
|
|
37
|
+
return {
|
|
38
|
+
version: VAULT_VERSION,
|
|
39
|
+
targets: data.targets && typeof data.targets === 'object' ? data.targets : {},
|
|
40
|
+
sessions: data.sessions && typeof data.sessions === 'object' ? data.sessions : {},
|
|
41
|
+
active: typeof data.active === 'string' ? data.active : null,
|
|
42
|
+
updatedAt: data.updatedAt || null,
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// v1:{active:{name,baseUrl,token},updatedAt} → 迁移成单目标库(落盘留给下次 persist)
|
|
46
|
+
if (data.active && data.active.baseUrl && data.active.token) {
|
|
47
|
+
const at = data.updatedAt || new Date().toISOString()
|
|
48
|
+
const t = { name: data.active.name || data.active.baseUrl, baseUrl: data.active.baseUrl, token: data.active.token, savedAt: at, lastUsedAt: at }
|
|
49
|
+
return { version: VAULT_VERSION, targets: { [t.name]: t }, sessions: {}, active: t.name, updatedAt: data.updatedAt || null }
|
|
50
|
+
}
|
|
51
|
+
return empty
|
|
52
|
+
} catch { return empty }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 原子写(tmp+rename);关闭持久化或无 hostDir 时静默跳过。 */
|
|
56
|
+
export function saveVault(file, vault) {
|
|
57
|
+
if (!file || !vaultEnabled()) return false
|
|
58
|
+
try {
|
|
59
|
+
mkdirSync(path.dirname(file), { recursive: true })
|
|
60
|
+
const tmp = `${file}.tmp`
|
|
61
|
+
writeFileSync(tmp, JSON.stringify({ ...vault, version: VAULT_VERSION, updatedAt: new Date().toISOString() }, null, 2))
|
|
62
|
+
renameSync(tmp, file)
|
|
63
|
+
return true
|
|
64
|
+
} catch { return false }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function pruneVault(v) {
|
|
68
|
+
const names = Object.keys(v.targets)
|
|
69
|
+
if (names.length > MAX_TARGETS) {
|
|
70
|
+
const referenced = new Set([...Object.values(v.sessions), v.active])
|
|
71
|
+
const drop = names
|
|
72
|
+
.filter((n) => !referenced.has(n))
|
|
73
|
+
.sort((a, b) => String(v.targets[a].lastUsedAt || '').localeCompare(String(v.targets[b].lastUsedAt || '')))
|
|
74
|
+
for (const n of drop.slice(0, names.length - MAX_TARGETS)) delete v.targets[n]
|
|
75
|
+
}
|
|
76
|
+
const sids = Object.keys(v.sessions)
|
|
77
|
+
if (sids.length > MAX_SESSIONS) for (const s of sids.slice(0, sids.length - MAX_SESSIONS)) delete v.sessions[s]
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export class RspManager {
|
|
81
|
+
constructor({ hostDir, logger, fetchImpl, WebSocketImpl, clientFactory } = {}) {
|
|
82
|
+
this.hostDir = hostDir || null
|
|
83
|
+
this.log = logger || (() => {})
|
|
84
|
+
this.fetchImpl = fetchImpl
|
|
85
|
+
this.WebSocketImpl = WebSocketImpl
|
|
86
|
+
this.clientFactory = clientFactory || ((opts) => new RspClient(opts))
|
|
87
|
+
this.clients = new Map() // bucket(session id) -> RspClient
|
|
88
|
+
this.bindings = new Map() // bucket -> {name,baseUrl,token}(内存真源,与 vault.sessions 同步)
|
|
89
|
+
this.paused = new Set() // 本进程内显式 disconnect 过的桶:不懒自动重连,直到再次 connect
|
|
90
|
+
this.activeSession = DEFAULT_BUCKET
|
|
91
|
+
this._persistentWanted = false
|
|
92
|
+
this._persistentTimer = null
|
|
93
|
+
this._persistentRetry = 0
|
|
94
|
+
this.vault = loadVault(this._file())
|
|
95
|
+
for (const [sid, name] of Object.entries(this.vault.sessions)) {
|
|
96
|
+
const t = this.vault.targets[name]
|
|
97
|
+
if (t) this.bindings.set(sid, { name: t.name, baseUrl: t.baseUrl, token: t.token })
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
_file() { return this.hostDir ? path.join(this.hostDir, 'targets.json') : null }
|
|
102
|
+
|
|
103
|
+
/** 兼容旧读法:当前活动会话「自己的」连接/目标(不含常驻回落,disconnect 语义保持)。 */
|
|
104
|
+
get client() { return this.clients.get(this.activeSession) || null }
|
|
105
|
+
get target() {
|
|
106
|
+
const t = this.bindings.get(this.activeSession)
|
|
107
|
+
if (t) return t
|
|
108
|
+
return this.vault.active ? this.vault.targets[this.vault.active] || null : null
|
|
109
|
+
}
|
|
110
|
+
get connected() { const c = this.client; return !!c && !c.closed && c.screenState === 'open' }
|
|
111
|
+
|
|
112
|
+
/** 查看器/路由取某会话的 client;本会话无活连接时回落常驻连接(持久化连接态)。只读。 */
|
|
113
|
+
clientFor(sid) { return this.clients.get(sid || DEFAULT_BUCKET) || this.clients.get(PERSISTENT_BUCKET) || null }
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 连接目标。解析顺序:显式 url/host(+token,缺省复用同基址的记忆令牌) →
|
|
117
|
+
* 记忆别名 name → 本会话记住的目标 → 库 active。无参=重连本会话上次目标。
|
|
118
|
+
* 只断开/替换本会话桶的旧连接,绝不动其它会话。返回 {info,status}。
|
|
119
|
+
*/
|
|
120
|
+
async connect(args = {}, sidRaw) {
|
|
121
|
+
const sid = sidRaw || DEFAULT_BUCKET
|
|
122
|
+
const v = this.vault
|
|
123
|
+
let baseUrl, token, name
|
|
124
|
+
if (args.url || args.host) {
|
|
125
|
+
baseUrl = normalizeBase({ url: args.url, host: args.host, port: args.port })
|
|
126
|
+
const known = Object.values(v.targets).find((t) => t.baseUrl === baseUrl)
|
|
127
|
+
token = args.token || (known && known.token)
|
|
128
|
+
if (!token) { const e = new Error('新目标必须提供 token(或改用已记住的别名 name)'); e.code = 'bad_event'; throw e }
|
|
129
|
+
name = args.name || (known && known.name) || baseUrl
|
|
130
|
+
} else if (args.name) {
|
|
131
|
+
const t = v.targets[args.name]
|
|
132
|
+
if (!t) { const e = new Error(`没有记住名为 ${args.name} 的目标;可用 rsp_status 查看 remembered.targets`); e.code = 'no_target'; throw e }
|
|
133
|
+
baseUrl = t.baseUrl; name = t.name; token = args.token || t.token
|
|
134
|
+
} else {
|
|
135
|
+
const t = this.bindings.get(sid) || (v.active && v.targets[v.active]) || null
|
|
136
|
+
if (!t) { const e = new Error('未配置目标:请提供 url/host + token,或 name 选用已记住目标'); e.code = 'no_target'; throw e }
|
|
137
|
+
baseUrl = t.baseUrl; name = t.name; token = args.token || t.token
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const old = this.clients.get(sid)
|
|
141
|
+
if (old) { try { await old.disconnect() } catch { /* ignore */ } this.clients.delete(sid) }
|
|
142
|
+
|
|
143
|
+
const client = this.clientFactory({ baseUrl, token, fetchImpl: this.fetchImpl, WebSocketImpl: this.WebSocketImpl, logger: this.log })
|
|
144
|
+
client.on('auth-error', (d) => this.log('鉴权失败:' + JSON.stringify(d)))
|
|
145
|
+
client.on('error', (e) => this.log('client error:' + (e.message || JSON.stringify(e))))
|
|
146
|
+
const info = await client.connect()
|
|
147
|
+
this.clients.set(sid, client)
|
|
148
|
+
this.bindings.set(sid, { name, baseUrl, token })
|
|
149
|
+
this.paused.delete(sid)
|
|
150
|
+
this.activeSession = sid
|
|
151
|
+
if (args.persist !== false) {
|
|
152
|
+
const prev = v.targets[name]
|
|
153
|
+
const now = new Date().toISOString()
|
|
154
|
+
v.targets[name] = { name, baseUrl, token, savedAt: (prev && prev.savedAt) || now, lastUsedAt: now }
|
|
155
|
+
v.sessions[sid] = name
|
|
156
|
+
v.active = name
|
|
157
|
+
pruneVault(v)
|
|
158
|
+
if (!saveVault(this._file(), v)) this.log('targets.json 未写入(无 hostDir 或持久化已关闭)')
|
|
159
|
+
}
|
|
160
|
+
if (this._persistentWanted) void this._tickPersistent() // active 目标可能变化,常驻连接跟随
|
|
161
|
+
return { info, status: this.status(sid) }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 取本会话 client;没有活连接时优先复用进程级常驻连接(持久化连接态),
|
|
165
|
+
* 本会话记了不同目标才单独建连。本进程内显式 disconnect 过的桶不自动重连。 */
|
|
166
|
+
async requireClient(sidRaw) {
|
|
167
|
+
const sid = sidRaw || DEFAULT_BUCKET
|
|
168
|
+
const c = this.clients.get(sid)
|
|
169
|
+
if (c && !c.closed) { this.activeSession = sid; return c }
|
|
170
|
+
if (c) this.clients.delete(sid)
|
|
171
|
+
if (this.paused.has(sid)) { const e = new Error('本会话已断开:调用 rsp_connect 重连(可无参)'); e.code = 'not_connected'; throw e }
|
|
172
|
+
const b = this.bindings.get(sid) || null
|
|
173
|
+
const p = this.clients.get(PERSISTENT_BUCKET) || null
|
|
174
|
+
const pb = this.bindings.get(PERSISTENT_BUCKET) || null
|
|
175
|
+
// 本会话记住的目标与常驻连接相同(或本会话无绑定)→ 直接复用常驻连接,不重复建通道
|
|
176
|
+
if (p && !p.closed && (!b || (pb && pb.baseUrl === b.baseUrl))) { this.activeSession = sid; return p }
|
|
177
|
+
if (b) {
|
|
178
|
+
await this.connect({ url: b.baseUrl, token: b.token, name: b.name }, sid)
|
|
179
|
+
return this.clients.get(sid)
|
|
180
|
+
}
|
|
181
|
+
if (!this._persistentWanted) this.startPersistent()
|
|
182
|
+
if (!this._persistentTarget() && !this.clients.get(PERSISTENT_BUCKET)) {
|
|
183
|
+
const e = new Error('尚未连接:请先调用 rsp_connect(提供 url/host + token,或 name 选已记住目标)')
|
|
184
|
+
e.code = 'not_connected'
|
|
185
|
+
throw e
|
|
186
|
+
}
|
|
187
|
+
const ready = await this._waitPersistent(6000)
|
|
188
|
+
if (ready) { this.activeSession = sid; return ready }
|
|
189
|
+
const e = new Error('尚未连接:请先调用 rsp_connect(提供 url/host + token,或 name 选已记住目标)')
|
|
190
|
+
e.code = 'not_connected'
|
|
191
|
+
throw e
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// ---- 进程级常驻连接(持久化连接态) ----
|
|
195
|
+
/** 激活时调用:立即连记住的 active 目标;离线/掉线按退避自动重试,跨会话共享。 */
|
|
196
|
+
startPersistent() {
|
|
197
|
+
if (!vaultEnabled()) return
|
|
198
|
+
this._persistentWanted = true
|
|
199
|
+
this._persistentRetry = 0
|
|
200
|
+
void this._tickPersistent()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
stopPersistent() {
|
|
204
|
+
this._persistentWanted = false
|
|
205
|
+
if (this._persistentTimer) { clearTimeout(this._persistentTimer); this._persistentTimer = null }
|
|
206
|
+
const c = this.clients.get(PERSISTENT_BUCKET)
|
|
207
|
+
if (c) { try { c.disconnect() } catch { /* ignore */ } this.clients.delete(PERSISTENT_BUCKET) }
|
|
208
|
+
this.bindings.delete(PERSISTENT_BUCKET)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
_persistentTarget() { return this.vault.active ? (this.vault.targets[this.vault.active] || null) : null }
|
|
212
|
+
|
|
213
|
+
_schedulePersistent(delay) {
|
|
214
|
+
if (!this._persistentWanted) return
|
|
215
|
+
if (this._persistentTimer) clearTimeout(this._persistentTimer)
|
|
216
|
+
this._persistentTimer = setTimeout(() => { this._persistentTimer = null; void this._tickPersistent() }, delay)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async _tickPersistent() {
|
|
220
|
+
if (!this._persistentWanted) return
|
|
221
|
+
const t = this._persistentTarget()
|
|
222
|
+
if (!t) { this._schedulePersistent(5000); return }
|
|
223
|
+
const existing = this.clients.get(PERSISTENT_BUCKET)
|
|
224
|
+
if (existing && !existing.closed) {
|
|
225
|
+
const b = this.bindings.get(PERSISTENT_BUCKET)
|
|
226
|
+
// 同目标且未鉴权失败:活着或正在自愈(client 自带退避重连),不重建
|
|
227
|
+
if (b && b.baseUrl === t.baseUrl && !existing._authFailed) return
|
|
228
|
+
try { await existing.disconnect() } catch { /* ignore */ }
|
|
229
|
+
this.clients.delete(PERSISTENT_BUCKET)
|
|
230
|
+
}
|
|
231
|
+
const client = this.clientFactory({ baseUrl: t.baseUrl, token: t.token, fetchImpl: this.fetchImpl, WebSocketImpl: this.WebSocketImpl, logger: this.log })
|
|
232
|
+
client.on('auth-error', (d) => this.log('常驻连接鉴权失败:' + JSON.stringify(d)))
|
|
233
|
+
client.on('error', (e) => this.log('常驻连接 error:' + (e.message || JSON.stringify(e))))
|
|
234
|
+
try {
|
|
235
|
+
await client.connect()
|
|
236
|
+
} catch (e) {
|
|
237
|
+
try { await client.disconnect() } catch { /* ignore */ }
|
|
238
|
+
const permanent = e.code === 'unauthorized' || e.code === 'protocol_mismatch' || e.code === 'unsupported_format'
|
|
239
|
+
if (permanent) { this._persistentWanted = false; this.log('常驻连接停止(永久错误):' + e.message); return }
|
|
240
|
+
this._schedulePersistent(Math.min(30000, 1000 * Math.pow(2, this._persistentRetry++)))
|
|
241
|
+
return
|
|
242
|
+
}
|
|
243
|
+
this._persistentRetry = 0
|
|
244
|
+
this.clients.set(PERSISTENT_BUCKET, client)
|
|
245
|
+
this.bindings.set(PERSISTENT_BUCKET, { name: t.name, baseUrl: t.baseUrl, token: t.token })
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** 轮询等待常驻连接就绪(screen open);超时返回 null。 */
|
|
249
|
+
async _waitPersistent(ms) {
|
|
250
|
+
const deadline = Date.now() + ms
|
|
251
|
+
for (;;) {
|
|
252
|
+
const c = this.clients.get(PERSISTENT_BUCKET)
|
|
253
|
+
if (c && !c.closed && c.screenState === 'open') return c
|
|
254
|
+
if (Date.now() >= deadline) return null
|
|
255
|
+
await new Promise((r) => setTimeout(r, 200))
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
async disconnect({ forget = false } = {}, sidRaw) {
|
|
260
|
+
const sid = sidRaw || DEFAULT_BUCKET
|
|
261
|
+
if (sid === PERSISTENT_BUCKET) { this.stopPersistent(); return { ok: true, status: this.status(sid) } }
|
|
262
|
+
const c = this.clients.get(sid)
|
|
263
|
+
if (c) { try { await c.disconnect() } catch { /* ignore */ } this.clients.delete(sid) }
|
|
264
|
+
this.paused.add(sid)
|
|
265
|
+
if (forget) {
|
|
266
|
+
const t = this.bindings.get(sid)
|
|
267
|
+
this.bindings.delete(sid)
|
|
268
|
+
delete this.vault.sessions[sid]
|
|
269
|
+
if (t) {
|
|
270
|
+
const stillUsed = Object.values(this.vault.sessions).includes(t.name) || [...this.bindings.values()].some((x) => x.name === t.name)
|
|
271
|
+
if (!stillUsed) delete this.vault.targets[t.name]
|
|
272
|
+
if (this.vault.active === t.name) this.vault.active = stillUsed ? t.name : (Object.keys(this.vault.targets)[0] || null)
|
|
273
|
+
}
|
|
274
|
+
saveVault(this._file(), this.vault)
|
|
275
|
+
}
|
|
276
|
+
if (this._persistentWanted) void this._tickPersistent() // forget 可能改变 active 目标
|
|
277
|
+
return { ok: true, status: this.status(sid) }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** 记忆面(令牌掩码):供 rsp_status / 查看器下拉使用。 */
|
|
281
|
+
remembered() {
|
|
282
|
+
return {
|
|
283
|
+
active: this.vault.active,
|
|
284
|
+
targets: Object.values(this.vault.targets).map((t) => ({ name: t.name, baseUrl: t.baseUrl, token: maskToken(t.token), savedAt: t.savedAt || null, lastUsedAt: t.lastUsedAt || null })),
|
|
285
|
+
sessions: { ...this.vault.sessions },
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** 活连接清单:供查看器选择观看哪个会话。 */
|
|
290
|
+
sessions() {
|
|
291
|
+
return [...this.clients.entries()].map(([sid, c]) => {
|
|
292
|
+
const t = this.bindings.get(sid) || null
|
|
293
|
+
return {
|
|
294
|
+
session: sid,
|
|
295
|
+
target: t ? t.name : null,
|
|
296
|
+
baseUrl: t ? t.baseUrl : null,
|
|
297
|
+
connected: !c.closed && c.screenState === 'open',
|
|
298
|
+
lastFrame: c.lastFrame ? { width: c.lastFrame.width, height: c.lastFrame.height, at: c.lastFrame.at } : null,
|
|
299
|
+
}
|
|
300
|
+
})
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
status(sidRaw) {
|
|
304
|
+
const view = sidRaw || DEFAULT_BUCKET
|
|
305
|
+
let client = this.clients.get(view) || null
|
|
306
|
+
let viaPersistent = false
|
|
307
|
+
if (!client && !this.paused.has(view)) {
|
|
308
|
+
const p = this.clients.get(PERSISTENT_BUCKET)
|
|
309
|
+
if (p && !p.closed) { client = p; viaPersistent = true }
|
|
310
|
+
}
|
|
311
|
+
const target = this.bindings.get(view) || (viaPersistent ? this.bindings.get(PERSISTENT_BUCKET) : null) || (this.vault.active && this.vault.targets[this.vault.active]) || null
|
|
312
|
+
const pc = this.clients.get(PERSISTENT_BUCKET) || null
|
|
313
|
+
return {
|
|
314
|
+
configured: !!target,
|
|
315
|
+
target: target ? { name: target.name, baseUrl: target.baseUrl, token: maskToken(target.token) } : null,
|
|
316
|
+
connected: !!client && !client.closed && client.screenState === 'open',
|
|
317
|
+
client: client ? client.status() : null,
|
|
318
|
+
session: sidRaw || null,
|
|
319
|
+
activeSession: this.activeSession,
|
|
320
|
+
viaPersistent,
|
|
321
|
+
persistent: { wanted: this._persistentWanted, connected: !!pc && !pc.closed && pc.screenState === 'open' },
|
|
322
|
+
remembered: this.remembered(),
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
async close() {
|
|
327
|
+
this.stopPersistent()
|
|
328
|
+
for (const [sid, c] of [...this.clients.entries()]) {
|
|
329
|
+
try { await c.disconnect() } catch { /* ignore */ }
|
|
330
|
+
this.clients.delete(sid)
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话工作台模式守卫 —— 与 ppt / canvas / browser 三个 bridge 同语义
|
|
3
|
+
* (见 @capyclaw/document-workbench/src/session/mode.mjs):
|
|
4
|
+
*
|
|
5
|
+
* - 一个会话只钉一个工作台种类,认领后终生固化(存储真源在 work-store 的
|
|
6
|
+
* claimSessionMode / getSessionMode,works.db 会话级记录);
|
|
7
|
+
* - 非 read 工具执行前认领本种类 'rsp',异种类硬拒(提示新开会话);
|
|
8
|
+
* - 认领成功后 GUI 主区(portal-hud)按 mode 自动摆上 RSP 查看器——这就是
|
|
9
|
+
* 「AI 一动手,人就能在主区看到实时画面」的实现路径。
|
|
10
|
+
*
|
|
11
|
+
* 为什么包在 TOOL_IMPL 层:DSH 原生工具面把执行上下文作为第二参传下来
|
|
12
|
+
* (registerWithDsh: execute(args, exec) → impl(args, exec)),
|
|
13
|
+
* exec.agent.session.id 才是「调用者会话」。MCP / HTTP 形态没有 exec,
|
|
14
|
+
* 此时不认领——不猜、不误锁别人的会话。
|
|
15
|
+
*/
|
|
16
|
+
const DEFAULT_KIND = 'rsp'
|
|
17
|
+
const CLAIMED_BY = 'rsp-workbench'
|
|
18
|
+
|
|
19
|
+
/** 从 DSH 工具执行上下文取调用者会话 id;拿不到返回空串。 */
|
|
20
|
+
export function sessionFromExec(exec) {
|
|
21
|
+
const sid = exec && exec.agent && exec.agent.session ? exec.agent.session.id : ''
|
|
22
|
+
return typeof sid === 'string' ? sid.trim() : ''
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 认领/校验(抛):异种类 → 抛 SESSION_MODE_LOCKED,带 lockedTo。底座缺席 → 跳过不报错。 */
|
|
26
|
+
export function assertSessionMode(sessionId, kind, getWorkStore) {
|
|
27
|
+
const ws = typeof getWorkStore === 'function' ? getWorkStore() : getWorkStore
|
|
28
|
+
if (!ws || typeof ws.claimSessionMode !== 'function') return { ok: true, skipped: true }
|
|
29
|
+
if (!sessionId) return { ok: true, skipped: true }
|
|
30
|
+
let result
|
|
31
|
+
try {
|
|
32
|
+
result = ws.claimSessionMode(sessionId, kind, CLAIMED_BY)
|
|
33
|
+
} catch {
|
|
34
|
+
/* 存储故障不该让操控整体不可用:降级为不认领(主区仍可从工作台列表手动打开)。 */
|
|
35
|
+
return { ok: true, skipped: true }
|
|
36
|
+
}
|
|
37
|
+
if (result && result.ok) return result
|
|
38
|
+
const lockedTo = (result && result.lockedTo) || ''
|
|
39
|
+
const error = new Error(
|
|
40
|
+
`本会话已固化为「${lockedTo}」工作台,不能在这里操控远程屏幕。要使用 RSP,请新开一个会话。`,
|
|
41
|
+
)
|
|
42
|
+
error.code = 'SESSION_MODE_LOCKED'
|
|
43
|
+
error.lockedTo = lockedTo
|
|
44
|
+
throw error
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 把 registry 里的非 read 工具包一层:执行前认领本会话的 rsp 模式。
|
|
49
|
+
* read 工具不包(读不受限)。重复调用幂等(__modeBound 标记)。
|
|
50
|
+
*/
|
|
51
|
+
export function bindToolsToSessionMode(registry, { getWorkStore, kind = DEFAULT_KIND } = {}) {
|
|
52
|
+
const impls = registry && registry.TOOL_IMPL
|
|
53
|
+
const meta = (registry && registry.TOOL_META) || {}
|
|
54
|
+
if (!impls || typeof impls !== 'object') return registry
|
|
55
|
+
for (const name of Object.keys(impls)) {
|
|
56
|
+
const impl = impls[name]
|
|
57
|
+
if (typeof impl !== 'function' || impl.__modeBound) continue
|
|
58
|
+
if ((meta[name] && meta[name].kind) === 'read') continue
|
|
59
|
+
const bound = async (args, exec) => {
|
|
60
|
+
const sid = sessionFromExec(exec)
|
|
61
|
+
if (sid) assertSessionMode(sid, kind, getWorkStore)
|
|
62
|
+
return impl(args, exec)
|
|
63
|
+
}
|
|
64
|
+
bound.__modeBound = true
|
|
65
|
+
impls[name] = bound
|
|
66
|
+
}
|
|
67
|
+
return registry
|
|
68
|
+
}
|