dsh-ssh-compute 0.0.0-stage → 1.2.3

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,17 @@
1
+ # This bundle inserts the ssh-compute tool process-wide, so every agent preset
2
+ # gets it without declaring anything in the preset itself.
3
+ #
4
+ # Do NOT also add a `ssh-compute` row to a preset: DSH registers tools by name
5
+ # and a second registration fails with
6
+ # `tool "ssh-compute" is already registered in this scope`.
7
+ #
8
+ # The entry name is PATH-RELATIVE on purpose. DSH anchors a relative `name:` to
9
+ # the directory of the patch file that declared it, so this row always loads
10
+ # this bundle's own `index.js` whatever the package folder is called.
11
+ #
12
+ # No servers are declared here: a bundle that shipped somebody's host names would
13
+ # connect the wrong machine for everyone who installs it. The settings page on the
14
+ # plugin's own page is where servers are added.
15
+ - insert:
16
+ - id: dsh-ssh-compute
17
+ name: './index.js'
package/icon.svg ADDED
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none" role="img" aria-label="Remote compute over SSH">
2
+ <rect x="6" y="7" width="40" height="29" rx="7" fill="#3B82F6" fill-opacity="0.15" stroke="#3B82F6" stroke-width="2.6"/>
3
+ <path d="M15 15.5 L21.5 21.5 L15 27.5" stroke="#3B82F6" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>
4
+ <path d="M26 27.5 L33 27.5" stroke="#3B82F6" stroke-width="2.8" stroke-linecap="round"/>
5
+ <path d="M28 48 L50 48" stroke="#0EA5E9" stroke-width="2.8" stroke-linecap="round"/>
6
+ <path d="M44 42 L50 48 L44 54" stroke="#0EA5E9" stroke-width="2.8" stroke-linecap="round" stroke-linejoin="round"/>
7
+ </svg>
package/index.js ADDED
@@ -0,0 +1,578 @@
1
+ // dsh-ssh-compute — one tool that hands the agent a remote machine.
2
+ //
3
+ // The plugin owns exactly one capability: start a job on a configured SSH
4
+ // server, then look at it, read it, stop it, and move files both ways. It does
5
+ // not decide what is "compute-heavy" and it installs nothing: the agent probes
6
+ // the machine (`nproc`, `free`, `nvidia-smi`) and decides for itself.
7
+ //
8
+ // Shape of a job is a directory on the server — see `lib/remote.js`, which is
9
+ // also why this plugin keeps no state of its own.
10
+
11
+ import { resolve } from 'node:path'
12
+
13
+ import { resolveConfig, selectServer, serverNameFromJobId } from './lib/config.js'
14
+ import { createKeyStore } from './lib/keys.js'
15
+ import { assertCommandAllowed, assertUploadAllowed } from './lib/guard.js'
16
+ import { startJob, waitJob, jobStatus, readLog, killJob, listJobs, probeServer } from './lib/remote.js'
17
+ import { cleanupControlSockets } from './lib/ssh.js'
18
+ import { readSshConfigFile } from './lib/sshconfig.js'
19
+ import { upload, download } from './lib/transfer.js'
20
+ import { loadSchemaBuilder } from './lib/schema.js'
21
+
22
+ export const name = 'dsh-ssh-compute'
23
+ export const inject = ['tools']
24
+
25
+ // The schema is what gives this plugin a settings surface: the platform
26
+ // projects the config of every entry that declares one. Loading the builder must
27
+ // never be what decides whether the tool exists, so a missing or incompatible
28
+ // package only costs the settings page.
29
+ const Schema = await loadSchemaBuilder()
30
+
31
+ /**
32
+ * The settings the plugin exposes.
33
+ *
34
+ * EVERY field is `.volatile()`, and that is not decoration. DSH's settings
35
+ * service projects a plugin's config into a form only through `volatileForm()`,
36
+ * which keeps a field only when its nearest ancestor is marked volatile — a
37
+ * schema without one disappears from `describe()` entirely, and the page sees
38
+ * `configForms` report the namespace as unavailable. A volatile field also
39
+ * resolves to a live cell rather than a value, so an edit is written in place
40
+ * and read at call time without remounting this plugin; `resolveConfig`
41
+ * unboxes them.
42
+ *
43
+ * A volatile field must not sit inside another volatile one, so the server
44
+ * ARRAY is the volatile field and its element fields are plain.
45
+ */
46
+ function defineConfig(builder) {
47
+ return builder.object({
48
+ servers: builder.array(builder.object({
49
+ name: builder.string().default('').description('短名字,工具的 `server` 参数用它引用这台机器,如 gpu01。'),
50
+ host: builder.string().default('').description('地址或域名。'),
51
+ port: builder.number().default(22).description('SSH 端口,默认 22。'),
52
+ user: builder.string().default('').description('登录用户名。'),
53
+ keyPath: builder.string().default('').description('私钥文件路径。留空则自动使用 ~/.ssh 下的第一个私钥;一个都没找到就不传 -i,交给 ssh 自己的配置和 agent。'),
54
+ keyText: builder.string().default('').description('直接粘贴私钥内容(优先级高于 keyPath)。会写到系统临时目录的 0600 文件,插件卸载时删除。'),
55
+ extraArgs: builder.string().default('').description('额外的 ssh 参数,空格分隔,例如 `-J bastion` 或 `-o UseKeychain=no`。这些 token 直接进 argv、不经过 shell;因此值本身不能含空格(rsync 传输会把 `-e` 再按空格切一次)。'),
56
+ }).description('一台远程服务器')).description('可用的远程服务器列表。省略 `server` 仅在只配了一台时有效。').volatile(),
57
+ remoteRoot: builder.string().default('~/dsh-compute').description('远端任务目录。每个任务是其中的一个子目录,含 cmd.sh、pid、exit、output.log。').volatile(),
58
+ guard: builder.boolean().default(true).description('拦截明显破坏性的远端命令(rm -rf /、mkfs、dd 到磁盘等)和往系统目录的上传。调用方传 allowDangerous: true 可放行。').volatile(),
59
+ connectTimeoutMs: builder.number().default(15000).description('建立 SSH 连接的超时(毫秒)。').volatile(),
60
+ commandTimeoutMs: builder.number().default(30000).description('非任务命令(status/logs/kill 等)的超时(毫秒)。').volatile(),
61
+ logTailLines: builder.number().default(40).description('status 顺带返回的日志行数;0 表示不返回。').volatile(),
62
+ maxLogBytes: builder.number().default(65536).description('logs 一次最多返回的字节数。').volatile(),
63
+ listLimit: builder.number().default(60).description('list 最多返回多少个任务。').volatile(),
64
+ maxFileSizeMb: builder.number().default(10240).description('单个文件大小上限(MiB),由任务包装脚本用 `ulimit -f` 施加;0 表示不限制。超限任务收到 SIGXFSZ,以 153 退出。').volatile(),
65
+ minFreeSpaceMb: builder.number().default(1024).description('任务目录所在卷的可用空间低于此值(MiB)时拒绝启动新任务。').volatile(),
66
+ waitTimeoutMs: builder.number().default(300000).description('`wait` 动作的默认等待上限(毫秒)。').volatile(),
67
+ maxRunningJobs: builder.number().default(64).description('同一台服务器上同时运行的任务上限;`run` 超过它会被拒绝并报出当前数量。设为 0 表示不限制。').volatile(),
68
+ reuseConnection: builder.boolean().default(true).description('复用 ssh 连接(ControlMaster)。仅在 Linux/macOS 上生效:Windows 的 OpenSSH 在设置 ControlPath 后会直接断开连接,所以那里始终不用。').volatile(),
69
+ reuseIdleSeconds: builder.number().default(300).description('复用的连接空闲多少秒后关闭。').volatile(),
70
+ recordResources: builder.boolean().default(true).description('记录任务环境(hostname/内核/编译器版本)与峰值内存。').volatile(),
71
+ }).description('dsh-ssh-compute 的远程服务器与默认值。')
72
+ }
73
+
74
+ /** This plugin's config schema, or undefined when no builder is available. */
75
+ export const Config = Schema === null ? undefined : defineConfig(Schema)
76
+
77
+ /** The read-only routes the detail page's test button calls. */
78
+ const SERVERS_ROUTE = '/dsh-ssh-compute/servers'
79
+ const TEST_ROUTE = '/dsh-ssh-compute/test'
80
+ /** The hosts this machine's own ssh already knows, offered to the settings form. */
81
+ const SSH_CONFIG_ROUTE = '/dsh-ssh-compute/ssh-config'
82
+
83
+ /** Read a JSON body with a small ceiling; these payloads are one server name. */
84
+ async function readJsonBody(request) {
85
+ const chunks = []
86
+ let size = 0
87
+ for await (const chunk of request) {
88
+ size += chunk.length
89
+ if (size > 65536) throw new Error('request body too large')
90
+ chunks.push(chunk)
91
+ }
92
+ if (chunks.length === 0) return {}
93
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
94
+ }
95
+
96
+ /** Answer one JSON value with the headers a page fetch needs. */
97
+ function answerJson(response, status, value) {
98
+ const body = JSON.stringify(value)
99
+ response.writeHead(status, {
100
+ 'content-type': 'application/json; charset=utf-8',
101
+ 'cache-control': 'no-store',
102
+ })
103
+ response.end(body)
104
+ }
105
+
106
+ /** The session directory a relative local path resolves against. */
107
+ function sessionDirectory(exec) {
108
+ const directory = exec?.agent?.session?.header?.cwd
109
+ return typeof directory === 'string' && directory !== '' ? directory : process.cwd()
110
+ }
111
+
112
+ /**
113
+ * Build the single model-facing tool.
114
+ *
115
+ * The settings row is held, not a resolved snapshot: every field is volatile and
116
+ * resolves per call, so a server added or edited in the settings page is used by
117
+ * the very next call without remounting this plugin.
118
+ * @param context - the settings row and this mount's key store.
119
+ * @returns the tool definition.
120
+ */
121
+ function createTool(context) {
122
+ const { settings, keyStore } = context
123
+
124
+ return {
125
+ name: 'ssh-compute',
126
+ description:
127
+ 'Run work on a remote SSH server instead of this machine. Reach for it when a task is compute-heavy ' +
128
+ '(long builds, training, large numerics, many parallel jobs) or when the local machine is the wrong ' +
129
+ 'place for it; quick local edits and reads stay local. ' +
130
+ 'The servers are the ones configured in this plugin\'s settings (Plugins → SSH compute); `list` names them. ' +
131
+ 'A run always starts a background job and returns a job id at once, so poll `status` for the exit code ' +
132
+ 'and `logs` for progress; `kill` stops a job. `upload` and `download` move files both ways. ' +
133
+ 'On a machine you have not used before, first run something like `nproc; free -g; nvidia-smi -L; df -h` ' +
134
+ 'to see what it actually is, then decide how to use it.',
135
+ parameters: {
136
+ type: 'object',
137
+ properties: {
138
+ action: {
139
+ type: 'string',
140
+ enum: ['run', 'wait', 'status', 'logs', 'kill', 'list', 'upload', 'download'],
141
+ description:
142
+ '`run` starts a job; `wait` blocks until it finishes (or the timeout) and returns the exit ' +
143
+ 'code plus the log tail — prefer it over polling; `status` reports one job; `logs` reads its ' +
144
+ 'output; `kill` stops it; `list` shows the servers, or the jobs on one server; ' +
145
+ '`upload`/`download` copy files.',
146
+ },
147
+ server: {
148
+ type: 'string',
149
+ description:
150
+ 'Server name, as `list` prints it. Required for `run`/`upload`/`download` when more than one is ' +
151
+ 'configured, and optional when only one is; `status`/`logs`/`kill` can infer it from the job id. ' +
152
+ 'Omit `server` on `list` to list the servers.',
153
+ },
154
+ command: {
155
+ type: 'string',
156
+ description:
157
+ 'run: the shell command, run with bash on the server inside a subshell. Use it for everything ' +
158
+ 'from one command to a whole script; multi-line text is fine. Its exit code is captured.',
159
+ },
160
+ jobId: {
161
+ type: 'string',
162
+ description: 'status/logs/kill: the id `run` returned, e.g. `gpu01-20261115-020000-a1b2`.',
163
+ },
164
+ cwd: {
165
+ type: 'string',
166
+ description: 'run: the directory the command starts in on the server. Defaults to the login home.',
167
+ },
168
+ offset: {
169
+ type: 'number',
170
+ description:
171
+ 'logs: byte offset to continue from. Omit for the first read; pass the `nextOffset` of the ' +
172
+ 'previous answer to get only what is new.',
173
+ },
174
+ lines: {
175
+ type: 'number',
176
+ description:
177
+ 'logs: return the last N lines instead of reading from `offset`. status: how many trailing ' +
178
+ 'log lines to include.',
179
+ },
180
+ limit: {
181
+ type: 'number',
182
+ description: 'list: how many jobs to return, newest first.',
183
+ },
184
+ local: {
185
+ type: 'array',
186
+ items: { type: 'string' },
187
+ description:
188
+ 'upload: local paths, relative to the session directory when not absolute. ' +
189
+ '`*`, `?` and `**` patterns are expanded here.',
190
+ },
191
+ target: {
192
+ type: 'string',
193
+ description:
194
+ 'download: the local directory to extract into. Defaults to the session directory.',
195
+ },
196
+ remote: {
197
+ type: 'string',
198
+ description: 'upload: the destination directory on the server. It is created when missing.',
199
+ },
200
+ sources: {
201
+ type: 'array',
202
+ items: { type: 'string' },
203
+ description:
204
+ 'download: paths on the server, absolute or `~/…`; a trailing pattern is expanded by the ' +
205
+ 'server itself.',
206
+ },
207
+ timeoutMs: {
208
+ type: 'number',
209
+ description:
210
+ 'wait: how long to block, in milliseconds. The job keeps running when it elapses. ' +
211
+ 'Defaults to `waitTimeoutMs` in the settings.',
212
+ },
213
+ allowDangerous: {
214
+ type: 'boolean',
215
+ description: 'Permit a command the guard would otherwise refuse. Only for a genuinely intended write.',
216
+ },
217
+ },
218
+ required: ['action'],
219
+ },
220
+ output: {
221
+ schema: {
222
+ type: 'object',
223
+ properties: { text: { type: 'string' } },
224
+ required: ['text'],
225
+ },
226
+ render: (_args, value) => [{ type: 'text', text: value.text }],
227
+ },
228
+
229
+ async execute(args, exec) {
230
+ // Every field is volatile, so this is the user's latest edit even when the
231
+ // row was saved after this plugin mounted.
232
+ const config = resolveConfig(settings)
233
+ const action = args.action
234
+ const signal = exec?.signal
235
+ const cwd = sessionDirectory(exec)
236
+
237
+ /** Resolve the target of a job-scoped action. */
238
+ const jobServer = (jobId) => selectServer(
239
+ config,
240
+ args.server,
241
+ serverNameFromJobId(config, jobId),
242
+ )
243
+
244
+ if (action === 'run') {
245
+ const command = typeof args.command === 'string' ? args.command : ''
246
+ if (command.trim() === '') throw new Error('dsh-ssh-compute: `run` needs a `command`')
247
+ assertCommandAllowed(config, command, args.allowDangerous === true)
248
+ const server = selectServer(config, args.server)
249
+ const keyFile = keyStore.fileFor(server)
250
+ const started = await startJob({
251
+ config,
252
+ server,
253
+ keyFile,
254
+ command,
255
+ cwd: args.cwd,
256
+ signal,
257
+ })
258
+ return {
259
+ text: [
260
+ `started ${started.jobId} on ${server.name} (pid ${started.pid || 'unknown'})`,
261
+ `directory: ${config.remoteRoot}/${started.jobId}`,
262
+ `connect: ${started.durationMs} ms`,
263
+ '',
264
+ `poll it with action="status" jobId="${started.jobId}", read output with action="logs"`,
265
+ ].join('\n'),
266
+ }
267
+ }
268
+
269
+ if (action === 'wait') {
270
+ if (typeof args.jobId !== 'string' || args.jobId === '') {
271
+ throw new Error('dsh-ssh-compute: `wait` needs `jobId`')
272
+ }
273
+ const server = jobServer(args.jobId)
274
+ const keyFile = keyStore.fileFor(server)
275
+ // The default is the configured patience; a caller may ask for less, and
276
+ // the job is untouched either way when it runs out.
277
+ const requested = Number(args.timeoutMs)
278
+ const timeoutMs = Number.isFinite(requested) && requested > 0
279
+ ? Math.min(requested, 6 * 60 * 60 * 1000)
280
+ : config.waitTimeoutMs
281
+ const outcome = await waitJob({
282
+ config,
283
+ server,
284
+ keyFile,
285
+ jobId: args.jobId,
286
+ signal,
287
+ timeoutMs,
288
+ tailLines: args.lines ?? config.logTailLines,
289
+ })
290
+ const seconds = Math.round(outcome.waitedMs / 100) / 10
291
+ const lines = outcome.state === 'exited'
292
+ ? [
293
+ `job: ${outcome.jobId} on ${server.name}`,
294
+ `state: exited${outcome.killed ? ' (killed)' : ''}`,
295
+ `exit: ${outcome.exitCode ?? 'unrecorded'}${outcome.exitCode === 153 ? ' (SIGXFSZ — hit maxFileSizeMb)' : ''}`,
296
+ `waited: ${seconds} s`,
297
+ ]
298
+ : [
299
+ `job: ${outcome.jobId} on ${server.name}`,
300
+ outcome.state === 'lost'
301
+ ? 'state: the process is gone but it never wrote an exit code'
302
+ : 'state: still running',
303
+ `waited: ${seconds} s`,
304
+ '',
305
+ outcome.state === 'lost'
306
+ ? 'read the log with action="logs" to see how far it got'
307
+ : 'call `wait` again, or `status`/`logs`, when you want more',
308
+ ]
309
+ if (outcome.logTail.trim() !== '') {
310
+ lines.push('', `--- last ${Math.min(args.lines ?? config.logTailLines, 400)} lines ---`, outcome.logTail.trimEnd())
311
+ }
312
+ return { text: lines.join('\n') }
313
+ }
314
+
315
+ if (action === 'status') {
316
+ if (typeof args.jobId !== 'string' || args.jobId === '') {
317
+ throw new Error('dsh-ssh-compute: `status` needs `jobId`')
318
+ }
319
+ const server = jobServer(args.jobId)
320
+ const keyFile = keyStore.fileFor(server)
321
+ const status = await jobStatus({
322
+ config,
323
+ server,
324
+ keyFile,
325
+ jobId: args.jobId,
326
+ signal,
327
+ tailLines: args.lines ?? config.logTailLines,
328
+ })
329
+ const lines = [
330
+ `job: ${status.jobId} on ${server.name}`,
331
+ `state: ${status.state}${status.killed ? ' (killed)' : ''}`,
332
+ status.exitCode === undefined
333
+ ? 'exit: not yet recorded'
334
+ : `exit: ${status.exitCode}${status.exitCode === 153 ? ' (SIGXFSZ — hit maxFileSizeMb)' : ''}`,
335
+ `pid: ${status.pid || 'unknown'}`,
336
+ status.started > 0 ? `started: ${new Date(status.started * 1000).toISOString()}` : 'started: unknown',
337
+ `log: ${status.logSize} bytes`,
338
+ ]
339
+ if (status.durationSeconds !== undefined) lines.push(`duration: ${status.durationSeconds} s`)
340
+ if (status.peakRssKb !== undefined) lines.push(`peak memory: ${Math.round(status.peakRssKb / 1024)} MiB`)
341
+ if (status.label !== '') lines.push(`command: ${status.label.split('\n')[0].slice(0, 400)}`)
342
+ if (status.logTail.trim() !== '') {
343
+ lines.push('', `--- last ${Math.min(args.lines ?? config.logTailLines, 400)} lines ---`, status.logTail.trimEnd())
344
+ }
345
+ return { text: lines.join('\n') }
346
+ }
347
+
348
+ if (action === 'logs') {
349
+ if (typeof args.jobId !== 'string' || args.jobId === '') {
350
+ throw new Error('dsh-ssh-compute: `logs` needs `jobId`')
351
+ }
352
+ const server = jobServer(args.jobId)
353
+ const keyFile = keyStore.fileFor(server)
354
+ const log = await readLog({
355
+ config,
356
+ server,
357
+ keyFile,
358
+ jobId: args.jobId,
359
+ signal,
360
+ offset: args.offset,
361
+ lines: args.lines,
362
+ })
363
+ // The cursor is printed even at the end of the log: an answer without one
364
+ // forces the next read to start over and repeat everything.
365
+ const footer = log.nextOffset >= log.size
366
+ ? `[end of log · ${log.size} bytes · nextOffset ${log.nextOffset}]`
367
+ : `[nextOffset ${log.nextOffset} of ${log.size} bytes${log.truncated ? ', more is waiting' : ''}]`
368
+ return {
369
+ text: log.text.trimEnd() === '' ? footer : `${log.text.trimEnd()}\n\n${footer}`,
370
+ }
371
+ }
372
+
373
+ if (action === 'kill') {
374
+ if (typeof args.jobId !== 'string' || args.jobId === '') {
375
+ throw new Error('dsh-ssh-compute: `kill` needs `jobId`')
376
+ }
377
+ const server = jobServer(args.jobId)
378
+ const keyFile = keyStore.fileFor(server)
379
+ const outcome = await killJob({ config, server, keyFile, jobId: args.jobId, signal })
380
+ return {
381
+ text: outcome.killedProcess
382
+ ? `stopped ${outcome.jobId} on ${server.name} (exit ${outcome.exitCode ?? 'unknown'})`
383
+ : `${outcome.jobId} on ${server.name} was not running any more (exit ${outcome.exitCode ?? 'unknown'})`,
384
+ }
385
+ }
386
+
387
+ if (action === 'list') {
388
+ const serverName = typeof args.server === 'string' ? args.server.trim() : ''
389
+ if (serverName === '') {
390
+ if (config.servers.length === 0) {
391
+ return { text: 'no servers configured — add one in Plugins → SSH compute' }
392
+ }
393
+ const rows = config.servers.map((server) => {
394
+ const key = keyStore.describe(server)
395
+ const more = key.count > 1 ? ` (+${key.count - 1} more)` : ''
396
+ const keyLabel = key.source === 'default'
397
+ ? 'ssh default (no key found in ~/.ssh)'
398
+ : key.source === 'inline'
399
+ ? 'key from settings'
400
+ : `${key.source === 'detected' ? 'auto-detected' : 'configured'}: ${key.path}${more}`
401
+ return `${server.name}\t${server.user}@${server.host}:${server.port}\t${keyLabel}`
402
+ })
403
+ return {
404
+ text: [
405
+ `servers (${config.servers.length}), jobs live in ${config.remoteRoot}/<jobId> on each:`,
406
+ ...rows,
407
+ ].join('\n'),
408
+ }
409
+ }
410
+ const server = selectServer(config, serverName)
411
+ const keyFile = keyStore.fileFor(server)
412
+ const jobs = await listJobs({ config, server, keyFile, signal, limit: args.limit })
413
+ if (jobs.length === 0) return { text: `no jobs on ${server.name} yet` }
414
+ const rows = jobs.map((job) => {
415
+ const when = job.started > 0 ? new Date(job.started * 1000).toISOString() : 'unknown'
416
+ const exit = job.exitCode === undefined ? '' : `\texit ${job.exitCode}`
417
+ return `${job.jobId}\t${when}\t${job.state}${exit}`
418
+ })
419
+ return { text: [`jobs on ${server.name} (newest first):`, ...rows].join('\n') }
420
+ }
421
+
422
+ if (action === 'upload') {
423
+ const server = selectServer(config, args.server)
424
+ const remoteTarget = typeof args.remote === 'string' ? args.remote.trim() : ''
425
+ if (remoteTarget === '') throw new Error('dsh-ssh-compute: `upload` needs `remote`, the target directory')
426
+ assertUploadAllowed(config, remoteTarget, args.allowDangerous === true)
427
+ const keyFile = keyStore.fileFor(server)
428
+ const moved = await upload({
429
+ config,
430
+ server,
431
+ keyFile,
432
+ local: args.local,
433
+ remote: remoteTarget,
434
+ cwd,
435
+ })
436
+ const notes = [`uploaded ${moved.count} path(s) to ${server.name}:${remoteTarget} via ${moved.transport}`]
437
+ if (moved.missing.length > 0) notes.push(`no match for: ${moved.missing.join(', ')}`)
438
+ return { text: notes.join('\n') }
439
+ }
440
+
441
+ if (action === 'download') {
442
+ const server = selectServer(config, args.server)
443
+ const keyFile = keyStore.fileFor(server)
444
+ // A bare `target` is relative to the conversation, not to wherever the
445
+ // DSH host process happens to have been launched.
446
+ const requested = typeof args.target === 'string' ? args.target.trim() : ''
447
+ const target = requested === '' ? cwd : resolve(cwd, requested)
448
+ const moved = await download({
449
+ config,
450
+ server,
451
+ keyFile,
452
+ remote: args.sources,
453
+ local: target,
454
+ cwd,
455
+ })
456
+ return { text: `downloaded ${moved.count} argument(s) from ${server.name} into ${moved.target} via ${moved.transport}` }
457
+ }
458
+
459
+ throw new Error(
460
+ `dsh-ssh-compute: unknown action ${JSON.stringify(action)}; ` +
461
+ 'use run, status, logs, kill, list, upload or download',
462
+ )
463
+ },
464
+ }
465
+ }
466
+
467
+ /**
468
+ * Mount the plugin: the tool, the two routes the detail page calls, and the
469
+ * key store's lifetime.
470
+ * @param ctx - the plugin context.
471
+ * @param settings - the config row.
472
+ */
473
+ export function apply(ctx, settings = {}) {
474
+ const keyStore = createKeyStore()
475
+ ctx.effect(() => () => keyStore.dispose(), 'dsh-ssh-compute: key files')
476
+ // Masters started with ControlPersist expire on their own; this only tidies the
477
+ // socket files so a long-lived profile does not collect them.
478
+ ctx.effect(() => () => cleanupControlSockets(), 'dsh-ssh-compute: ssh masters')
479
+
480
+ const disposeTool = ctx.tools.register(createTool({ settings, keyStore }))
481
+ ctx.effect(() => disposeTool, 'dsh-ssh-compute: tool')
482
+
483
+ // A server list is only a warning at mount: the settings form saves the whole
484
+ // array, so a card that is still half-filled must not take the plugin down.
485
+ const initial = resolveConfig(settings)
486
+ for (const problem of initial.problems) console.warn(`dsh-ssh-compute: ${problem}`)
487
+
488
+ ctx.inject(['webServer'], (inner) => {
489
+ const webServer = inner.webServer
490
+ if (webServer === undefined || webServer === null || typeof webServer.register !== 'function') return
491
+
492
+ const publish = (path, handler, label) => {
493
+ const dispose = webServer.register({ kind: 'exact', path, handler })
494
+ if (typeof inner.effect === 'function') inner.effect(() => dispose, label)
495
+ }
496
+
497
+ publish(SERVERS_ROUTE, (request, response) => {
498
+ if (request.method !== 'GET') {
499
+ response.writeHead(405, { allow: 'GET' })
500
+ response.end()
501
+ return
502
+ }
503
+ const config = resolveConfig(settings)
504
+ answerJson(response, 200, {
505
+ remoteRoot: config.remoteRoot,
506
+ problems: config.problems,
507
+ servers: config.servers.map((server) => {
508
+ const key = keyStore.describe(server)
509
+ return {
510
+ name: server.name,
511
+ host: server.host,
512
+ port: server.port,
513
+ user: server.user,
514
+ keySource: key.source,
515
+ keyPath: key.path ?? null,
516
+ }
517
+ }),
518
+ })
519
+ }, 'dsh-ssh-compute: servers route')
520
+
521
+ publish(TEST_ROUTE, async (request, response) => {
522
+ if (request.method !== 'POST') {
523
+ response.writeHead(405, { allow: 'POST' })
524
+ response.end()
525
+ return
526
+ }
527
+ // A cross-origin `text/plain` POST is a CORS "simple request" and would reach
528
+ // this handler without a preflight, letting any local page make the Host open
529
+ // an SSH connection. Demanding JSON forces the preflight, which this server
530
+ // answers with 405.
531
+ if (!String(request.headers?.['content-type'] ?? '').toLowerCase().startsWith('application/json')) {
532
+ answerJson(response, 415, { ok: false, error: 'content-type must be application/json' })
533
+ return
534
+ }
535
+ try {
536
+ const config = resolveConfig(settings)
537
+ const body = await readJsonBody(request)
538
+ const server = selectServer(config, typeof body?.name === 'string' ? body.name : undefined)
539
+ const keyFile = keyStore.fileFor(server)
540
+ const probe = await probeServer({ config, server, keyFile })
541
+ answerJson(response, 200, {
542
+ ok: true,
543
+ server: server.name,
544
+ durationMs: probe.durationMs,
545
+ facts: Object.fromEntries(probe.facts),
546
+ })
547
+ } catch (error) {
548
+ answerJson(response, 200, { ok: false, error: error instanceof Error ? error.message : String(error) })
549
+ }
550
+ }, 'dsh-ssh-compute: connection test route')
551
+
552
+ // Read-only: the settings form asks what this machine's ssh already knows,
553
+ // offers the list, and writes only the entries the user ticks.
554
+ publish(SSH_CONFIG_ROUTE, (request, response) => {
555
+ if (request.method !== 'GET') {
556
+ response.writeHead(405, { allow: 'GET' })
557
+ response.end()
558
+ return
559
+ }
560
+ try {
561
+ const found = readSshConfigFile()
562
+ answerJson(response, 200, {
563
+ path: found.path,
564
+ exists: found.exists,
565
+ entries: found.entries,
566
+ problems: found.problems,
567
+ })
568
+ } catch (error) {
569
+ answerJson(response, 200, {
570
+ path: '',
571
+ exists: false,
572
+ entries: [],
573
+ problems: [error instanceof Error ? error.message : String(error)],
574
+ })
575
+ }
576
+ }, 'dsh-ssh-compute: ssh config route')
577
+ })
578
+ }