dsh-remote-deck 0.0.0-stage → 1.46.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.
Files changed (118) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +227 -2
  3. package/README.zh-CN.md +201 -0
  4. package/client.js +8645 -0
  5. package/cordis.patch.yml +6 -0
  6. package/icon.svg +19 -0
  7. package/index.js +701 -0
  8. package/lib/api.js +1452 -0
  9. package/lib/bash-result.js +93 -0
  10. package/lib/connection.js +1133 -0
  11. package/lib/delete.js +199 -0
  12. package/lib/drafts.js +299 -0
  13. package/lib/encoding.js +247 -0
  14. package/lib/file-edit.js +339 -0
  15. package/lib/file-ops.js +402 -0
  16. package/lib/forwards.js +186 -0
  17. package/lib/fs-actions.js +235 -0
  18. package/lib/guide.js +162 -0
  19. package/lib/metrics.js +523 -0
  20. package/lib/remote-shells.js +320 -0
  21. package/lib/remote-terminal.js +427 -0
  22. package/lib/routing.js +695 -0
  23. package/lib/ssh-config.js +118 -0
  24. package/lib/terminal.js +123 -0
  25. package/lib/tool-forward.js +185 -0
  26. package/lib/transfer.js +235 -0
  27. package/lib/upload-chunks.js +306 -0
  28. package/lib/util.js +154 -0
  29. package/locale/README.md +160 -0
  30. package/locale/en-ui.json +477 -0
  31. package/locale/en.json +6 -0
  32. package/locale/zh.json +6 -0
  33. package/package.json +63 -4
  34. package/vendor/codemirror/LICENSE +21 -0
  35. package/vendor/codemirror/README.md +18 -0
  36. package/vendor/codemirror/addon/edit/closebrackets.min.js +8 -0
  37. package/vendor/codemirror/addon/edit/matchbrackets.min.js +8 -0
  38. package/vendor/codemirror/addon/search/search.min.js +8 -0
  39. package/vendor/codemirror/addon/search/searchcursor.min.js +8 -0
  40. package/vendor/codemirror/addon/selection/active-line.min.js +8 -0
  41. package/vendor/codemirror/lib/codemirror.css +344 -0
  42. package/vendor/codemirror/lib/codemirror.min.js +8 -0
  43. package/vendor/codemirror/mode/clike/clike.min.js +8 -0
  44. package/vendor/codemirror/mode/css/css.min.js +8 -0
  45. package/vendor/codemirror/mode/go/go.min.js +8 -0
  46. package/vendor/codemirror/mode/htmlmixed/htmlmixed.min.js +8 -0
  47. package/vendor/codemirror/mode/javascript/javascript.min.js +8 -0
  48. package/vendor/codemirror/mode/markdown/markdown.min.js +8 -0
  49. package/vendor/codemirror/mode/python/python.min.js +8 -0
  50. package/vendor/codemirror/mode/rust/rust.min.js +8 -0
  51. package/vendor/codemirror/mode/shell/shell.min.js +8 -0
  52. package/vendor/codemirror/mode/xml/xml.min.js +8 -0
  53. package/vendor/codemirror/mode/yaml/yaml.min.js +8 -0
  54. package/vendor/node_modules/asn1/Jenkinsfile +65 -0
  55. package/vendor/node_modules/asn1/LICENSE +19 -0
  56. package/vendor/node_modules/asn1/README.md +50 -0
  57. package/vendor/node_modules/asn1/lib/ber/errors.js +13 -0
  58. package/vendor/node_modules/asn1/lib/ber/index.js +27 -0
  59. package/vendor/node_modules/asn1/lib/ber/reader.js +262 -0
  60. package/vendor/node_modules/asn1/lib/ber/types.js +36 -0
  61. package/vendor/node_modules/asn1/lib/ber/writer.js +317 -0
  62. package/vendor/node_modules/asn1/lib/index.js +20 -0
  63. package/vendor/node_modules/asn1/package.json +31 -0
  64. package/vendor/node_modules/bcrypt-pbkdf/CONTRIBUTING.md +13 -0
  65. package/vendor/node_modules/bcrypt-pbkdf/LICENSE +66 -0
  66. package/vendor/node_modules/bcrypt-pbkdf/README.md +45 -0
  67. package/vendor/node_modules/bcrypt-pbkdf/index.js +556 -0
  68. package/vendor/node_modules/bcrypt-pbkdf/package.json +15 -0
  69. package/vendor/node_modules/safer-buffer/LICENSE +21 -0
  70. package/vendor/node_modules/safer-buffer/Porting-Buffer.md +268 -0
  71. package/vendor/node_modules/safer-buffer/Readme.md +156 -0
  72. package/vendor/node_modules/safer-buffer/dangerous.js +58 -0
  73. package/vendor/node_modules/safer-buffer/package.json +34 -0
  74. package/vendor/node_modules/safer-buffer/safer.js +77 -0
  75. package/vendor/node_modules/safer-buffer/tests.js +406 -0
  76. package/vendor/node_modules/ssh2/LICENSE +19 -0
  77. package/vendor/node_modules/ssh2/README.md +1529 -0
  78. package/vendor/node_modules/ssh2/SFTP.md +413 -0
  79. package/vendor/node_modules/ssh2/lib/Channel.js +295 -0
  80. package/vendor/node_modules/ssh2/lib/agent.js +1123 -0
  81. package/vendor/node_modules/ssh2/lib/client.js +2176 -0
  82. package/vendor/node_modules/ssh2/lib/http-agents.js +84 -0
  83. package/vendor/node_modules/ssh2/lib/index.js +44 -0
  84. package/vendor/node_modules/ssh2/lib/keygen.js +582 -0
  85. package/vendor/node_modules/ssh2/lib/protocol/Protocol.js +2136 -0
  86. package/vendor/node_modules/ssh2/lib/protocol/SFTP.js +4052 -0
  87. package/vendor/node_modules/ssh2/lib/protocol/constants.js +356 -0
  88. package/vendor/node_modules/ssh2/lib/protocol/crypto/binding.gyp +23 -0
  89. package/vendor/node_modules/ssh2/lib/protocol/crypto/poly1305.js +43 -0
  90. package/vendor/node_modules/ssh2/lib/protocol/crypto/src/binding.cc +2300 -0
  91. package/vendor/node_modules/ssh2/lib/protocol/crypto.js +1602 -0
  92. package/vendor/node_modules/ssh2/lib/protocol/handlers.js +16 -0
  93. package/vendor/node_modules/ssh2/lib/protocol/handlers.misc.js +1285 -0
  94. package/vendor/node_modules/ssh2/lib/protocol/kex.js +1908 -0
  95. package/vendor/node_modules/ssh2/lib/protocol/keyParser.js +1484 -0
  96. package/vendor/node_modules/ssh2/lib/protocol/node-fs-compat.js +115 -0
  97. package/vendor/node_modules/ssh2/lib/protocol/utils.js +356 -0
  98. package/vendor/node_modules/ssh2/lib/protocol/zlib.js +255 -0
  99. package/vendor/node_modules/ssh2/lib/server.js +1380 -0
  100. package/vendor/node_modules/ssh2/lib/utils.js +336 -0
  101. package/vendor/node_modules/ssh2/package.json +49 -0
  102. package/vendor/node_modules/tweetnacl/AUTHORS.md +28 -0
  103. package/vendor/node_modules/tweetnacl/CHANGELOG.md +221 -0
  104. package/vendor/node_modules/tweetnacl/LICENSE +24 -0
  105. package/vendor/node_modules/tweetnacl/PULL_REQUEST_TEMPLATE.md +20 -0
  106. package/vendor/node_modules/tweetnacl/README.md +459 -0
  107. package/vendor/node_modules/tweetnacl/nacl-fast.js +2388 -0
  108. package/vendor/node_modules/tweetnacl/nacl-fast.min.js +2 -0
  109. package/vendor/node_modules/tweetnacl/nacl.d.ts +98 -0
  110. package/vendor/node_modules/tweetnacl/nacl.js +1175 -0
  111. package/vendor/node_modules/tweetnacl/nacl.min.js +1 -0
  112. package/vendor/node_modules/tweetnacl/package.json +58 -0
  113. package/vendor/xterm/LICENSE.addon-fit +19 -0
  114. package/vendor/xterm/LICENSE.xterm +21 -0
  115. package/vendor/xterm/README.md +9 -0
  116. package/vendor/xterm/addon-fit.js +2 -0
  117. package/vendor/xterm/xterm.css +218 -0
  118. package/vendor/xterm/xterm.js +2 -0
