@tina_summer/codepocket 2.6.11 → 2.7.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.
@@ -0,0 +1,526 @@
1
+ /**
2
+ * ZCode live control via the official web-remote relay (ws2).
3
+ *
4
+ * Verified protocol (captured + replayed against ZCode 3.18.2):
5
+ * 1. JWT: ~/.zcode/v2/credentials.json['zcodejwttoken'] (enc:v2, AES-256-GCM
6
+ * with key from macOS Keychain "ZCode Credential Encryption"), or
7
+ * CODEPOCKET_ZCODE_JWT env, or ~/.codepocket/zcode-jwt.txt cache.
8
+ * 2. POST https://zcode.z.ai/api/v1/remote/token {role:"terminal"} → one-time token
9
+ * 3. wss://zcode.z.ai/api/v1/remote/ws2?token=…&mid=… → auth_init → auth_ack (matched)
10
+ * 4. bootstrap-request → workspaces; workspace-bridge-open → bridge
11
+ * 5. RPC frames (binary, see zcodeRpc.js) with relay-level seq + rpc-frame-ack
12
+ * 6. send: zcode-agent.sendConversationCommandV4 (envelope with type sendText)
13
+ *
14
+ * Note: the relay allows ONE terminal per device — connecting kicks the
15
+ * user's phone/browser remote session (and vice versa).
16
+ */
17
+ const { execSync } = require('child_process')
18
+ const crypto = require('crypto')
19
+ const fs = require('fs')
20
+ const os = require('os')
21
+ const path = require('path')
22
+
23
+ const { WebSocket } = require('ws')
24
+ const rpc = require('./zcodeRpc')
25
+
26
+ const ZCODE_HOME = path.join(os.homedir(), '.zcode')
27
+ const V2 = path.join(ZCODE_HOME, 'v2')
28
+ const RELAY_ORIGIN = 'https://zcode.z.ai'
29
+ const KEYCHAIN_SERVICE = 'ZCode Credential Encryption'
30
+
31
+ const LIVE_CAPS = {
32
+ send: true, stop: false, resume: true, approve: false, question: false,
33
+ attachments: false, permissionMode: false, queue: false, compact: false,
34
+ share: true, spawn: false,
35
+ }
36
+
37
+ // ── credentials ──
38
+
39
+ function readDeviceConfig() {
40
+ try {
41
+ const setting = JSON.parse(fs.readFileSync(path.join(V2, 'setting.json'), 'utf8'))
42
+ const dev = setting.webRemoteControlRelayV2Device || {}
43
+ let mid = ''
44
+ try {
45
+ const tele = JSON.parse(fs.readFileSync(path.join(V2, 'telemetry-state.json'), 'utf8'))
46
+ mid = tele.deviceMid || ''
47
+ } catch {}
48
+ if (!dev.deviceSid || !mid) return null
49
+ return { sid: dev.deviceSid, mid, origin: dev.endpointOrigin || RELAY_ORIGIN }
50
+ } catch { return null }
51
+ }
52
+
53
+ function decryptEncV2(payload, key) {
54
+ // enc envelope body: <iv>.<authTag>.<ciphertext> (base64url, AES-256-GCM)
55
+ const parts = payload.split('.')
56
+ if (parts.length !== 3) throw new Error('enc:v2 payload 格式无效')
57
+ const iv = Buffer.from(parts[0], 'base64url')
58
+ const tag = Buffer.from(parts[1], 'base64url')
59
+ const data = Buffer.from(parts[2], 'base64url')
60
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv)
61
+ decipher.setAuthTag(tag)
62
+ return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8')
63
+ }
64
+
65
+ /** Best-effort JWT acquisition. Returns '' when unavailable. */
66
+ function readJwt() {
67
+ if (process.env.CODEPOCKET_ZCODE_JWT) return process.env.CODEPOCKET_ZCODE_JWT.trim()
68
+ try {
69
+ const cached = fs.readFileSync(path.join(os.homedir(), '.codepocket', 'zcode-jwt.txt'), 'utf8').trim()
70
+ if (cached) return cached
71
+ } catch {}
72
+ try {
73
+ const creds = JSON.parse(fs.readFileSync(path.join(V2, 'credentials.json'), 'utf8'))
74
+ const raw = creds['zcodejwttoken'] || ''
75
+ const m = /^enc:v2:os:[0-9a-f]+:(.+)$/s.exec(raw)
76
+ if (!m) return ''
77
+ let secret = ''
78
+ try {
79
+ secret = execSync(`security find-generic-password -s "${KEYCHAIN_SERVICE}" -w`, { timeout: 15000, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim()
80
+ } catch { return '' } // keychain denied/unavailable — needs one-time user approval
81
+ if (!secret) return ''
82
+ // keychain value is base64 of the raw 32-byte AES key (verified)
83
+ const key = Buffer.from(secret, 'base64')
84
+ if (key.length !== 32) return ''
85
+ const jwt = decryptEncV2(m[1], key)
86
+ if (jwt) {
87
+ // cache so the keychain is only consulted when the cache is missing
88
+ try {
89
+ const dir = path.join(os.homedir(), '.codepocket')
90
+ fs.mkdirSync(dir, { recursive: true })
91
+ fs.writeFileSync(path.join(dir, 'zcode-jwt.txt'), jwt, { mode: 0o600 })
92
+ } catch {}
93
+ }
94
+ return jwt
95
+ } catch { return '' }
96
+ }
97
+
98
+ /** Wipe the JWT cache so the next readJwt() goes back to the keychain. */
99
+ function refreshJwt() {
100
+ try { fs.unlinkSync(path.join(os.homedir(), '.codepocket', 'zcode-jwt.txt')) } catch {}
101
+ return readJwt()
102
+ }
103
+
104
+ // ── relay client ──
105
+
106
+ let client = null // singleton
107
+ let clientPromise = null
108
+
109
+ function onSessionEvent(cb) { notifyCb = cb }
110
+ let notifyCb = () => {}
111
+
112
+ class ZcodeRelayClient {
113
+ constructor() {
114
+ this.ws = null
115
+ this.seq = 0 // relay-level payload counter
116
+ this.rpcSeq = 0 // rpc-frame seq — INDEPENDENT counter starting at 1 per bridge (verified)
117
+ this.rpcId = 0
118
+ this.taskViewEpoch = null
119
+ this.taskViewSeq = 0
120
+ this.pending = new Map() // rpcId → {resolve, reject}
121
+ this.listeners = new Map() // rpcId → handler(data)
122
+ this.bridge = null // { bridgeSessionId, bridgeGeneration, workspaceKey }
123
+ this.ready = false
124
+ this.debug = !!process.env.CODEPOCKET_ZCODE_DEBUG
125
+ }
126
+
127
+ sendWire(obj) {
128
+ if (!this.ws || this.ws.readyState !== 1) throw new Error('ZCode 中继未连接')
129
+ this.ws.send(JSON.stringify(obj))
130
+ }
131
+
132
+ sendPayload(payload) {
133
+ this.seq += 1
134
+ this.sendWire({ type: 'data', client_ts: Math.floor(Date.now() / 1000), payload })
135
+ }
136
+
137
+ async request(method, params, timeoutMs = 20000) {
138
+ const id = crypto.randomUUID()
139
+ return new Promise((resolve, reject) => {
140
+ const t = setTimeout(() => { this.pending.delete(id); reject(new Error(`ZCode 请求超时: ${method}`)) }, timeoutMs)
141
+ this.pending.set(id, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } })
142
+ this.sendPayload({ zcode_type: method, requestId: id, ...(params || {}) })
143
+ })
144
+ }
145
+
146
+ handlePayload(p) {
147
+ const zt = p.zcode_type
148
+ if (this.debug) console.log('[zcode-relay <<]', JSON.stringify(p).slice(0, 220))
149
+ if (zt === 'mobile-task-view-request' && p.epoch) this.taskViewEpoch = p.epoch
150
+ if (zt === 'bootstrap-response' || zt === 'workspace-bridge-ready' || zt === 'workspace-bridge-error') {
151
+ const cb = this.pending.get(p.requestId)
152
+ if (cb) {
153
+ this.pending.delete(p.requestId)
154
+ if (zt === 'workspace-bridge-error') cb.reject(new Error(p.error || 'bridge 打开失败'))
155
+ else cb.resolve(p)
156
+ }
157
+ return
158
+ }
159
+ if (zt === 'app-error') {
160
+ // request-scoped failure — reject matching pending by best effort
161
+ if (p.requestId && this.pending.has(p.requestId)) {
162
+ const cb = this.pending.get(p.requestId)
163
+ this.pending.delete(p.requestId)
164
+ cb.reject(new Error(p.error || 'ZCode 应用错误 (' + (p.reason || '?') + ')'))
165
+ }
166
+ return
167
+ }
168
+ if (zt !== 'rpc-frame' && zt !== 'rpc-frame-ack') return
169
+
170
+ // relay-level sequencing: ack every received frame
171
+ if (zt === 'rpc-frame' && p.messageSeq !== undefined && p.bridgeSessionId === this.bridge?.bridgeSessionId) {
172
+ this.sendPayload({ zcode_type: 'rpc-frame-ack', bridgeSessionId: p.bridgeSessionId, bridgeGeneration: p.bridgeGeneration || 1, ackMessageSeq: p.messageSeq })
173
+ }
174
+ if (zt !== 'rpc-frame') return
175
+ const data = Buffer.from(p.dataBase64, 'base64')
176
+ let msg
177
+ try { msg = rpc.decodeMessage(data) } catch { return }
178
+ if (!msg.header) return
179
+ const type = msg.header[0]
180
+ const id = msg.header[1]
181
+
182
+ if (type === rpc.RS.Initialize) { this.ready = true; notifyCb(); return }
183
+ if (type === rpc.RS.PromiseSuccess || type === rpc.RS.PromiseError || type === rpc.RS.PromiseErrorObj) {
184
+ const cb = this.pending.get(`rpc:${id}`)
185
+ if (cb) {
186
+ this.pending.delete(`rpc:${id}`)
187
+ if (type === rpc.RS.PromiseSuccess) cb.resolve(msg.body)
188
+ else cb.reject(Object.assign(new Error((msg.body && msg.body.message) || 'ZCode RPC 失败'), msg.body || {}))
189
+ }
190
+ return
191
+ }
192
+ if (type === rpc.RS.EventFire) {
193
+ const h = this.listeners.get(id)
194
+ if (h && msg.body !== undefined) h(msg.body)
195
+ return
196
+ }
197
+ }
198
+
199
+ /** Channel.call over the bridge RPC. */
200
+ call(channel, method, arg, timeoutMs = 30000) {
201
+ const id = ++this.rpcId
202
+ const payload = rpc.encodeRequest(rpc.RT.Promise, id, channel, method, arg)
203
+ this.rpcSeq += 1
204
+ return new Promise((resolve, reject) => {
205
+ const t = setTimeout(() => { this.pending.delete(`rpc:${id}`); reject(new Error(`ZCode RPC 超时: ${channel}.${method}`)) }, timeoutMs)
206
+ this.pending.set(`rpc:${id}`, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } })
207
+ this.sendPayload({
208
+ zcode_type: 'rpc-frame',
209
+ bridgeSessionId: this.bridge.bridgeSessionId,
210
+ bridgeGeneration: this.bridge.bridgeGeneration || 1,
211
+ seq: this.rpcSeq,
212
+ messageSeq: this.rpcSeq,
213
+ fragmentIndex: 0, fragmentCount: 1,
214
+ messageBytes: payload.length,
215
+ checksum: { algorithm: 'crc32', value: crc32(payload).toString(16) },
216
+ dataBase64: payload.toString('base64'),
217
+ })
218
+ })
219
+ }
220
+
221
+ async connect() {
222
+ const cfg = readDeviceConfig()
223
+ if (!cfg) throw new Error('未找到 ZCode 远控配置(请先在 ZCode 桌面端开启手机远控)')
224
+ let jwt = readJwt()
225
+ if (!jwt) throw new Error('ZCode 凭据不可用(需一次钥匙串授权或设置 CODEPOCKET_ZCODE_JWT)')
226
+
227
+ let tokenRes = await fetch(`${cfg.origin}/api/v1/remote/token`, {
228
+ method: 'POST',
229
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + jwt },
230
+ body: JSON.stringify({ role: 'terminal' }),
231
+ })
232
+ let tj = await tokenRes.json()
233
+ // cached JWT expired → re-read from keychain once and retry
234
+ if (!(tj.data && tj.data.token) && (tokenRes.status === 401 || tj.code === 401 || /auth/i.test(JSON.stringify(tj).slice(0, 200)))) {
235
+ jwt = refreshJwt()
236
+ if (jwt) {
237
+ tokenRes = await fetch(`${cfg.origin}/api/v1/remote/token`, {
238
+ method: 'POST',
239
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + jwt },
240
+ body: JSON.stringify({ role: 'terminal' }),
241
+ })
242
+ tj = await tokenRes.json()
243
+ }
244
+ }
245
+ const token = tj.data && tj.data.token
246
+ if (!token) throw new Error('ZCode token 获取失败: ' + JSON.stringify(tj).slice(0, 120))
247
+
248
+ await new Promise((resolve, reject) => {
249
+ const ws = this.ws = new WebSocket(`${cfg.origin.replace(/^http/, 'ws')}/api/v1/remote/ws2?token=${encodeURIComponent(token)}&mid=${encodeURIComponent(cfg.mid)}`)
250
+ let settled = false
251
+ const fail = (e) => {
252
+ if (settled) { this.ready = false; notifyCb(); return }
253
+ settled = true
254
+ this.ws = null
255
+ reject(new Error('ZCode 中继连接失败: ' + (e || '连接关闭')))
256
+ }
257
+ ws.on('error', () => fail('error'))
258
+ ws.on('close', () => fail())
259
+ ws.on('message', (raw) => {
260
+ let m
261
+ try { m = JSON.parse(raw.toString()) } catch { return }
262
+ if (m.type === 'auth_ack' && m.pair_status === 'matched') {
263
+ if (!settled) { settled = true; resolve() }
264
+ return
265
+ }
266
+ if (m.type === 'error') {
267
+ if (!settled) { settled = true; reject(new Error('ZCode 中继: ' + (m.code || 'error'))) }
268
+ else { this.ready = false }
269
+ notifyCb()
270
+ return
271
+ }
272
+ if (m.type === 'data' && m.payload) {
273
+ try { this.handlePayload(m.payload) } catch {}
274
+ }
275
+ })
276
+ ws.on('open', () => {
277
+ ws.send(JSON.stringify({ type: 'auth_init', device_sid: cfg.sid, meta: { platform: 'web', version: '3.18.2', name: 'codepocket-connector' }, client_ts: Math.floor(Date.now() / 1000) }))
278
+ })
279
+ })
280
+
281
+ // bootstrap + bridge — the relay binds bridge-open to the SAME
282
+ // terminalClientSessionId used in bootstrap (verified in captured flow)
283
+ this.terminalId = 'terminal-' + crypto.randomUUID()
284
+ const boot = await this.request('bootstrap-request', { terminalClientSessionId: this.terminalId })
285
+ const workspaces = (boot.result && boot.result.workspaces) || []
286
+ const target = workspaces.find(w => w.kind !== 'remote' || (w.workspaceIdentity && w.remoteSessionId)) || workspaces[0]
287
+ if (!target) throw new Error('ZCode 桌面端没有可用的项目工作区')
288
+ const key = target.workspaceIdentity || target.workspacePath
289
+ const bridgeRes = await this.request('workspace-bridge-open', {
290
+ terminalClientSessionId: this.terminalId,
291
+ bridgeSessionId: 'bridge-' + crypto.randomUUID(),
292
+ bridgeGeneration: 1,
293
+ workspaceKey: key,
294
+ })
295
+ this.bridge = {
296
+ bridgeSessionId: bridgeRes.bridge.bridgeSessionId,
297
+ bridgeGeneration: bridgeRes.bridge.bridgeGeneration || 1,
298
+ workspaceKey: key,
299
+ }
300
+ this.ready = true
301
+
302
+ // Agent handshake (verified from web client): sendConversationCommandV4
303
+ // fails with fault.connection.handshakeRequired without these two calls,
304
+ // and command envelopes must carry the SAME clientId as the handshake.
305
+ this.clientId = 'client-' + crypto.randomUUID()
306
+ await this.call('zcode-agent', 'helloConversationV4', undefined, 20000)
307
+ await this.call('zcode-agent', 'initializeConversationV4', {
308
+ kind: 'clientHello',
309
+ protocolVersion: 3,
310
+ clientId: this.clientId,
311
+ clientKind: 'web',
312
+ appVersion: 'unknown',
313
+ capabilities: { workspaceHookReviewUi: true },
314
+ }, 20000)
315
+
316
+ notifyCb()
317
+ return true
318
+ }
319
+
320
+ sendMessage(sessionIdRaw, text) {
321
+ if (!this.bridge) throw new Error('ZCode 中继未连接')
322
+ const sessionId = String(sessionIdRaw).replace(/^zcode:/, '')
323
+ const envelope = {
324
+ commandId: crypto.randomUUID(),
325
+ clientId: this.clientId,
326
+ sessionId,
327
+ type: 'sendText',
328
+ payload: {
329
+ text,
330
+ mode: 'yolo',
331
+ planEnabled: false,
332
+ genUiContext: [],
333
+ },
334
+ issuedAt: Date.now(),
335
+ }
336
+ return this.call('zcode-agent', 'sendConversationCommandV4', {
337
+ workspacePath: this.bridge.workspaceKey.startsWith('/') ? this.bridge.workspaceKey : this.bridge.workspaceKey,
338
+ envelope,
339
+ })
340
+ }
341
+
342
+ /**
343
+ * Create a NEW conversation on the desktop via the verified createSession
344
+ * command (web-client shape: sessionId null + payload.workspaceId; the
345
+ * accepted result carries the new sess_ id). First message is NOT sent —
346
+ * the phone's composer sends it after landing on the session.
347
+ */
348
+ async createSession() {
349
+ if (!this.bridge) throw new Error('ZCode 中继未连接')
350
+ const r = await this.call('zcode-agent', 'sendConversationCommandV4', {
351
+ workspacePath: this.bridge.workspaceKey,
352
+ envelope: {
353
+ commandId: crypto.randomUUID(),
354
+ clientId: this.clientId,
355
+ sessionId: null,
356
+ type: 'createSession',
357
+ payload: {
358
+ workspaceId: this.bridge.workspaceKey,
359
+ },
360
+ issuedAt: Date.now(),
361
+ },
362
+ }, 30000)
363
+ if (!r || r.status !== 'accepted' || !(r.result && r.result.sessionId)) {
364
+ throw new Error('ZCode 新建会话被拒: ' + JSON.stringify(r).slice(0, 160))
365
+ }
366
+ return 'zcode:' + r.result.sessionId
367
+ }
368
+
369
+ /** Open (or re-open) the workspace bridge bound to a specific task so the
370
+ * agent channel can resolve its sessionId (verified: without setting the
371
+ * task view + taskId-bound bridge the send is rejected with
372
+ * proto.sessionNotFound). */
373
+ async bindTask(sessionIdRaw) {
374
+ if (!this.bridge) throw new Error('ZCode 中继未连接')
375
+ const sessionId = String(sessionIdRaw).replace(/^zcode:/, '') // strip namespace prefix
376
+ if (this.bridge.taskId === sessionId) return
377
+ // 1. set the desktop's active task view + view state to the target session
378
+ // (verified from the captured web flow: both updates precede a successful send)
379
+ if (this.taskViewEpoch) {
380
+ this.sendPayload({
381
+ zcode_type: 'mobile-task-view-update',
382
+ epoch: this.taskViewEpoch,
383
+ seq: ++this.taskViewSeq,
384
+ bridgeSessionId: this.bridge.bridgeSessionId,
385
+ bridgeGeneration: this.bridge.bridgeGeneration || 1,
386
+ view: {
387
+ workspacePath: this.bridge.workspaceKey,
388
+ taskId: sessionId,
389
+ },
390
+ })
391
+ await new Promise(r => setTimeout(r, 500))
392
+ }
393
+ this.sendPayload({
394
+ zcode_type: 'mobile-view-state-update',
395
+ viewState: {
396
+ activeWorkspaceKey: this.bridge.workspaceKey,
397
+ activeTaskId: sessionId,
398
+ updatedAt: Date.now(),
399
+ },
400
+ deviceInfo: { platform: 'web', version: '3.18.2', name: 'codepocket-connector', updatedAt: Date.now() },
401
+ })
402
+ await new Promise(r => setTimeout(r, 500))
403
+ // 2. re-open the bridge bound to the task
404
+ const bridgeRes = await this.request('workspace-bridge-open', {
405
+ terminalClientSessionId: this.terminalId,
406
+ bridgeSessionId: 'bridge-' + crypto.randomUUID(),
407
+ bridgeGeneration: 1,
408
+ workspaceKey: this.bridge.workspaceKey,
409
+ taskId: sessionId,
410
+ })
411
+ this.bridge = {
412
+ bridgeSessionId: bridgeRes.bridge.bridgeSessionId,
413
+ bridgeGeneration: bridgeRes.bridge.bridgeGeneration || 1,
414
+ workspaceKey: this.bridge.workspaceKey,
415
+ taskId: sessionId,
416
+ }
417
+ this.rpcSeq = 0
418
+ // 3. re-handshake on the new bridge with the same clientId
419
+ await this.call('zcode-agent', 'helloConversationV4', undefined, 20000)
420
+ await this.call('zcode-agent', 'initializeConversationV4', {
421
+ kind: 'clientHello',
422
+ protocolVersion: 3,
423
+ clientId: this.clientId,
424
+ clientKind: 'web',
425
+ appVersion: 'unknown',
426
+ capabilities: { workspaceHookReviewUi: true },
427
+ }, 20000)
428
+ // 4. subscribe to the conversation — this LOADS the session in the host
429
+ // (host.getRevision returns null → proto.sessionNotFound without it)
430
+ const sub = await this.call('zcode-agent', 'subscribeConversationV4', {
431
+ workspacePath: this.bridge.workspaceKey,
432
+ sessionId,
433
+ visibility: 'foreground',
434
+ }, 30000)
435
+ this.conversationSub = sub && (sub.ack || sub)
436
+ if (this.debug) console.log('[zcode-relay] conversation subscribed:', JSON.stringify(this.conversationSub).slice(0, 160))
437
+ }
438
+
439
+ close() {
440
+ try { this.ws && this.ws.close() } catch {}
441
+ this.ws = null
442
+ this.bridge = null
443
+ this.ready = false
444
+ }
445
+ }
446
+
447
+ // crc32 for relay checksum field (server verified it accepts; kept for wire fidelity)
448
+ function crc32(buf) {
449
+ let c, crc = 0xffffffff
450
+ for (let i = 0; i < buf.length; i++) {
451
+ c = (crc ^ buf[i]) & 0xff
452
+ for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1
453
+ crc = (crc >>> 8) ^ c
454
+ }
455
+ return (crc ^ 0xffffffff) >>> 0
456
+ }
457
+
458
+ async function getClient() {
459
+ if (client && client.ready && client.ws && client.ws.readyState === 1) return client
460
+ if (clientPromise) return clientPromise
461
+ clientPromise = (async () => {
462
+ const c = new ZcodeRelayClient()
463
+ await c.connect()
464
+ client = c
465
+ c.ws.on('close', () => { c.ready = false; if (client === c) client = null; notifyCb() })
466
+ return c
467
+ })()
468
+ try {
469
+ return await clientPromise
470
+ } finally {
471
+ clientPromise = null
472
+ }
473
+ }
474
+
475
+ function isReady() { return !!(client && client.ready) }
476
+
477
+ function resetClient() {
478
+ if (client) { try { client.close() } catch {} }
479
+ client = null
480
+ clientPromise = null
481
+ }
482
+
483
+ function sendMessage(sessionId, text) {
484
+ // Try the CURRENT bridge first — fresh sessions and already-bound sessions
485
+ // send directly (verified). Only sessionNotFound triggers a task re-bind;
486
+ // unconditional bindTask destabilizes freshly-created runtimes.
487
+ const direct = () => getClient().then(c => c.sendMessage(String(sessionId).replace(/^zcode:/, ''), text))
488
+ const withBind = () => getClient().then(async c => {
489
+ await c.bindTask(sessionId)
490
+ return c.sendMessage(String(sessionId).replace(/^zcode:/, ''), text)
491
+ })
492
+ return direct().then(r => {
493
+ if (r && r.status === 'rejected' && /sessionNotFound/i.test(String(r.reasonCode || ''))) {
494
+ return withBind()
495
+ }
496
+ return r
497
+ }).catch(e => {
498
+ const msg = String(e && e.message || e)
499
+ if (/超时|timeout|not ready|未连接|closed|degraded/i.test(msg)) {
500
+ resetClient()
501
+ return withBind()
502
+ }
503
+ throw e
504
+ })
505
+ }
506
+
507
+ function createSession() {
508
+ const attempt = () => getClient().then(c => c.createSession())
509
+ return attempt().catch(e => {
510
+ const msg = String(e && e.message || e)
511
+ if (/超时|timeout|not ready|未连接|closed|degraded/i.test(msg)) {
512
+ resetClient()
513
+ return attempt()
514
+ }
515
+ throw e
516
+ })
517
+ }
518
+
519
+ function liveInfo() {
520
+ return { connected: isReady(), caps: LIVE_CAPS }
521
+ }
522
+
523
+ module.exports = {
524
+ LIVE_CAPS, readDeviceConfig, readJwt,
525
+ getClient, sendMessage, createSession, isReady, liveInfo, onSessionEvent,
526
+ }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * ZCode binary RPC serialization — JS port of the upstream Apache-2.0
3
+ * implementation (zai-org/ZCode packages/rpc/src/serialization.ts, v3.18.2).
4
+ *
5
+ * Wire format: [1-byte type tag][VQL length][data]
6
+ * 0=undefined 1=string 2=buffer 4=array 5=object(JSON) 6=int(VQL)
7
+ * Each RPC message = serialize(header) + serialize(body).
8
+ * Request header: [RequestType, id, channelName, methodName]
9
+ * Response header: [ResponseType, id]
10
+ *
11
+ * Verified byte-for-byte against captured ws2 relay frames:
12
+ * 04 04 06 64 06 79 01 0b "zcode-agent" 01 19 "sendConversationCommandV4" 04 01 05 <vql> {json}
13
+ */
14
+
15
+ const T_UNDEFINED = 0
16
+ const T_STRING = 1
17
+ const T_BUFFER = 2
18
+ const T_ARRAY = 4
19
+ const T_OBJECT = 5
20
+ const T_INT = 6
21
+
22
+ const RT = { Promise: 100, PromiseCancel: 101, EventListen: 102, EventDispose: 103 }
23
+ const RS = { Initialize: 200, PromiseSuccess: 201, PromiseError: 202, PromiseErrorObj: 203, EventFire: 204, EventError: 205 }
24
+
25
+ // ── VQL (variable-length quantity, 7-bit groups, little-endian) ──
26
+
27
+ function readVQL(buf, state) {
28
+ let value = 0
29
+ for (let n = 0; ; n += 7) {
30
+ const b = buf[state.pos++]
31
+ value |= (b & 0x7f) << n
32
+ if (!(b & 0x80)) return value
33
+ }
34
+ }
35
+
36
+ function writeVQL(out, value) {
37
+ if (value === 0) { out.push(0); return }
38
+ while (value !== 0) {
39
+ let byte = value & 0x7f
40
+ value = value >>> 7
41
+ if (value > 0) byte |= 0x80
42
+ out.push(byte)
43
+ }
44
+ }
45
+
46
+ // ── serialize: value → Buffer ──
47
+
48
+ function serialize(data) {
49
+ const out = []
50
+ ser(out, data)
51
+ return Buffer.from(out)
52
+ }
53
+
54
+ function ser(out, data) {
55
+ if (data === undefined) { out.push(T_UNDEFINED); return }
56
+ if (typeof data === 'string') {
57
+ out.push(T_STRING)
58
+ const b = Buffer.from(data, 'utf8')
59
+ writeVQL(out, b.length)
60
+ append(out, b)
61
+ return
62
+ }
63
+ if (Buffer.isBuffer(data) || data instanceof Uint8Array) {
64
+ out.push(T_BUFFER)
65
+ const b = Buffer.isBuffer(data) ? data : Buffer.from(data)
66
+ writeVQL(out, b.length)
67
+ append(out, b)
68
+ return
69
+ }
70
+ if (Array.isArray(data)) {
71
+ out.push(T_ARRAY)
72
+ writeVQL(out, data.length)
73
+ for (const el of data) ser(out, el)
74
+ return
75
+ }
76
+ if (typeof data === 'number' && (data | 0) === data) {
77
+ out.push(T_INT)
78
+ writeVQL(out, data)
79
+ return
80
+ }
81
+ const b = Buffer.from(JSON.stringify(data), 'utf8')
82
+ out.push(T_OBJECT)
83
+ writeVQL(out, b.length)
84
+ append(out, b)
85
+ }
86
+
87
+ function append(out, buf) {
88
+ for (let i = 0; i < buf.length; i++) out.push(buf[i])
89
+ }
90
+
91
+ // ── deserialize: Buffer → value ──
92
+
93
+ function deserializeValue(buf, state) {
94
+ const type = buf[state.pos++]
95
+ switch (type) {
96
+ case T_UNDEFINED:
97
+ return undefined
98
+ case T_STRING: {
99
+ const len = readVQL(buf, state)
100
+ const s = buf.slice(state.pos, state.pos + len).toString('utf8')
101
+ state.pos += len
102
+ return s
103
+ }
104
+ case T_BUFFER: {
105
+ const len = readVQL(buf, state)
106
+ const b = buf.slice(state.pos, state.pos + len)
107
+ state.pos += len
108
+ return b
109
+ }
110
+ case T_ARRAY: {
111
+ const len = readVQL(buf, state)
112
+ const arr = []
113
+ for (let i = 0; i < len; i++) arr.push(deserializeValue(buf, state))
114
+ return arr
115
+ }
116
+ case T_OBJECT: {
117
+ const len = readVQL(buf, state)
118
+ const s = buf.slice(state.pos, state.pos + len).toString('utf8')
119
+ state.pos += len
120
+ return JSON.parse(s)
121
+ }
122
+ case T_INT:
123
+ return readVQL(buf, state)
124
+ default:
125
+ throw new Error(`zcodeRpc: unknown type tag ${type} at offset ${state.pos - 1}`)
126
+ }
127
+ }
128
+
129
+ /** Deserialize the first value; returns { value, pos } so callers can continue with the body. */
130
+ function deserialize(buf, startPos = 0) {
131
+ const state = { pos: startPos }
132
+ const value = deserializeValue(buf, state)
133
+ return { value, pos: state.pos }
134
+ }
135
+
136
+ // ── RPC message helpers ──
137
+
138
+ /** Encode a request frame (call or listen). Args wire shape (verified): with arg → [arg]; no arg → []. */
139
+ function encodeRequest(type, id, channel, method, arg) {
140
+ return Buffer.concat([
141
+ serialize([type, id, channel, method]),
142
+ serialize(arg !== undefined ? [arg] : []),
143
+ ])
144
+ }
145
+
146
+ /** Encode a cancel/dispose frame. */
147
+ function encodeCancel(type, id) {
148
+ return Buffer.concat([
149
+ serialize([type, id]),
150
+ serialize(undefined),
151
+ ])
152
+ }
153
+
154
+ /** Decode a full message (header + optional body) from one rpc-frame payload. */
155
+ function decodeMessage(buf) {
156
+ const h = deserialize(buf)
157
+ const header = h.value
158
+ if (!Array.isArray(header)) return { type: -1, header: null, body: undefined }
159
+ let body
160
+ if (h.pos < buf.length) {
161
+ try { body = deserialize(buf, h.pos).value } catch { body = undefined }
162
+ }
163
+ return { type: header[0], header, body }
164
+ }
165
+
166
+ module.exports = {
167
+ RT, RS,
168
+ serialize, deserialize,
169
+ encodeRequest, encodeCancel, decodeMessage,
170
+ }