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
package/index.js ADDED
@@ -0,0 +1,701 @@
1
+ /**
2
+ * Remote Deck — host half.
3
+ *
4
+ * One DSH, many execution environments. Each configured SSH host owns one
5
+ * persistent connection; marked workspace stubs route `ctx.fs` through SFTP,
6
+ * a `bash` tool runs commands on the host, and ripgrep moves there too.
7
+ * The agent also gets remote background jobs (`bash` with `run_in_background` or
8
+ * a foreground wait that promotes to a job; collected with the built-in
9
+ * job_output / job_kill) and loopback port forwards (`remote_forward`).
10
+ * A loopback API feeds the sidebar chip, the quick panel and the console.
11
+ */
12
+ import { randomBytes, randomUUID } from 'node:crypto'
13
+ import { existsSync } from 'node:fs'
14
+ import { realpath } from 'node:fs/promises'
15
+ import { homedir } from 'node:os'
16
+ import { dirname, join } from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { CODEMIRROR_ASSET_FILES, createApi } from './lib/api.js'
19
+ import { ConnectionStore, RemoteHost, Secrets, ssh2SelfTest } from './lib/connection.js'
20
+ import { ForwardManager } from './lib/forwards.js'
21
+ import { installWorkspacePromptGuide } from './lib/guide.js'
22
+ import { installRemoteShells, shellProbeCommand } from './lib/remote-shells.js'
23
+ import { createSshTerminalHandle, installTerminalRedirect } from './lib/remote-terminal.js'
24
+ import { Routing } from './lib/routing.js'
25
+ import { readSshConfig } from './lib/ssh-config.js'
26
+ import { TerminalManager } from './lib/terminal.js'
27
+ import { portForwardToolSpec } from './lib/tool-forward.js'
28
+ import { errorText } from './lib/util.js'
29
+ import { renderBashResult, renderPromoted, resolveWorkdir } from './lib/bash-result.js'
30
+
31
+ const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
32
+ const ASSET_DIR = join(PLUGIN_DIR, 'vendor', 'xterm')
33
+ /** The editor's CodeMirror build; the served file list lives with the server. */
34
+ const CODEMIRROR_DIR = join(PLUGIN_DIR, 'vendor', 'codemirror')
35
+ const DSH_HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
36
+ const DATA_DIR = join(DSH_HOME, 'remote-deck')
37
+ const LEGACY_DIR = join(DSH_HOME, 'remote-ssh')
38
+ const WORKSPACE_ROOT = join(DATA_DIR, 'workspaces')
39
+ const LEGACY_WORKSPACE_ROOT = join(LEGACY_DIR, 'workspaces')
40
+ const BUILD = '1.46.0'
41
+ const diagnostics = { pid: process.pid, ssh2: 'pending', ssh2Error: '', checkedAt: 0 }
42
+ void ssh2SelfTest().then((result) => {
43
+ diagnostics.ssh2 = result.ok ? 'ok' : 'failed'
44
+ diagnostics.ssh2Error = result.ok ? '' : result.error
45
+ diagnostics.checkedAt = Date.now()
46
+ if (process.env.DSH_REMOTE_DECK_DEBUG === '1') {
47
+ console.error('[remote-deck] ssh2 self-test', JSON.stringify(diagnostics))
48
+ }
49
+ })
50
+ const SHELL_TIMEOUT_MS = 120000
51
+ /** Shell discovery only fills a menu: bounded hard, and never worth a long wait. */
52
+ const SHELL_PROBE_MAX_BYTES = 4096
53
+ const SHELL_PROBE_TIMEOUT_MS = 8000
54
+
55
+ /** Clamp an integer environment override; invalid values fall back to the default. */
56
+ function readIntEnv(name, fallback, min, max) {
57
+ const raw = process.env[name]
58
+ if (typeof raw !== 'string' || raw.trim().length === 0) return fallback
59
+ const value = Number(raw)
60
+ if (!Number.isFinite(value)) return fallback
61
+ return Math.min(max, Math.max(min, Math.round(value)))
62
+ }
63
+
64
+ /** Remote bash execution limits; dsh-remote-deck-fix/DESIGN.md 5.5 is the contract. */
65
+ const BASH_CONFIG = Object.freeze({
66
+ foregroundTimeoutMs: readIntEnv('DSH_REMOTE_DECK_FOREGROUND_TIMEOUT_MS', 600000, 1000, 7200000),
67
+ maxOutputBytes: readIntEnv('DSH_REMOTE_DECK_MAX_OUTPUT_BYTES', 4 * 1024 * 1024, 65536, 16 * 1024 * 1024),
68
+ killGraceMs: readIntEnv('DSH_REMOTE_DECK_KILL_GRACE_MS', 1000, 200, 10000),
69
+ progressIntervalMs: readIntEnv('DSH_REMOTE_DECK_PROGRESS_MS', 5000, 1000, 60000),
70
+ })
71
+
72
+ /** Resolve a request timeout against the configured default and hard cap. */
73
+ function clampTimeoutMs(value) {
74
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return BASH_CONFIG.foregroundTimeoutMs
75
+ return Math.min(7200000, Math.max(1000, Math.round(value)))
76
+ }
77
+
78
+ /** Services the plugin needs; web server and credentials store stay optional. */
79
+ export const inject = ['fs', 'workingDirectory', 'tools']
80
+ export const name = 'dsh-remote-deck'
81
+
82
+ export function apply(ctx) {
83
+ const debug = (...args) => {
84
+ if (process.env.DSH_REMOTE_DECK_DEBUG === '1') console.error('[remote-deck]', ...args)
85
+ }
86
+
87
+ const store = new ConnectionStore({ dataDir: DATA_DIR, legacyDir: LEGACY_DIR })
88
+ const secrets = new Secrets({ dataDir: DATA_DIR, legacyDir: LEGACY_DIR, credentials: ctx.get('credentials') })
89
+ const hosts = new Map()
90
+
91
+ const hostFor = (id) => {
92
+ let host = hosts.get(id)
93
+ if (host === undefined) {
94
+ const record = store.get(id)
95
+ if (record === undefined) return undefined
96
+ host = new RemoteHost(record, {
97
+ onLog: debug,
98
+ onConnected: (connected) => {
99
+ void forwards.restoreFor(connected.record.id)
100
+ },
101
+ // A ProxyJump hop reuses the credentials of the configured connection it
102
+ // names (by alias, or by host/port/user), so a bastion does not need a
103
+ // second copy of its key in the store.
104
+ resolveHop: (hop) => store.list().find((row) => {
105
+ if (row.name === hop.host) return true
106
+ if (row.host !== hop.host) return false
107
+ if (hop.user.length > 0 && row.username !== hop.user) return false
108
+ return row.port === hop.port
109
+ }),
110
+ })
111
+ hosts.set(id, host)
112
+ } else {
113
+ const record = store.get(id)
114
+ if (record !== undefined) host.record = record
115
+ }
116
+ return host
117
+ }
118
+
119
+ const listHosts = () => [...hosts.values()]
120
+
121
+ const ensureConnected = async (id) => {
122
+ const record = store.get(id)
123
+ if (record === undefined) return
124
+ const host = hostFor(id)
125
+ if (host === undefined) return
126
+ if (host.state === 'connected') return
127
+ if (record.autoConnect === true || process.env.DSH_REMOTE_DECK_AUTOCONNECT === '1') {
128
+ await host.connect(secrets)
129
+ }
130
+ }
131
+
132
+ const routing = new Routing({
133
+ workspaceRoot: WORKSPACE_ROOT,
134
+ legacyRoots: [LEGACY_WORKSPACE_ROOT],
135
+ hostFor,
136
+ ensureConnected,
137
+ getRegistry: () => ctx.get('workspaceRegistry'),
138
+ })
139
+
140
+ const forwards = new ForwardManager({ hostFor, secrets, dataDir: DATA_DIR, onLog: debug })
141
+ const terminals = new TerminalManager({ hostFor, secrets, onLog: debug })
142
+ // --- ctx.fs routing -------------------------------------------------------
143
+ const restoreFs = routing.installFs(ctx.fs)
144
+ ctx.effect(() => () => restoreFs(), 'remote-deck: fs patch')
145
+
146
+ // --- remote workspace prompt guidance -------------------------------------
147
+ // Adding a remote workspace used to write an `AGENTS.md` into the user's own
148
+ // project directory. Nothing is written now: the model learns that the
149
+ // workspace is remote from a system-prompt section plus one runtime-context
150
+ // line. Both are registered once and resolved per model step, so a local
151
+ // Session contributes empty text and never sees them; `ctx.inject` keeps this
152
+ // plugin loadable on a profile that exposes no `systemPrompt` service.
153
+ ctx.inject(['systemPrompt'], (scope) => {
154
+ installWorkspacePromptGuide(scope, {
155
+ directoryOf: (agent) => ctx.workingDirectory.get(agent.session),
156
+ resolveTarget: (cwd) => routing.resolveTarget(cwd, undefined),
157
+ hostNameFor: (connectionId) => store.get(connectionId)?.name,
158
+ })
159
+ })
160
+
161
+ // --- bash tool ------------------------------------------------------------
162
+ /**
163
+ * Bounded foreground execution used only when the profile exposes no job
164
+ * controller (or the job preflight rejects the call). The deadline closes
165
+ * the channel instead of leaving the turn waiting forever; the remote
166
+ * process may continue, which the notice states explicitly.
167
+ */
168
+ const runForegroundWithDeadline = async (host, cwd, exec, timeoutMs, command) => {
169
+ const controller = new AbortController()
170
+ let timedOut = false
171
+ const forwardAbort = () => controller.abort()
172
+ if (exec.signal !== undefined) {
173
+ if (exec.signal.aborted === true) controller.abort()
174
+ else exec.signal.addEventListener('abort', forwardAbort, { once: true })
175
+ }
176
+ const timer = setTimeout(() => {
177
+ timedOut = true
178
+ controller.abort()
179
+ }, timeoutMs)
180
+ timer.unref?.()
181
+ try {
182
+ const result = await host.runCommand(command, cwd, {
183
+ signal: controller.signal,
184
+ maxBytes: BASH_CONFIG.maxOutputBytes,
185
+ })
186
+ if (timedOut === true) {
187
+ return {
188
+ text: `[command still running after ${timeoutMs}ms; background jobs are unavailable in this profile, so it may keep running on the remote host]`,
189
+ exitCode: null,
190
+ }
191
+ }
192
+ return renderBashResult(result, { maxBytes: BASH_CONFIG.maxOutputBytes })
193
+ } finally {
194
+ clearTimeout(timer)
195
+ if (exec.signal !== undefined) exec.signal.removeEventListener('abort', forwardAbort)
196
+ }
197
+ }
198
+
199
+ // Every call registers a DSH background job, waits a bounded time in the
200
+ // foreground, and on timeout returns the job id instead of killing the
201
+ // remote process. This mirrors @deepseek-ai/dsh-tool-bash: long legitimate
202
+ // tasks are promoted, never interrupted; only job_kill / the Stop button
203
+ // terminate the remote process.
204
+ const bashToolConfiguration = {
205
+ name: 'bash',
206
+ description:
207
+ 'Run a shell command on the connected remote SSH host. Use it for every command inside a remote workspace: build, test, git, ripgrep, package managers. The working directory is the remote workspace (a POSIX path); use POSIX paths, not Windows paths. The working directory is strict: a missing directory fails the command instead of falling back to the home directory. Long commands keep running as a background job after the foreground wait; use job_output to read their output and job_kill to stop them.',
208
+ parameters: {
209
+ type: 'object',
210
+ properties: {
211
+ command: { type: 'string', description: 'The bash command to run on the remote host.' },
212
+ description: { type: 'string', description: 'Clear, concise description of what this command does in 5-10 words.' },
213
+ workdir: { type: 'string', description: 'Optional remote working directory. An absolute POSIX path is used as-is; a relative path resolves against the session workspace.' },
214
+ timeoutMs: { type: 'number', description: 'How long to wait in the foreground before moving the command to a background job. Defaults to the plugin limit; the command is not killed on timeout.' },
215
+ run_in_background: { type: 'boolean', description: 'Run the command as a background job and return its job id immediately; collect it with job_output and stop it with job_kill.' },
216
+ },
217
+ required: ['command'],
218
+ additionalProperties: false,
219
+ },
220
+ output: {
221
+ schema: {
222
+ type: 'object',
223
+ properties: {
224
+ text: { type: 'string' },
225
+ exitCode: { oneOf: [{ type: 'integer' }, { type: 'null' }] },
226
+ jobId: { type: 'string' },
227
+ },
228
+ required: ['text', 'exitCode'],
229
+ additionalProperties: false,
230
+ },
231
+ render: (_args, value) => [{ type: 'text', text: value.text }],
232
+ },
233
+ async execute(args, exec) {
234
+ try {
235
+ const sessionCwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
236
+ const target = routing.resolveTarget(sessionCwd, undefined)
237
+ if (target === null) {
238
+ return {
239
+ text: `The bash tool only runs inside a remote workspace. The current working directory is local: ${JSON.stringify(sessionCwd)}. Use pwsh for local commands.`,
240
+ exitCode: 1,
241
+ }
242
+ }
243
+ const host = hostFor(target.connectionId)
244
+ if (host === undefined) return { text: 'That connection no longer exists; recreate it.', exitCode: 1 }
245
+ await host.connect(secrets)
246
+ const resolved = resolveWorkdir(args.workdir, target.path)
247
+ if (resolved.error !== undefined) return { text: resolved.error, exitCode: 1 }
248
+ if (exec.signal !== undefined && exec.signal.aborted === true) {
249
+ return { text: 'Error: tool call aborted', exitCode: 1 }
250
+ }
251
+ const timeoutMs = clampTimeoutMs(args.timeoutMs)
252
+ const background = args.run_in_background === true
253
+ const jobs = ctx.get('jobs')
254
+ if (jobs === undefined) {
255
+ if (background === true) {
256
+ return {
257
+ text: 'Error: run_in_background requires the DSH background-jobs capability (load @deepseek-ai/dsh-tool-jobs in this profile).',
258
+ exitCode: 1,
259
+ }
260
+ }
261
+ return await runForegroundWithDeadline(host, resolved.cwd, exec, timeoutMs, args.command)
262
+ }
263
+ const owner = exec.agent?.id
264
+ const jobKey = randomUUID().replaceAll('-', '').slice(0, 16)
265
+ const startedAt = Date.now()
266
+ let commandResultPromise = null
267
+ let commandHandle = null
268
+ let pendingKill = null
269
+ let jobId
270
+ try {
271
+ jobId = jobs.start({
272
+ kind: 'bash',
273
+ label: String(args.command).slice(0, 80),
274
+ ...(owner !== undefined ? { owner } : {}),
275
+ ...(typeof exec.callId === 'string'
276
+ ? { toolCall: { callId: exec.callId, ...(typeof exec.rootCallId === 'string' ? { rootCallId: exec.rootCallId } : {}) } }
277
+ : {}),
278
+ outputLimitBytes: BASH_CONFIG.maxOutputBytes,
279
+ run: (handle) => {
280
+ commandResultPromise = (async () => {
281
+ const started = await host.startCommand(args.command, resolved.cwd, {
282
+ jobKey,
283
+ maxBytes: BASH_CONFIG.maxOutputBytes,
284
+ killGraceMs: BASH_CONFIG.killGraceMs,
285
+ onChunk: (channel, text) => {
286
+ try {
287
+ handle.append(text, { channel })
288
+ } catch {
289
+ /* job already settled */
290
+ }
291
+ },
292
+ })
293
+ commandHandle = started
294
+ if (pendingKill !== null) void started.kill(pendingKill)
295
+ return await started.done
296
+ })()
297
+ const timer = setInterval(() => {
298
+ try {
299
+ handle.updateProgress(`running for ${Math.round((Date.now() - startedAt) / 1000)}s`)
300
+ } catch {
301
+ /* settled */
302
+ }
303
+ }, BASH_CONFIG.progressIntervalMs)
304
+ timer.unref?.()
305
+ const done = commandResultPromise.then(
306
+ (result) => {
307
+ clearInterval(timer)
308
+ if (typeof result.transportError === 'string' && result.transportError.length > 0) {
309
+ return { status: 'failed', detail: result.transportError }
310
+ }
311
+ if (pendingKill !== null || (typeof result.signal === 'string' && result.signal.length > 0)) {
312
+ return {
313
+ status: 'killed',
314
+ detail: pendingKill !== null ? pendingKill : `signal: ${result.signal}`,
315
+ }
316
+ }
317
+ return { status: 'completed', detail: `exit code: ${result.code}` }
318
+ },
319
+ (error) => {
320
+ clearInterval(timer)
321
+ return { status: 'failed', detail: errorText(error) }
322
+ },
323
+ )
324
+ return {
325
+ done,
326
+ cancel: (reason) => {
327
+ pendingKill = typeof reason === 'string' && reason.length > 0 ? reason : 'killed'
328
+ if (commandHandle !== null) void commandHandle.kill(pendingKill)
329
+ },
330
+ }
331
+ },
332
+ })
333
+ } catch (jobError) {
334
+ const message = errorText(jobError)
335
+ if (!/job controller|jobs unavailable|no job controller/i.test(message)) {
336
+ return { text: `Error: ${message}`, exitCode: 1 }
337
+ }
338
+ if (background === true) {
339
+ return { text: `Error: run_in_background is unavailable in this profile: ${message}`, exitCode: 1 }
340
+ }
341
+ const rendered = await runForegroundWithDeadline(host, resolved.cwd, exec, timeoutMs, args.command)
342
+ const notice = `[background jobs unavailable: ${message}]`
343
+ return { ...rendered, text: `${notice}\n${rendered.text}`.trimEnd() }
344
+ }
345
+ if (background === true) {
346
+ return {
347
+ text: `[started background job ${jobId}; use job_output to read output, job_kill to stop]`,
348
+ exitCode: null,
349
+ jobId,
350
+ }
351
+ }
352
+ let view
353
+ try {
354
+ view = await jobs.wait(jobId, timeoutMs, owner, exec.signal)
355
+ } catch (waitError) {
356
+ if (exec.signal === undefined || exec.signal.aborted !== true) {
357
+ try {
358
+ jobs.kill(jobId, owner, 'wait failed')
359
+ } catch {
360
+ /* already settled */
361
+ }
362
+ return { text: `Error: ${errorText(waitError)}`, exitCode: null, jobId }
363
+ }
364
+ try {
365
+ jobs.kill(jobId, owner, 'tool call aborted')
366
+ } catch {
367
+ /* already settled */
368
+ }
369
+ try {
370
+ await jobs.wait(jobId, 5000, owner)
371
+ } catch {
372
+ /* settlement takes longer; the record stays */
373
+ }
374
+ try {
375
+ jobs.remove(jobId, owner)
376
+ } catch {
377
+ /* not settled/removable yet */
378
+ }
379
+ return { text: 'Error: tool call aborted', exitCode: null, jobId }
380
+ }
381
+ if (view.status === 'running' || view.status === 'stopping') {
382
+ try {
383
+ const read = jobs.read(jobId, owner)
384
+ return renderPromoted(read, jobId, timeoutMs)
385
+ } catch {
386
+ return {
387
+ text: `[still running after ${timeoutMs}ms; moved to background job ${jobId}; use job_output to read output, job_kill to stop]`,
388
+ exitCode: null,
389
+ jobId,
390
+ }
391
+ }
392
+ }
393
+ let result = null
394
+ try {
395
+ result = commandResultPromise === null ? null : await commandResultPromise
396
+ } catch (starterError) {
397
+ try {
398
+ jobs.remove(jobId, owner)
399
+ } catch {
400
+ /* keep the record when removal is not allowed */
401
+ }
402
+ return { text: errorText(starterError), exitCode: 1, jobId }
403
+ }
404
+ try {
405
+ jobs.remove(jobId, owner)
406
+ } catch {
407
+ /* keep the record when removal is not allowed */
408
+ }
409
+ return renderBashResult(result ?? { code: -1 }, { maxBytes: BASH_CONFIG.maxOutputBytes })
410
+ } catch (error) {
411
+ return { text: errorText(error), exitCode: 1 }
412
+ }
413
+ },
414
+ }
415
+ try {
416
+ ctx.tools.register(bashToolConfiguration)
417
+ } catch (error) {
418
+ // POSIX compositions already register the official bash tool; a duplicate
419
+ // name throws and used to abort the whole plugin load. Fall back to a
420
+ // remote-only tool name instead of failing the composition.
421
+ const message = errorText(error)
422
+ debug('bash tool registration failed:', message)
423
+ try {
424
+ ctx.tools.register({
425
+ ...bashToolConfiguration,
426
+ name: 'remote_bash',
427
+ description: `${bashToolConfiguration.description} (remote-only tool; the official bash tool is already registered on this platform)`,
428
+ })
429
+ } catch (fallbackError) {
430
+ debug('remote bash fallback registration failed:', errorText(fallbackError))
431
+ }
432
+ }
433
+
434
+ // --- shared session -> remote target resolution ---------------------------
435
+ const resolveSession = async (exec) => {
436
+ const sessionCwd = await ctx.workingDirectory.ensure(exec.agent, exec.signal)
437
+ return routing.resolveTarget(sessionCwd, undefined)
438
+ }
439
+
440
+ // --- agent-facing port forwarding ----------------------------------------
441
+ ctx.tools.register(portForwardToolSpec({
442
+ resolveSession,
443
+ forwards,
444
+ hostNameFor: (connectionId) => store.get(connectionId)?.name,
445
+ }))
446
+
447
+ // --- subprocess patch: remote ripgrep and the remote sidebar terminal -----
448
+ const subprocessService = ctx.get('subprocess')
449
+ const originalSpawn = subprocessService !== undefined && typeof subprocessService.spawn === 'function'
450
+ ? subprocessService.spawn
451
+ : null
452
+ if (originalSpawn !== null) {
453
+ subprocessService.spawn = function (spec) {
454
+ try {
455
+ const argv = spec !== null && typeof spec === 'object' && Array.isArray(spec.argv) ? spec.argv : null
456
+ if (argv !== null && argv.length > 0 && /(^|[\\/])rg(\.exe)?$/i.test(String(argv[0]))) {
457
+ const target = routing.resolveTarget(spec.cwd, undefined)
458
+ if (target !== null) {
459
+ const host = hostFor(target.connectionId)
460
+ if (host !== undefined) return routing.makeRemoteRipgrep(host, target.path, argv.slice(1), spec)
461
+ }
462
+ }
463
+ } catch {
464
+ /* fall back to the local process */
465
+ }
466
+ return originalSpawn.call(this, spec)
467
+ }
468
+ }
469
+
470
+ // The built-in Web sidebar terminal opens its PTY through `spawnTerminal`,
471
+ // not through `ctx.terminals`. In a remote workspace the local shell cannot
472
+ // start at all (its `cwd` is a POSIX path), so that one request is answered
473
+ // with a PTY on the ssh2 session this plugin already owns for the connection —
474
+ // no system OpenSSH client is required. Every other terminal request keeps the
475
+ // local shell untouched, and a failed remote open is reported instead of
476
+ // quietly falling back.
477
+ // `DSH_REMOTE_DECK_REMOTE_TERMINAL=0` turns the redirect off entirely and
478
+ // leaves the provider's local terminal, for a deployment that wants the
479
+ // stock behaviour back without uninstalling the plugin.
480
+ const remoteTerminalEnabled = process.env.DSH_REMOTE_DECK_REMOTE_TERMINAL !== '0'
481
+ const terminalRedirect = remoteTerminalEnabled
482
+ ? installTerminalRedirect(subprocessService, {
483
+ resolveTarget: (cwd) => routing.resolveTarget(cwd, undefined),
484
+ connectionFor: (connectionId) => store.get(connectionId),
485
+ onRemote: (plan) => debug('remote sidebar terminal on', plan.connectionId, plan.remotePath),
486
+ open: (plan, spec) => {
487
+ const host = hostFor(plan.connectionId)
488
+ if (host === undefined) throw new Error(`remote-deck: connection ${plan.connectionId} is no longer configured`)
489
+ const signal = spec !== null && typeof spec === 'object' ? spec.signal : undefined
490
+ return createSshTerminalHandle({ host, secrets, plan, signal })
491
+ },
492
+ })
493
+ : { restore: () => {} }
494
+ ctx.effect(() => () => {
495
+ if (subprocessService === undefined) return
496
+ if (originalSpawn !== null) subprocessService.spawn = originalSpawn
497
+ terminalRedirect.restore()
498
+ }, 'remote-deck: subprocess patch')
499
+
500
+ // --- remote shell menu ----------------------------------------------------
501
+ // The sidebar's shell dropdown asks `terminalController.shells(agent, signal)`
502
+ // for the shells of the Session's execution environment. That method is the
503
+ // only one on the path that receives the agent, and the gateway resolves it on
504
+ // every call, so a remote Session can answer with its own shells while every
505
+ // local Session keeps the stock list. `DSH_REMOTE_DECK_REMOTE_TERMINAL=0`
506
+ // turns this off with the terminal it belongs to: with the local shell back in
507
+ // place, offering remote shells would be a lie.
508
+ if (remoteTerminalEnabled) {
509
+ ctx.inject(['terminalController'], (scope) => {
510
+ const remoteShells = installRemoteShells(scope.get('terminalController'), {
511
+ // The controller reads the committed directory through the agent's own
512
+ // context (`this.execution(agent).workingDirectory.get(agent.session)`,
513
+ // dsh-api-terminal-controller/lib/index.js:785-790); the provider this
514
+ // plugin injects is the same service, and is the fallback here.
515
+ cwdFor: (agent) => {
516
+ if (agent === null || typeof agent !== 'object') return undefined
517
+ let workingDirectory = ctx.workingDirectory
518
+ try {
519
+ const scoped = agent.ctx !== undefined && typeof agent.ctx.get === 'function' ? agent.ctx.get('workingDirectory') : undefined
520
+ if (scoped !== undefined) workingDirectory = scoped
521
+ } catch {
522
+ /* the agent context is gone; the plugin's provider still answers */
523
+ }
524
+ if (workingDirectory === undefined || typeof workingDirectory.get !== 'function') return undefined
525
+ try {
526
+ const cwd = workingDirectory.get(agent.session)
527
+ return typeof cwd === 'string' && cwd.length > 0 ? cwd : undefined
528
+ } catch {
529
+ return undefined
530
+ }
531
+ },
532
+ resolveTarget: (cwd) => routing.resolveTarget(cwd, undefined),
533
+ probe: async (connectionId) => {
534
+ const host = hostFor(connectionId)
535
+ if (host === undefined) throw new Error(`remote-deck: connection ${connectionId} is no longer configured`)
536
+ await host.ensure(secrets)
537
+ const result = await host.runCommand(shellProbeCommand(), null, {
538
+ maxBytes: SHELL_PROBE_MAX_BYTES,
539
+ timeoutMs: SHELL_PROBE_TIMEOUT_MS,
540
+ })
541
+ if (typeof result.transportError === 'string' && result.transportError.length > 0) throw new Error(result.transportError)
542
+ return result.stdout
543
+ },
544
+ onRemote: (target, list) => debug('remote shells on', target.connectionId, list.map((shell) => shell.name).join(',')),
545
+ })
546
+ debug('remote shell menu:', remoteShells.installed ? 'installed' : remoteShells.reason)
547
+ scope.effect(() => () => remoteShells.restore(), 'remote-deck: remote shells')
548
+ })
549
+ }
550
+
551
+ // --- loopback API ---------------------------------------------------------
552
+ const token = randomBytes(24).toString('hex')
553
+ let apiPort = 0
554
+
555
+ const testConnection = async (input) => {
556
+ const record = {
557
+ id: 'test-' + randomBytes(4).toString('hex'),
558
+ name: String(input.name || 'test'),
559
+ host: String(input.host || '').trim(),
560
+ port: Number(input.port) || 22,
561
+ username: String(input.username || '').trim() || 'root',
562
+ authType: input.authType === 'password' ? 'password' : 'key',
563
+ privateKeyPath: String(input.privateKeyPath || '').trim(),
564
+ color: 'blue',
565
+ }
566
+ if (record.host.length === 0) throw new Error('host is required')
567
+ const tempSecrets = {
568
+ get: async (_id, kind) => {
569
+ if (kind === 'PASSWORD') return typeof input.password === 'string' && input.password.length > 0 ? input.password : null
570
+ return typeof input.passphrase === 'string' && input.passphrase.length > 0 ? input.passphrase : null
571
+ },
572
+ set: async () => {},
573
+ clear: async () => {},
574
+ describe: async () => ({ password: Boolean(input.password), passphrase: Boolean(input.passphrase) }),
575
+ }
576
+ const host = new RemoteHost(record, {})
577
+ try {
578
+ await host.connect(tempSecrets)
579
+ const status = host.status()
580
+ return { latencyMs: status.latencyMs ?? null, sys: status.sys ?? null }
581
+ } finally {
582
+ host.dispose()
583
+ }
584
+ }
585
+
586
+ const dropHost = (id) => {
587
+ const host = hosts.get(id)
588
+ hosts.delete(id)
589
+ try {
590
+ host?.dispose()
591
+ } catch {
592
+ /* ignore */
593
+ }
594
+ }
595
+
596
+ const server = createApi({
597
+ token,
598
+ store,
599
+ secrets,
600
+ hostFor,
601
+ dropHost,
602
+ listHosts,
603
+ routing,
604
+ getRegistry: () => ctx.get('workspaceRegistry'),
605
+ build: BUILD,
606
+ diagnostics,
607
+ homeDir: DSH_HOME,
608
+ dataDir: DATA_DIR,
609
+ readSshConfig,
610
+ testConnection,
611
+ terminals,
612
+ forwards,
613
+ assetDir: ASSET_DIR,
614
+ assetDirs: [{ dir: CODEMIRROR_DIR, files: CODEMIRROR_ASSET_FILES }],
615
+ })
616
+ server.on('error', (error) => {
617
+ console.error('[remote-deck] api server failed:', errorText(error))
618
+ })
619
+ if (process.env.DSH_REMOTE_DECK_DEBUG === '1') debug('api token', token)
620
+ server.listen(0, '127.0.0.1', () => {
621
+ apiPort = server.address().port
622
+ debug('api ready on', apiPort)
623
+ })
624
+
625
+ ctx.effect(() => () => {
626
+ try {
627
+ server.close()
628
+ } catch {
629
+ /* already closed */
630
+ }
631
+ }, 'remote-deck: api')
632
+
633
+ // --- inject connection info into the page --------------------------------
634
+ ctx.inject(['webServer'], (webCtx) => {
635
+ webCtx.on('webserver/index-inject', (table) => {
636
+ table.push({
637
+ kind: 'global',
638
+ name: '__DSH_REMOTE_DECK__',
639
+ value: {
640
+ get port() {
641
+ return apiPort
642
+ },
643
+ token,
644
+ build: BUILD,
645
+ dataDir: DATA_DIR,
646
+ },
647
+ })
648
+ })
649
+ })
650
+
651
+ // --- auto-connect at startup ---------------------------------------------
652
+ ctx.effect(() => {
653
+ const timer = setTimeout(() => {
654
+ for (const record of store.list()) {
655
+ if (record.autoConnect !== true) continue
656
+ hostFor(record.id)?.connect(secrets).catch((error) => debug('auto-connect failed', record.name, errorText(error)))
657
+ }
658
+ }, 1500)
659
+ timer.unref?.()
660
+ return () => clearTimeout(timer)
661
+ }, 'remote-deck: auto-connect')
662
+
663
+ // A moved DSH home (folder migration, drive change, junction) leaves stored
664
+ // workspace paths spelled with the old alias; re-register under the canonical
665
+ // path keeping the title, otherwise sessions cannot attach.
666
+ ctx.inject(['workspaceRegistry'], (scope) => {
667
+ void (async () => {
668
+ const registry = scope.get('workspaceRegistry')
669
+ if (registry === undefined) return
670
+ const roots = [WORKSPACE_ROOT, LEGACY_WORKSPACE_ROOT].filter((root) => existsSync(root))
671
+ for (const entity of [...registry.list()]) {
672
+ try {
673
+ const canonical = await realpath(entity.path)
674
+ if (canonical === entity.path) continue
675
+ if (!roots.some((root) => canonical.toLowerCase().startsWith(root.toLowerCase()))) continue
676
+ const title = entity.title
677
+ await registry.delete(entity.id)
678
+ await registry.create(canonical, title)
679
+ console.log('[remote-deck] re-registered moved workspace', canonical)
680
+ } catch (error) {
681
+ debug('workspace heal failed:', errorText(error))
682
+ }
683
+ }
684
+ })()
685
+ })
686
+
687
+ // --- teardown -------------------------------------------------------------
688
+ ctx.effect(() => () => {
689
+ terminals.closeAll()
690
+ forwards.closeAll()
691
+ for (const host of hosts.values()) host.dispose()
692
+ hosts.clear()
693
+ try {
694
+ server.close()
695
+ } catch {
696
+ /* already closed */
697
+ }
698
+ }, 'remote-deck: teardown')
699
+
700
+ debug('loaded', BUILD, 'data dir', DATA_DIR, 'legacy', LEGACY_DIR)
701
+ }