@@ -0,0 +1,427 @@
1
+ /**
2
+ * The built-in Web sidebar terminal, served from this plugin's own ssh2 session.
3
+ *
4
+ * The sidebar (`@deepseek-ai/dsh-api-terminal-controller`) does not use
5
+ * `ctx.terminals`: its `spawn(agent, owner, request, signal)` calls
6
+ * `subprocess.spawnTerminal(...)` directly and wraps the result
7
+ * (`dsh-api-terminal-controller/lib/index.js:981-1009`, verified in the
8
+ * installed app.asar):
9
+ *
10
+ * const handle = await subprocess.spawnTerminal({
11
+ * argv: [shell.path, ...shell.args], cwd, cols, rows,
12
+ * terminalType: 'xterm-256color',
13
+ * env: { DSH_SESSION_ID: agent.id },
14
+ * shellActivity: true, graceMs, signal,
15
+ * })
16
+ * return new BrowserTerminal(handle, info, scrollback, maxBufferedBytes)
17
+ *
18
+ * In a remote workspace that request cannot work: `cwd` is the remote POSIX
19
+ * path, so the local shell never starts. Rather than shelling out to a system
20
+ * OpenSSH client — which a trimmed Windows, a container or an unprivileged host
21
+ * may not have — this module answers the request itself with the ssh2 session the
22
+ * plugin already owns for that connection.
23
+ *
24
+ * Handle contract, read off the only consumer (`BrowserTerminal`, same file,
25
+ * lines 315-573) and the reference producer (`LocalTerminalHandle`,
26
+ * `dsh-subprocess-local/lib/index.js:918-1090`). The consumer uses exactly:
27
+ *
28
+ * - `done` — Promise settling with `{ exitCode, signal }`; a rejection becomes
29
+ * the published `state: 'failed'` with the error message (lines 534-557).
30
+ * - `output` — async-iterable byte chunks; the loop ends when the process ends
31
+ * (line 539). Only these two are read after `write`/`resize`/`terminate`.
32
+ * - `write(data)` — async; throws once the process has exited (line 434).
33
+ * - `resize(cols, rows)` — async; must map to the remote PTY window (line 438).
34
+ * - `inspectActivity()` — async `{ state: 'idle'|'busy'|'unknown', revision }`
35
+ * (lines 360/1011), polled by `TerminalRetention` only while no browser is
36
+ * attached; a continuous `'idle'` for `unattendedTimeoutMs` closes it
37
+ * (`types/retention.js:120-151`).
38
+ * - `terminate()` — async, idempotent, awaited before the screen is released
39
+ * (lines 509/1013) and again by `closeProcess`'s `drained` wait.
40
+ *
41
+ * `pid`, `inspectForeground`, `signalForeground` and `running` are NOT part of
42
+ * the consumed surface: nothing in the controller reads them, and a remote
43
+ * session has no local pid to report, so this handle omits them.
44
+ */
45
+ import { PassThrough } from 'node:stream'
46
+ import { isRemoteShellPath } from './remote-shells.js'
47
+ import { shellQuote } from './util.js'
48
+
49
+ /** `terminalType` the sidebar terminal alone requests (controller line 991). */
50
+ export const SIDEBAR_TERMINAL_TYPE = 'xterm-256color'
51
+ /** Fallback terminate grace when the request carries none. */
52
+ export const DEFAULT_TERMINATE_GRACE_MS = 3000
53
+ /** Output silence after which activity stops being provably busy. */
54
+ export const DEFAULT_ACTIVITY_SILENCE_MS = 3000
55
+
56
+ /**
57
+ * Is this `spawnTerminal` request the Web sidebar terminal?
58
+ *
59
+ * Both conditions are literals at the sidebar call site and both are absent from
60
+ * the other in-tree PTY consumer (`dsh-terminal-bash` passes
61
+ * `terminalType: 'dumb'` and never `shellActivity`), so the model-facing
62
+ * terminal tools keep their local backend.
63
+ */
64
+ export function isSidebarTerminalSpec(spec) {
65
+ return spec !== null
66
+ && typeof spec === 'object'
67
+ && spec.terminalType === SIDEBAR_TERMINAL_TYPE
68
+ && spec.shellActivity === true
69
+ && Array.isArray(spec.argv)
70
+ && spec.argv.length > 0
71
+ }
72
+
73
+ /**
74
+ * The remote command line: change into the workspace, then start a shell.
75
+ *
76
+ * It runs under the connection's login shell on a PTY, so a login shell keeps the
77
+ * user's normal profile and `sh` covers hosts without bash. The path is
78
+ * POSIX-single-quoted, and a missing directory leaves the user in `$HOME`
79
+ * instead of failing the terminal.
80
+ *
81
+ * `shellPath` is the shell picked in the sidebar menu. It is honoured only when
82
+ * {@link isRemoteShellPath} accepts it — an absolute POSIX path to one of the
83
+ * offered shells; a local default such as `cmd.exe`, or a bare name, is not a
84
+ * remote program and keeps the bash-then-sh chain. The chosen shell is still
85
+ * checked on the host before it is exec'd: the menu can be a minute stale, and a
86
+ * terminal that will not start is worse than the fallback the user already has.
87
+ *
88
+ * @param {string} remotePath absolute remote directory
89
+ * @param {unknown} [shellPath] shell chosen in the sidebar menu
90
+ * @returns {string} command for the remote shell
91
+ */
92
+ export function remoteTerminalCommand(remotePath, shellPath) {
93
+ const cd = `cd -- ${shellQuote(remotePath)} 2>/dev/null`
94
+ const fallback = 'if command -v bash >/dev/null 2>&1; then exec bash -l; else exec sh -l; fi'
95
+ if (!isRemoteShellPath(shellPath)) return `${cd}; ${fallback}`
96
+ const quoted = shellQuote(shellPath)
97
+ return `${cd}; if [ -x ${quoted} ]; then exec ${quoted} -l; fi; ${fallback}`
98
+ }
99
+
100
+ /**
101
+ * Decide whether one terminal request should run on the remote host, and how.
102
+ *
103
+ * Every rejection returns null, which means "call the original provider": a
104
+ * local Session, an unreadable workspace, a connection that is no longer
105
+ * configured, or a malformed request all keep today's behaviour instead of
106
+ * guessing. Nothing here throws on bad input.
107
+ *
108
+ * Credentials are deliberately not inspected: ssh2 authenticates with the
109
+ * connection's stored key or password, so both authentication types qualify.
110
+ *
111
+ * @param {object} spec the intercepted `spawnTerminal` request
112
+ * @param {object} deps
113
+ * @param {(cwd: string) => ({ connectionId: string, path: string } | null)} deps.resolveTarget remote target for a path
114
+ * @param {(connectionId: string) => object | undefined} deps.connectionFor configured connection record
115
+ * @returns {{ connectionId: string, remotePath: string, remoteCommand: string, cols: number, rows: number, term: string, graceMs: number } | null}
116
+ */
117
+ export function planRemoteTerminal(spec, deps) {
118
+ if (!isSidebarTerminalSpec(spec)) return null
119
+ if (typeof spec.cwd !== 'string' || spec.cwd.length === 0) return null
120
+
121
+ let target
122
+ try {
123
+ target = deps.resolveTarget(spec.cwd)
124
+ } catch {
125
+ return null
126
+ }
127
+ if (target === null || typeof target !== 'object' || typeof target.path !== 'string' || target.path.length === 0) return null
128
+
129
+ let record
130
+ try {
131
+ record = deps.connectionFor(target.connectionId)
132
+ } catch {
133
+ return null
134
+ }
135
+ if (record === null || typeof record !== 'object') return null
136
+ const host = typeof record.host === 'string' ? record.host.trim() : ''
137
+ const username = typeof record.username === 'string' ? record.username.trim() : ''
138
+ if (host.length === 0 || username.length === 0) return null
139
+
140
+ return {
141
+ connectionId: target.connectionId,
142
+ remotePath: target.path,
143
+ remoteCommand: remoteTerminalCommand(target.path, spec.argv[0]),
144
+ cols: Number.isSafeInteger(spec.cols) && spec.cols >= 2 ? spec.cols : 80,
145
+ rows: Number.isSafeInteger(spec.rows) && spec.rows >= 1 ? spec.rows : 24,
146
+ term: SIDEBAR_TERMINAL_TYPE,
147
+ graceMs: Number.isFinite(spec.graceMs) && spec.graceMs > 0 ? Math.round(spec.graceMs) : DEFAULT_TERMINATE_GRACE_MS,
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Bounded wait for the grace race.
153
+ *
154
+ * Deliberately referenced: `terminate()` must settle even when the rest of the
155
+ * process is already idle (shutdown, or a test with nothing else pending), and
156
+ * the wait is capped by the request's grace.
157
+ */
158
+ function delay(ms) {
159
+ return new Promise((resolve) => {
160
+ setTimeout(resolve, ms)
161
+ })
162
+ }
163
+
164
+ /**
165
+ * One remote PTY, exposed through the subprocess terminal-handle contract.
166
+ *
167
+ * The class is exported so the contract can be tested against a fake channel.
168
+ */
169
+ export class SshTerminalHandle {
170
+ #channel
171
+ #output = new PassThrough()
172
+ #graceMs
173
+ #idleSilenceMs
174
+ #now
175
+ #resolveDone = null
176
+ #rejectDone = null
177
+ #done
178
+ #settled = false
179
+ #terminating = false
180
+ #cleanup = null
181
+ #sawExit = false
182
+ #exitCode = null
183
+ #exitSignal = null
184
+ #paused = false
185
+ #lastOutputAt = Number.NEGATIVE_INFINITY
186
+ #activityState = 'unknown'
187
+ #activityRevision = 0
188
+
189
+ /**
190
+ * @param {object} input
191
+ * @param {object} input.channel connected ssh2 session channel carrying a PTY
192
+ * @param {number} [input.graceMs] terminate grace before settlement is forced
193
+ * @param {number} [input.idleSilenceMs] output silence that ends a provable `busy`
194
+ * @param {() => number} [input.now] clock, injectable for deterministic tests
195
+ */
196
+ constructor({ channel, graceMs = DEFAULT_TERMINATE_GRACE_MS, idleSilenceMs = DEFAULT_ACTIVITY_SILENCE_MS, now = () => Date.now() }) {
197
+ this.#channel = channel
198
+ this.#graceMs = graceMs
199
+ this.#idleSilenceMs = idleSilenceMs
200
+ this.#now = now
201
+ this.#done = new Promise((resolve, reject) => {
202
+ this.#resolveDone = resolve
203
+ this.#rejectDone = reject
204
+ })
205
+ // The consumer attaches to `done` after the constructor returns; keep an
206
+ // early failure from surfacing as an unhandled rejection.
207
+ this.#done.catch(() => {})
208
+
209
+ channel.on('data', (chunk) => this.#push(chunk))
210
+ // A PTY merges the remote stderr into the session stream; a server that
211
+ // still sends extended data must not lose it.
212
+ if (channel.stderr !== null && typeof channel.stderr === 'object' && typeof channel.stderr.on === 'function') {
213
+ channel.stderr.on('data', (chunk) => this.#push(chunk))
214
+ }
215
+ channel.on('exit', (code, signal) => {
216
+ // ssh2 reports `code` for a normal exit and `code = null, signal = 'SIGTERM'`
217
+ // for a signalled one (vendor/node_modules/ssh2/lib/client.js:670-679).
218
+ this.#sawExit = true
219
+ this.#exitCode = Number.isInteger(code) ? code : null
220
+ this.#exitSignal = typeof signal === 'string' && signal.length > 0 ? signal : null
221
+ })
222
+ channel.on('close', () => {
223
+ if (this.#sawExit) this.#finish({ exitCode: this.#exitCode, signal: this.#exitSignal })
224
+ else if (this.#terminating) this.#finish({ exitCode: null, signal: null })
225
+ else this.#fail(new Error('remote-deck: the remote shell channel closed without an exit status'))
226
+ })
227
+ channel.on('error', (error) => this.#fail(error))
228
+
229
+ this.#output.on('drain', () => {
230
+ if (!this.#paused || this.#settled) return
231
+ this.#paused = false
232
+ try {
233
+ channel.resume()
234
+ } catch {
235
+ /* the channel is gone; the close path settles the handle */
236
+ }
237
+ })
238
+ }
239
+
240
+ /** Byte stream for `BrowserTerminal.consume()`. */
241
+ get output() {
242
+ return this.#output
243
+ }
244
+
245
+ /** Settles with `{ exitCode, signal }`, or rejects when the transport failed. */
246
+ get done() {
247
+ return this.#done
248
+ }
249
+
250
+ /** Whether the remote shell has ended and the handle is quiescent. */
251
+ get exited() {
252
+ return this.#settled
253
+ }
254
+
255
+ async write(data) {
256
+ if (this.#settled) throw new Error('terminal process has exited')
257
+ this.#channel.write(data)
258
+ }
259
+
260
+ async resize(cols, rows) {
261
+ if (this.#settled) throw new Error('terminal process has exited')
262
+ // ssh2 takes rows first (vendor/node_modules/ssh2/lib/Channel.js:221-235).
263
+ this.#channel.setWindow(rows, cols, 0, 0)
264
+ }
265
+
266
+ /**
267
+ * Approximate remote activity.
268
+ *
269
+ * Exact stdin-wait evidence is a provider-local capability this transport does
270
+ * not have, and `TerminalRetention` closes a terminal after a continuous
271
+ * `'idle'`, so the conservative rule is: `'idle'` only once the shell has
272
+ * actually ended, `'busy'` while output is arriving, and `'unknown'` otherwise.
273
+ * An unattended remote terminal is therefore never reclaimed on a guess.
274
+ */
275
+ async inspectActivity() {
276
+ const now = this.#now()
277
+ let state = 'unknown'
278
+ if (this.#settled) state = 'idle'
279
+ else if (now - this.#lastOutputAt < this.#idleSilenceMs) state = 'busy'
280
+ if (state !== this.#activityState) {
281
+ this.#activityState = state
282
+ this.#activityRevision += 1
283
+ }
284
+ return { state, revision: this.#activityRevision }
285
+ }
286
+
287
+ /**
288
+ * Close the remote session and settle the handle.
289
+ *
290
+ * Idempotent. A half-dead socket must not hang `BrowserTerminal.closeProcess()`,
291
+ * which awaits `terminate()` and then the drained output, so settlement is
292
+ * forced after the grace even when the server never answers.
293
+ */
294
+ terminate() {
295
+ if (this.#cleanup !== null) return this.#cleanup
296
+ this.#terminating = true
297
+ this.#cleanup = (async () => {
298
+ const channel = this.#channel
299
+ try {
300
+ channel.signal('HUP')
301
+ } catch {
302
+ /* the server may not accept signals; closing the channel is enough */
303
+ }
304
+ try {
305
+ channel.end()
306
+ } catch {
307
+ /* already closed */
308
+ }
309
+ try {
310
+ channel.close()
311
+ } catch {
312
+ /* already closed */
313
+ }
314
+ if (!this.#settled) await Promise.race([this.#done.catch(() => {}), delay(this.#graceMs)])
315
+ this.#finish({ exitCode: null, signal: null })
316
+ })()
317
+ return this.#cleanup
318
+ }
319
+
320
+ #push(chunk) {
321
+ if (this.#settled || chunk === undefined || chunk === null) return
322
+ this.#lastOutputAt = this.#now()
323
+ // Mirror the local provider: stop reading the session while the consumer is
324
+ // behind, so a slow browser cannot grow this buffer without bound.
325
+ if (!this.#output.write(chunk) && !this.#paused) {
326
+ this.#paused = true
327
+ try {
328
+ this.#channel.pause()
329
+ } catch {
330
+ /* the channel is gone; the close path settles the handle */
331
+ }
332
+ }
333
+ }
334
+
335
+ #finish(outcome) {
336
+ if (this.#settled) return
337
+ this.#settled = true
338
+ this.#output.end()
339
+ this.#resolveDone(outcome)
340
+ }
341
+
342
+ #fail(error) {
343
+ if (this.#settled) return
344
+ this.#settled = true
345
+ this.#output.end()
346
+ this.#rejectDone(error instanceof Error ? error : new Error(String(error)))
347
+ }
348
+ }
349
+
350
+ /**
351
+ * Open the remote PTY and wrap it in a handle.
352
+ *
353
+ * Rejections here are the controller's `state: 'failed'` path, so every failure
354
+ * keeps its own message: an unknown connection, an unreachable host, a refused
355
+ * shell request, or a cancelled request.
356
+ *
357
+ * @param {object} input
358
+ * @param {object} input.host the connected (or connectable) `RemoteHost`
359
+ * @param {object} input.secrets credential store for `host.connect`
360
+ * @param {object} input.plan result of {@link planRemoteTerminal}
361
+ * @param {AbortSignal} [input.signal] request cancellation
362
+ * @param {() => number} [input.now] clock, injectable for deterministic tests
363
+ * @returns {Promise<SshTerminalHandle>}
364
+ */
365
+ export async function createSshTerminalHandle({ host, secrets, plan, signal, now }) {
366
+ if (host === undefined || host === null) {
367
+ throw new Error('remote-deck: the connection is no longer configured')
368
+ }
369
+ signal?.throwIfAborted()
370
+ await host.connect(secrets)
371
+ signal?.throwIfAborted()
372
+ const channel = await host.shellCommand(plan.remoteCommand, { cols: plan.cols, rows: plan.rows, term: plan.term })
373
+ if (signal?.aborted === true) {
374
+ // Cancelled while the shell request was in flight: never publish a PTY the
375
+ // caller has already stopped waiting for.
376
+ try {
377
+ channel.close()
378
+ } catch {
379
+ /* already closed */
380
+ }
381
+ signal.throwIfAborted()
382
+ }
383
+ return new SshTerminalHandle({ channel, graceMs: plan.graceMs, now })
384
+ }
385
+
386
+ /**
387
+ * Install the redirect on one subprocess provider.
388
+ *
389
+ * A planned request is answered here and the original provider is never called
390
+ * for it — not even when opening the remote PTY fails, because a silent fallback
391
+ * would hand the user a local shell inside a remote workspace. Unplanned
392
+ * requests reach the original exactly once.
393
+ *
394
+ * @param {{ spawnTerminal?: Function }} subprocess the provider to patch
395
+ * @param {object} deps
396
+ * @param {(cwd: string) => object | null} deps.resolveTarget remote target for a path
397
+ * @param {(connectionId: string) => object | undefined} deps.connectionFor configured connection record
398
+ * @param {(plan: object, spec: object) => Promise<object>} deps.open opens the remote handle
399
+ * @param {(plan: object) => void} [deps.onRemote] observability hook, called only on a takeover
400
+ * @returns {{ restore: () => void }} teardown for the plugin's effect
401
+ */
402
+ export function installTerminalRedirect(subprocess, deps) {
403
+ const original = subprocess === undefined || subprocess === null ? undefined : subprocess.spawnTerminal
404
+ if (typeof original !== 'function') return { restore: () => {} }
405
+ subprocess.spawnTerminal = async function (spec) {
406
+ let plan = null
407
+ try {
408
+ plan = planRemoteTerminal(spec, deps)
409
+ } catch {
410
+ plan = null
411
+ }
412
+ if (plan === null) return original.call(subprocess, spec)
413
+ if (typeof deps.onRemote === 'function') {
414
+ try {
415
+ deps.onRemote(plan)
416
+ } catch {
417
+ /* diagnostics must never break the terminal */
418
+ }
419
+ }
420
+ return deps.open(plan, spec)
421
+ }
422
+ return {
423
+ restore: () => {
424
+ subprocess.spawnTerminal = original
425
+ },
426
+ }
427
+ }