dsh-plugin-cua-win 0.0.0-stage → 0.2.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,644 @@
1
+ // dsh-plugin-cua-win — MCP client for the Windows daemon.
2
+ //
3
+ // The daemon speaks the Model Context Protocol (JSON-RPC 2.0). This module is the client half:
4
+ // ONE persistent TCP connection for the whole plugin activation, with request-id multiplexing,
5
+ // heartbeat, and reconnect.
6
+ //
7
+ // Why one connection and not a call helper: a per-call connect would add a TCP handshake to every
8
+ // tool call, and would make the daemon's session ownership meaningless (ownership is per
9
+ // connection). Everything here exists to keep that socket healthy and to make every in-flight call
10
+ // settle exactly once.
11
+ //
12
+ // The invariants, all checked by test/connection.test.mjs:
13
+ // * ids are never reused, not even across reconnects, so a late response on a dead socket
14
+ // cannot be mistaken for a live request's answer;
15
+ // * when the socket dies, every pending call rejects immediately with `connection_closed`
16
+ // (a tool call must never hang waiting for a reconnect);
17
+ // * heartbeat silence and EOF converge on the same teardown, because an SSH-forwarded TCP
18
+ // connection can stay ESTABLISHED long after the remote process died;
19
+ // * in-flight calls are NOT replayed on reconnect: clicking twice is a real bug.
20
+
21
+ import net from 'node:net'
22
+ import { EventEmitter } from 'node:events'
23
+ import { execFileSync } from 'node:child_process'
24
+
25
+ /** MCP protocol versions this client knows, newest first. */
26
+ export const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']
27
+
28
+ export const CLIENT_INFO = { name: 'dsh-plugin-cua-win', version: '0.2.1' }
29
+
30
+ export const MAX_LINE_BYTES = 64 * 1024 * 1024
31
+
32
+ /**
33
+ * Read the daemon token from the Windows host over ssh.
34
+ *
35
+ * The token guards the daemon's loopback port against *other local processes*. Anyone who can ssh
36
+ * to that host can read the file anyway, so requiring a manual copy added a step without adding a
37
+ * boundary — and every `serve` that regenerated the token silently invalidated the copy, which
38
+ * then surfaced as an opaque bad_token.
39
+ *
40
+ * `type` is used before PowerShell: one process instead of two, and it does not depend on the
41
+ * host's execution policy. Returns '' on any failure so the caller keeps whatever it had.
42
+ */
43
+ export function fetchTokenOverSsh(sshHost, { timeoutMs = 15000, sshConfig = '' } = {}) {
44
+ if (!sshHost) return ''
45
+ const base = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=5']
46
+ if (sshConfig) base.unshift('-F', sshConfig)
47
+ const attempts = [
48
+ 'cmd /c type %LOCALAPPDATA%\\cua-win-daemon\\token',
49
+ 'powershell -NoProfile -Command "Get-Content -Raw ($env:LOCALAPPDATA + \'\\cua-win-daemon\\token\')"',
50
+ ]
51
+ for (const remote of attempts) {
52
+ try {
53
+ const out = execFileSync('ssh', [...base, sshHost, remote], {
54
+ encoding: 'utf8',
55
+ timeout: timeoutMs,
56
+ stdio: ['ignore', 'pipe', 'ignore'],
57
+ })
58
+ const token = out.trim()
59
+ // The daemon writes lowercase hex. Anything else (a banner, an error line) must not be
60
+ // handed to the handshake as if it were a token.
61
+ if (/^[0-9a-f]{16,128}$/i.test(token)) return token
62
+ } catch {
63
+ // try the next form
64
+ }
65
+ }
66
+ return ''
67
+ }
68
+
69
+ export const STATE = {
70
+ idle: 'idle',
71
+ connecting: 'connecting',
72
+ handshaking: 'handshaking',
73
+ ready: 'ready',
74
+ reconnecting: 'reconnecting',
75
+ disposed: 'disposed',
76
+ }
77
+
78
+ /**
79
+ * A failure whose `code` is meaningful to the caller. MCP distinguishes two kinds and so does
80
+ * this class:
81
+ * * a JSON-RPC error (`rpcCode` set) means the REQUEST was wrong — unknown tool, bad arguments;
82
+ * * a tool result with `isError:true` means the TOOL ran and failed — that is returned to the
83
+ * model, not thrown, so it is never a DaemonError.
84
+ */
85
+ export class DaemonError extends Error {
86
+ constructor(code, message, details, rpcCode) {
87
+ super(message)
88
+ this.name = 'DaemonError'
89
+ this.code = code
90
+ this.details = details
91
+ this.rpcCode = rpcCode
92
+ }
93
+ }
94
+
95
+ export class Connection extends EventEmitter {
96
+ #options
97
+ #socket = null
98
+ #state = STATE.idle
99
+ #nextId = 1
100
+ #pending = new Map()
101
+ #buffer = Buffer.alloc(0)
102
+ #heartbeatTimer = null
103
+ #reconnectTimer = null
104
+ #reconnectAttempt = 0
105
+ #lastPongAt = 0
106
+ #serverInfo = null
107
+ #tokenFetched = false
108
+ #protocolVersion = null
109
+ #tools = new Map()
110
+ #disposed = false
111
+
112
+ constructor(options) {
113
+ super()
114
+ // Drop keys whose value is undefined so they cannot overwrite a default below. `apply()`
115
+ // forwards optional config fields directly; without this, an unset field arrives as undefined
116
+ // and replaces the default (tokenAuto: undefined disabled the ssh token fetch entirely).
117
+ const provided = Object.fromEntries(
118
+ Object.entries(options ?? {}).filter(([, value]) => value !== undefined),
119
+ )
120
+ this.#options = {
121
+ host: '127.0.0.1',
122
+ port: 9000,
123
+ token: '',
124
+ // When no token is configured but an ssh host is, fetch it once instead of failing with a
125
+ // bad_token the user cannot explain.
126
+ sshHost: '',
127
+ sshConfig: '',
128
+ tokenAuto: true,
129
+ // true when `token` came from a cacheable source (a file) rather than from explicit config.
130
+ tokenRefreshable: false,
131
+ connectTimeoutMs: 3000,
132
+ handshakeTimeoutMs: 10000,
133
+ callTimeoutMs: 30000,
134
+ heartbeatIntervalMs: 10000,
135
+ pongDeadlineMs: 25000,
136
+ reconnectInitialMs: 500,
137
+ reconnectMaxMs: 30000,
138
+ reconnectJitter: 0.2,
139
+ autoReconnect: true,
140
+ ...provided,
141
+ }
142
+ }
143
+
144
+ get state() {
145
+ return this.#state
146
+ }
147
+
148
+ get serverInfo() {
149
+ return this.#serverInfo
150
+ }
151
+
152
+ /** The MCP protocol version the daemon agreed to. */
153
+ get protocolVersion() {
154
+ return this.#protocolVersion
155
+ }
156
+
157
+ /** MCP tool names the daemon offers, e.g. `cua_win_click`. The only authority on availability. */
158
+ get availableTools() {
159
+ return new Set(this.#tools.keys())
160
+ }
161
+
162
+ hasTool(mcpName) {
163
+ return this.#tools.has(mcpName)
164
+ }
165
+
166
+ /** The advertised input schema for one MCP tool name, if the daemon sent one. */
167
+ toolSchema(mcpName) {
168
+ return this.#tools.get(mcpName)?.inputSchema
169
+ }
170
+
171
+ toolMeta(mcpName) {
172
+ return this.#tools.get(mcpName)
173
+ }
174
+
175
+ get reconnectAttempt() {
176
+ return this.#reconnectAttempt
177
+ }
178
+
179
+ get pendingCount() {
180
+ return this.#pending.size
181
+ }
182
+
183
+ /** Connect and complete the MCP handshake. Resolves once READY. */
184
+ async start() {
185
+ if (this.#state === STATE.ready || this.#disposed) return
186
+ await this.#connectOnce().catch((error) => {
187
+ if (!this.#disposed && this.#state !== STATE.reconnecting) this.#setState(STATE.idle)
188
+ throw error
189
+ })
190
+ }
191
+
192
+ startAutoReconnect() {
193
+ if (this.#disposed || !this.#options.autoReconnect) return
194
+ if (this.#state === STATE.ready || this.#state === STATE.connecting) return
195
+ this.#scheduleReconnect()
196
+ }
197
+
198
+ async #connectOnce() {
199
+ this.#setState(STATE.connecting)
200
+ this.#tokenFetched = false
201
+ this.#serverInfo = null
202
+ this.#tools = new Map()
203
+
204
+ const socket = await this.#openSocket()
205
+ if (this.#disposed) {
206
+ socket.destroy()
207
+ throw new DaemonError('connection_closed', 'the client was disposed')
208
+ }
209
+ this.#socket = socket
210
+ this.#buffer = Buffer.alloc(0)
211
+
212
+ socket.on('data', (chunk) => { if (this.#socket === socket) this.#onData(chunk) })
213
+ socket.on('error', (error) => this.#onSocketDown(`socket error: ${error.message}`, socket))
214
+ socket.on('close', () => this.#onSocketDown('the connection closed', socket))
215
+
216
+ this.#setState(STATE.handshaking)
217
+ try {
218
+ await this.#handshake()
219
+ } catch (error) {
220
+ if (this.#socket === socket) this.#destroySocket()
221
+ throw error
222
+ }
223
+
224
+ if (this.#disposed || this.#socket !== socket) {
225
+ throw new DaemonError('connection_closed', 'the connection closed during handshake')
226
+ }
227
+
228
+ this.#setState(STATE.ready)
229
+ this.#reconnectAttempt = 0
230
+ this.#lastPongAt = Date.now()
231
+ this.#startHeartbeat()
232
+ this.emit('ready', this.#serverInfo)
233
+ }
234
+
235
+ #openSocket() {
236
+ const { host, port, connectTimeoutMs } = this.#options
237
+ return new Promise((resolve, reject) => {
238
+ const socket = net.createConnection({ host, port })
239
+ const timer = setTimeout(() => {
240
+ socket.destroy()
241
+ reject(new DaemonError('daemon_unreachable',
242
+ `connecting to ${host}:${port} timed out after ${connectTimeoutMs}ms; is the ssh -L tunnel running?`))
243
+ }, connectTimeoutMs)
244
+
245
+ socket.once('connect', () => {
246
+ clearTimeout(timer)
247
+ socket.setNoDelay(true)
248
+ resolve(socket)
249
+ })
250
+ socket.once('error', (error) => {
251
+ clearTimeout(timer)
252
+ reject(new DaemonError('daemon_unreachable',
253
+ `cannot reach ${host}:${port} (${error.code ?? error.message}); is the ssh -L tunnel running and the daemon up?`))
254
+ })
255
+ })
256
+ }
257
+
258
+ /**
259
+ * Fetch the token from the ssh host once, if none was supplied.
260
+ *
261
+ * Called lazily at handshake time so an activation that never connects does not spawn ssh, and
262
+ * guarded by `#tokenFetched` so a handshake fetches at most once; a later connection can
263
+ * refresh a rotated token or retry a failed SSH fetch.
264
+ */
265
+ #ensureToken() {
266
+ if (this.#tokenFetched) return
267
+ // An explicit token is the operator's decision and is never overridden. A token that came from
268
+ // a file may be stale, and refreshing it is the whole point of the fetch: a `serve` restart that
269
+ // regenerated the token leaves the cached copy wrong, and the symptom is an opaque bad_token.
270
+ if (this.#options.token && !this.#options.tokenRefreshable) return
271
+ if (!this.#options.sshHost || !this.#options.tokenAuto) return
272
+ this.#tokenFetched = true
273
+ const token = fetchTokenOverSsh(this.#options.sshHost, { sshConfig: this.#options.sshConfig })
274
+ if (token) {
275
+ this.#options.token = token
276
+ this.#options.tokenRefreshable = true
277
+ }
278
+ }
279
+
280
+ /**
281
+ * MCP handshake: `initialize`, then the `notifications/initialized` notification.
282
+ *
283
+ * The notification is not optional politeness: a compliant server may refuse `tools/list` until
284
+ * it has seen it.
285
+ */
286
+ async #handshake() {
287
+ const params = {
288
+ protocolVersion: MCP_VERSIONS[0],
289
+ capabilities: {},
290
+ clientInfo: CLIENT_INFO,
291
+ }
292
+ // The TCP transport authenticates with a token on the first message. stdio needs none.
293
+ this.#ensureToken()
294
+ if (this.#options.token) params.token = this.#options.token
295
+
296
+ const result = await this.#request('initialize', params, { timeoutMs: this.#options.handshakeTimeoutMs })
297
+
298
+ this.#protocolVersion = result?.protocolVersion ?? null
299
+ this.#serverInfo = {
300
+ ...(result?.serverInfo ?? {}),
301
+ ...(result?.cuaWinDaemon ?? {}),
302
+ }
303
+
304
+ if (!MCP_VERSIONS.includes(this.#protocolVersion)) {
305
+ // A server that answered with a version this client does not know may still work, but saying
306
+ // so is better than pretending the two agree.
307
+ this.emit('warning',
308
+ `the daemon answered MCP version "${this.#protocolVersion}", which this client does not list; ` +
309
+ `expected one of ${MCP_VERSIONS.join(', ')}`)
310
+ }
311
+
312
+ // Order matters: MCP servers may refuse tools/list until they have seen
313
+ // `notifications/initialized`, so the notification goes first.
314
+ this.#notify('notifications/initialized', {})
315
+
316
+ // Record the tool surface before declaring readiness, so a caller reacting to 'ready' already
317
+ // sees an accurate tool list.
318
+ try {
319
+ const list = await this.#request('tools/list', {}, { timeoutMs: this.#options.handshakeTimeoutMs })
320
+ for (const tool of list?.tools ?? []) {
321
+ if (tool?.name) this.#tools.set(tool.name, tool)
322
+ }
323
+ } catch (error) {
324
+ // A daemon that cannot list tools cannot serve them; treat it as a failed handshake rather
325
+ // than starting a connection that will fail every call.
326
+ throw new DaemonError('handshake_failed', `tools/list failed during handshake: ${error.message}`)
327
+ }
328
+ }
329
+
330
+ #setState(next) {
331
+ if (this.#state === next) return
332
+ this.#state = next
333
+ this.emit('state', next)
334
+ }
335
+
336
+ // ── framing ────────────────────────────────────────────────────────────────
337
+
338
+ #onData(chunk) {
339
+ this.#buffer = this.#buffer.length === 0 ? chunk : Buffer.concat([this.#buffer, chunk])
340
+
341
+ for (;;) {
342
+ const index = this.#buffer.indexOf(0x0a)
343
+ if (index === -1) {
344
+ if (this.#buffer.length > MAX_LINE_BYTES) this.#onSocketDown('the daemon sent a line over the protocol cap', this.#socket)
345
+ break
346
+ }
347
+ const line = this.#buffer.subarray(0, index)
348
+ this.#buffer = this.#buffer.subarray(index + 1)
349
+ if (line.length === 0) continue
350
+ if (line.length > MAX_LINE_BYTES) {
351
+ this.#onSocketDown('the daemon sent a line over the protocol cap', this.#socket)
352
+ return
353
+ }
354
+ try {
355
+ this.#onMessage(JSON.parse(line.toString('utf8')))
356
+ } catch (error) {
357
+ this.emit('protocol-error', error)
358
+ }
359
+ }
360
+ }
361
+
362
+ #onMessage(message) {
363
+ // A JSON-RPC message carries either result/error (a response) or method (a notification).
364
+ if (message.method !== undefined && message.id === undefined) {
365
+ this.emit('notification', message)
366
+ return
367
+ }
368
+
369
+ const pending = this.#pending.get(message.id)
370
+ if (!pending) {
371
+ // A late answer to a call that already timed out. Counted, never guessed at.
372
+ this.emit('dropped-response', message.id)
373
+ return
374
+ }
375
+ this.#pending.delete(message.id)
376
+ clearTimeout(pending.timer)
377
+ pending.settle(message, Date.now() - pending.startedAt)
378
+ }
379
+
380
+ /**
381
+ * Send a JSON-RPC request and resolve with `result`.
382
+ *
383
+ * A JSON-RPC `error` is rejected as a DaemonError (the REQUEST was wrong). A tool that ran and
384
+ * failed is NOT an error here: `tools/call` returns it as a result with isError:true, and that is
385
+ * handed back to the caller for the model to read.
386
+ */
387
+ #request(method, params, { timeoutMs } = {}) {
388
+ return new Promise((resolve, reject) => {
389
+ if (this.#state === STATE.reconnecting) {
390
+ reject(new DaemonError('daemon_reconnecting',
391
+ `the connection is being re-established (attempt ${this.#reconnectAttempt}); retry shortly`))
392
+ return
393
+ }
394
+ if (!this.#socket || this.#socket.destroyed) {
395
+ reject(new DaemonError('daemon_unreachable',
396
+ 'not connected to the Windows daemon; check the ssh -L tunnel and that the daemon is running'))
397
+ return
398
+ }
399
+
400
+ const id = this.#nextId++
401
+ const startedAt = Date.now()
402
+ const effectiveTimeout = timeoutMs ?? this.#options.callTimeoutMs
403
+ const timer = setTimeout(() => {
404
+ if (this.#pending.delete(id)) {
405
+ reject(new DaemonError('timeout',
406
+ `${method} exceeded its ${effectiveTimeout}ms client deadline; it may still be running on the host`))
407
+ }
408
+ }, effectiveTimeout)
409
+
410
+ this.#pending.set(id, {
411
+ startedAt,
412
+ timer,
413
+ reject,
414
+ settle: (message, elapsed) => {
415
+ if (message.error) {
416
+ const rpcCode = message.error.code
417
+ // Map the JSON-RPC codes a caller can act on onto the daemon's own vocabulary, so the
418
+ // plugin's error handling does not need two vocabularies.
419
+ const code = rpcCode === -32602 ? 'invalid_arguments'
420
+ : rpcCode === -32601 ? 'unknown_tool'
421
+ : rpcCode === -32001 ? 'bad_token'
422
+ : 'rpc_error'
423
+ reject(new DaemonError(code, message.error.message, message.error.data, rpcCode))
424
+ return
425
+ }
426
+ resolve(message.result, elapsed)
427
+ },
428
+ })
429
+
430
+ const payload = { jsonrpc: '2.0', id, method }
431
+ if (params !== undefined && params !== null) payload.params = params
432
+
433
+ try {
434
+ this.#socket.write(`${JSON.stringify(payload)}\n`)
435
+ } catch (error) {
436
+ this.#pending.delete(id)
437
+ clearTimeout(timer)
438
+ reject(new DaemonError('connection_closed', error.message))
439
+ }
440
+ })
441
+ }
442
+
443
+ /** Send a JSON-RPC notification: no id, no response, no promise. */
444
+ #notify(method, params) {
445
+ if (!this.#socket || this.#socket.destroyed) return
446
+ const payload = { jsonrpc: '2.0', method }
447
+ if (params !== undefined && params !== null) payload.params = params
448
+ try {
449
+ this.#socket.write(`${JSON.stringify(payload)}\n`)
450
+ } catch {
451
+ // A notification has no reply to lose; the socket's close handler deals with the connection.
452
+ }
453
+ }
454
+
455
+ // ── tools ──────────────────────────────────────────────────────────────────
456
+
457
+ /**
458
+ * Call one MCP tool by its MCP name (`cua_win_click`).
459
+ *
460
+ * Returns the MCP CallToolResult unchanged: `{ content, structuredContent, isError }`. The caller
461
+ * decides how to render it; the plugin never treats `isError` as a transport failure.
462
+ *
463
+ * `busy` is retried once, and only for calls the caller marks as safe to repeat. A daemon that
464
+ * shares one worker pool among several clients answers `busy` as backpressure, not failure.
465
+ */
466
+ async callTool(mcpName, args, { signal, timeoutMs, retryOnBusy = false } = {}) {
467
+ const dispatch = () => this.#request('tools/call', { name: mcpName, arguments: args ?? {} }, { timeoutMs })
468
+ const guarded = signal ? this.#withCancellation(mcpName, dispatch, signal) : dispatch()
469
+
470
+ const result = await guarded
471
+ if (result?.isError !== true) return result
472
+
473
+ const code = result?.structuredContent?.code
474
+ if (code !== 'busy' || !retryOnBusy) return result
475
+
476
+ const retryAfter = Number(result?.structuredContent?.retry_after_ms ?? 250)
477
+ const delay = Number.isFinite(retryAfter) ? Math.max(50, retryAfter) : 250
478
+ await new Promise((resolve, reject) => {
479
+ if (signal?.aborted) {
480
+ reject(new DaemonError('canceled', `${mcpName} was cancelled before retry`))
481
+ return
482
+ }
483
+ const onAbort = () => {
484
+ clearTimeout(timer)
485
+ reject(new DaemonError('canceled', `${mcpName} was cancelled before retry`))
486
+ }
487
+ const timer = setTimeout(() => {
488
+ signal?.removeEventListener('abort', onAbort)
489
+ resolve()
490
+ }, delay)
491
+ signal?.addEventListener('abort', onAbort, { once: true })
492
+ })
493
+ return signal ? this.#withCancellation(mcpName, dispatch, signal) : dispatch()
494
+ }
495
+
496
+ /** `ping` — the MCP liveness method, used by the heartbeat and available to callers. */
497
+ ping({ timeoutMs } = {}) {
498
+ return this.#request('ping', {}, { timeoutMs })
499
+ }
500
+
501
+ /** Re-read the tool list, e.g. after the daemon is replaced by a newer build. */
502
+ async listTools() {
503
+ const result = await this.#request('tools/list', {})
504
+ this.#tools = new Map()
505
+ for (const tool of result?.tools ?? []) {
506
+ if (tool?.name) this.#tools.set(tool.name, tool)
507
+ }
508
+ return [...this.#tools.values()]
509
+ }
510
+
511
+ /**
512
+ * Race a call against the caller's cancellation.
513
+ *
514
+ * Settling the caller immediately is the honest part: a Win32 or UIA action already dispatched
515
+ * cannot be un-sent, so the result says cancelled while the host may still be finishing it.
516
+ */
517
+ #withCancellation(mcpName, dispatch, signal) {
518
+ if (signal.aborted) {
519
+ return Promise.reject(new DaemonError('canceled', `${mcpName} was cancelled before it started`))
520
+ }
521
+ let onAbort
522
+ const cancelled = new Promise((_, reject) => {
523
+ onAbort = () => reject(new DaemonError('canceled', `${mcpName} was cancelled; it may still be running on the host`))
524
+ signal.addEventListener('abort', onAbort, { once: true })
525
+ })
526
+ return Promise.race([dispatch(), cancelled]).finally(() => signal.removeEventListener('abort', onAbort))
527
+ }
528
+
529
+ // ── heartbeat / teardown / reconnect ───────────────────────────────────────
530
+
531
+ #startHeartbeat() {
532
+ this.#stopHeartbeat()
533
+ this.#heartbeatTimer = setInterval(() => {
534
+ void this.#heartbeatTick()
535
+ }, this.#options.heartbeatIntervalMs)
536
+ this.#heartbeatTimer.unref?.()
537
+ }
538
+
539
+ #stopHeartbeat() {
540
+ if (this.#heartbeatTimer) {
541
+ clearInterval(this.#heartbeatTimer)
542
+ this.#heartbeatTimer = null
543
+ }
544
+ }
545
+
546
+ async #heartbeatTick() {
547
+ if (this.#state !== STATE.ready) return
548
+ const socket = this.#socket
549
+ try {
550
+ await this.#request('ping', {}, { timeoutMs: Math.min(this.#options.pongDeadlineMs, 5000) })
551
+ if (this.#socket !== socket || this.#state !== STATE.ready) return
552
+ this.#lastPongAt = Date.now()
553
+ } catch {
554
+ // The deadline check below decides whether the silence is fatal.
555
+ }
556
+
557
+ if (this.#socket !== socket || this.#state !== STATE.ready) return
558
+ const silence = Date.now() - this.#lastPongAt
559
+ if (silence > this.#options.pongDeadlineMs) {
560
+ // The decisive case: ssh -L forwards bytes, so a killed remote daemon does not necessarily
561
+ // produce an EOF here. Silence is the only signal available.
562
+ this.#onSocketDown(`no pong for ${silence}ms (deadline ${this.#options.pongDeadlineMs}ms)`, socket)
563
+ }
564
+ }
565
+
566
+ #onSocketDown(reason, expectedSocket = null) {
567
+ if (this.#state === STATE.disposed) return
568
+ if (this.#state === STATE.reconnecting) return
569
+ if (expectedSocket && this.#socket !== expectedSocket) return
570
+
571
+ const wasLive = this.#state === STATE.ready || this.#state === STATE.handshaking
572
+ this.#destroySocket()
573
+
574
+ if (!wasLive) {
575
+ this.#setState(STATE.idle)
576
+ return
577
+ }
578
+
579
+ this.#failPending(reason)
580
+ this.#setState(this.#options.autoReconnect ? STATE.reconnecting : STATE.idle)
581
+ this.emit('disconnected', reason)
582
+
583
+ if (this.#options.autoReconnect) this.#scheduleReconnect()
584
+ }
585
+
586
+ #failPending(reason) {
587
+ for (const [id, entry] of this.#pending) {
588
+ this.#pending.delete(id)
589
+ clearTimeout(entry.timer)
590
+ // Settle directly instead of synthesising a JSON-RPC error: a transport failure is not a
591
+ // reply from the server, and squeezing it through the -32000 mapper produced `rpc_error`,
592
+ // a code that appears nowhere in the contract.
593
+ entry.reject(new DaemonError('connection_closed', `the connection closed: ${reason}`))
594
+ }
595
+ }
596
+
597
+ /** Backoff with jitter, capped. Exposed so the documented sequence is testable. */
598
+ backoffFor(attempt) {
599
+ const { reconnectInitialMs, reconnectMaxMs, reconnectJitter } = this.#options
600
+ const raw = reconnectInitialMs * Math.pow(2, Math.max(0, attempt - 1))
601
+ const capped = Math.min(raw, reconnectMaxMs)
602
+ if (reconnectJitter <= 0) return Math.round(capped)
603
+ const offset = (Math.random() * 2 - 1) * capped * reconnectJitter
604
+ return Math.max(1, Math.round(capped + offset))
605
+ }
606
+
607
+ #scheduleReconnect() {
608
+ if (this.#disposed || this.#reconnectTimer) return
609
+ this.#reconnectAttempt += 1
610
+ const delay = this.backoffFor(this.#reconnectAttempt)
611
+ this.#setState(STATE.reconnecting)
612
+
613
+ this.#reconnectTimer = setTimeout(() => {
614
+ this.#reconnectTimer = null
615
+ this.#connectOnce().catch(() => {
616
+ this.#scheduleReconnect()
617
+ })
618
+ }, delay)
619
+ this.#reconnectTimer.unref?.()
620
+ }
621
+
622
+ #destroySocket() {
623
+ this.#stopHeartbeat()
624
+ const socket = this.#socket
625
+ this.#socket = null
626
+ this.#buffer = Buffer.alloc(0)
627
+ if (socket) {
628
+ socket.removeAllListeners()
629
+ socket.destroy()
630
+ }
631
+ }
632
+
633
+ dispose() {
634
+ this.#disposed = true
635
+ this.#setState(STATE.disposed)
636
+ if (this.#reconnectTimer) {
637
+ clearTimeout(this.#reconnectTimer)
638
+ this.#reconnectTimer = null
639
+ }
640
+ this.#stopHeartbeat()
641
+ this.#failPending('the client was disposed')
642
+ this.#destroySocket()
643
+ }
644
+ }