dsh-ssh-compute 0.0.0-stage → 1.2.2

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,256 @@
1
+ // Reading `~/.ssh/config`.
2
+ //
3
+ // The file is a list of blocks: a `Host` line names the patterns the block
4
+ // applies to, and the lines under it set options. ssh resolves one connection by
5
+ // walking the file top to bottom and taking the FIRST value it meets for each
6
+ // keyword, so a `Host *` block at the bottom supplies defaults and one at the top
7
+ // would win instead. This module reproduces that, because a config that looks
8
+ // fine by eye often resolves differently — `Port 2222` under a `Host *` that
9
+ // sits above `Host lab` is the small version of that surprise.
10
+ //
11
+ // What it deliberately does not do: `Include`, `Match`, and `ProxyCommand`.
12
+ // Those change which file or which options apply, and guessing would produce a
13
+ // server entry that connects somewhere else than the user's own ssh does.
14
+
15
+ import { readFileSync } from 'node:fs'
16
+ import { homedir, userInfo } from 'node:os'
17
+ import { join } from 'node:path'
18
+
19
+ import { SERVER_NAME_RE } from './config.js'
20
+
21
+ /** A value that carries a wildcard or a negation, so it can never BE a server. */
22
+ const PATTERN_CHARS = /[*?!]/
23
+
24
+ /**
25
+ * Split one line into a keyword and its value, dropping a trailing comment.
26
+ *
27
+ * ssh_config has no general quoting; a `#` starts a comment, and a double-quoted
28
+ * run protects its own spaces and `#`. This is the same rule the client uses.
29
+ * @param line - one non-empty, non-comment line.
30
+ * @returns the lowercased keyword and the trimmed value.
31
+ */
32
+ function splitLine(line) {
33
+ let out = ''
34
+ let quoted = false
35
+ for (const character of line) {
36
+ if (character === '"') {
37
+ quoted = !quoted
38
+ continue
39
+ }
40
+ if (character === '#' && !quoted) break
41
+ out += character
42
+ }
43
+ const trimmed = out.trim()
44
+ const match = /^([A-Za-z][A-Za-z0-9]*)\s*(?:=\s*)?(.*)$/.exec(trimmed)
45
+ if (match === null) return undefined
46
+ return { keyword: match[1].toLowerCase(), value: (match[2] ?? '').trim() }
47
+ }
48
+
49
+ /**
50
+ * Compile one `Host` pattern into a matcher.
51
+ * @param pattern - a literal alias, or one with `*` / `?` / a leading `!`.
52
+ * @returns the matcher and whether it is a negation.
53
+ */
54
+ function compilePattern(pattern) {
55
+ const negated = pattern.startsWith('!')
56
+ const body = negated ? pattern.slice(1) : pattern
57
+ const source = body
58
+ .split('')
59
+ .map((character) => {
60
+ if (character === '*') return '.*'
61
+ if (character === '?') return '.'
62
+ return character.replace(/[.+^${}()|[\]\\]/g, '\\$&')
63
+ })
64
+ .join('')
65
+ return { negated, test: new RegExp(`^${source}$`, 'i') }
66
+ }
67
+
68
+ /**
69
+ * Whether one block applies to an alias.
70
+ *
71
+ * ssh applies the last matching pattern rule of a negation: a block whose
72
+ * patterns all fail, or whose matching pattern is negated, does not apply.
73
+ * @param patterns - the block's compiled patterns.
74
+ * @param alias - the host alias being resolved.
75
+ * @returns true when the block applies.
76
+ */
77
+ function appliesTo(patterns, alias) {
78
+ let matched = false
79
+ for (const pattern of patterns) {
80
+ if (!pattern.test.test(alias)) continue
81
+ if (pattern.negated) return false
82
+ matched = true
83
+ }
84
+ return matched
85
+ }
86
+
87
+ /**
88
+ * Parse the text of an ssh config into ordered blocks.
89
+ * @param text - the file's contents.
90
+ * @returns the blocks, and the directives that were not understood.
91
+ */
92
+ export function parseSshConfig(text) {
93
+ const blocks = []
94
+ const problems = []
95
+ let current
96
+ let lineNumber = 0
97
+ for (const raw of String(text).split(/\r?\n/)) {
98
+ lineNumber += 1
99
+ const line = raw.trim()
100
+ if (line === '' || line.startsWith('#')) continue
101
+ const parsed = splitLine(raw)
102
+ if (parsed === undefined) {
103
+ problems.push(`line ${lineNumber}: not a directive (${line})`)
104
+ continue
105
+ }
106
+ if (parsed.keyword === 'host') {
107
+ const aliases = parsed.value.split(/\s+/).filter((value) => value !== '')
108
+ current = { patterns: aliases.map(compilePattern), aliases, options: {}, lineNumber }
109
+ blocks.push(current)
110
+ continue
111
+ }
112
+ if (parsed.keyword === 'match') {
113
+ // A Match block's options are conditional on more than the host name, so
114
+ // nothing after it may be attributed to a host without evaluating it.
115
+ current = undefined
116
+ problems.push(`line ${lineNumber}: Match blocks are not read, so the options under this line are ignored`)
117
+ continue
118
+ }
119
+ if (parsed.keyword === 'include') {
120
+ problems.push(`line ${lineNumber}: Include is not followed, so the hosts it names are not listed`)
121
+ continue
122
+ }
123
+ if (current === undefined) {
124
+ // Directives before the first Host line apply to every connection in ssh's
125
+ // own model; this plugin cannot represent them, so it reports them once.
126
+ if (!problems.includes('options before the first Host block are ignored')) {
127
+ problems.push('options before the first Host block are ignored')
128
+ }
129
+ continue
130
+ }
131
+ // First occurrence within a block wins, as it does in ssh.
132
+ if (current.options[parsed.keyword] === undefined) current.options[parsed.keyword] = parsed.value
133
+ }
134
+ return { blocks, problems }
135
+ }
136
+
137
+ /** Expand a leading `~` the way ssh treats an identity file path. */
138
+ function expandTilde(path) {
139
+ if (path === '~') return homedir()
140
+ if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
141
+ return path
142
+ }
143
+
144
+ /**
145
+ * Turn one block's resolved options into a server entry for this plugin.
146
+ * @param alias - the block's own alias.
147
+ * @param options - every keyword resolved for it, first match wins.
148
+ * @returns the importable entry.
149
+ */
150
+ function toEntry(alias, options) {
151
+ const notes = []
152
+ const unsupported = []
153
+ // ProxyJump is a flag ssh itself understands, so it travels as an ordinary
154
+ // argument. ProxyCommand is a shell command line, which this plugin has no
155
+ // field for: importing it would silently connect somewhere else.
156
+ let extraArgs = ''
157
+ const jump = options.proxyjump ?? ''
158
+ if (jump !== '') {
159
+ if (/\s/.test(jump)) {
160
+ notes.push(`ProxyJump ${jump} contains spaces; check the imported arguments`)
161
+ }
162
+ extraArgs = `-J ${jump}`
163
+ }
164
+ if (options.proxycommand !== undefined) unsupported.push('ProxyCommand')
165
+ if (options.localcommand !== undefined) unsupported.push('LocalCommand')
166
+ if (options.remotecommand !== undefined) unsupported.push('RemoteCommand')
167
+
168
+ const host = options.hostname !== undefined && options.hostname !== '' ? options.hostname : alias
169
+ if (options.hostname === undefined) notes.push('no HostName, so the alias is the address')
170
+
171
+ const port = Number(options.port ?? 22)
172
+ const usablePort = Number.isInteger(port) && port > 0 && port < 65536 ? port : 22
173
+ if (options.port !== undefined && usablePort !== port) notes.push(`Port ${options.port} was not a usable port, so 22 is used`)
174
+
175
+ let user = options.user ?? ''
176
+ if (user === '') {
177
+ user = userInfo().username
178
+ notes.push('no User in the config, so this machine\'s user name is filled in')
179
+ }
180
+
181
+ let keyPath = ''
182
+ const identity = options.identityfile ?? ''
183
+ if (identity !== '') {
184
+ // %d is the local home; the other tokens name remote-side facts this plugin
185
+ // does not know before it connects.
186
+ if (/%[a-z]/i.test(identity.replace(/%d/gi, ''))) {
187
+ notes.push(`IdentityFile ${identity} uses ssh tokens; the path is kept as written`)
188
+ }
189
+ keyPath = expandTilde(identity.replace(/%d/gi, '~'))
190
+ }
191
+
192
+ return {
193
+ alias,
194
+ name: alias,
195
+ // An alias ssh accepts may not be usable as this plugin's name: the name becomes
196
+ // a path segment and part of a job id, so it has to stay a plain token.
197
+ nameOk: SERVER_NAME_RE.test(alias),
198
+ host,
199
+ port: usablePort,
200
+ user,
201
+ keyPath,
202
+ extraArgs,
203
+ notes,
204
+ unsupported,
205
+ }
206
+ }
207
+
208
+ /**
209
+ * Every host in a config that can become a server, in file order.
210
+ *
211
+ * Only blocks whose `Host` line is a plain alias are candidates: `Host foo bar`
212
+ * declares two, and a pattern like `Host *` or `Host *.example.com` declares
213
+ * none this plugin could connect to.
214
+ * @param text - the file's contents.
215
+ * @returns the entries, plus the directives that were not understood.
216
+ */
217
+ export function readHosts(text) {
218
+ const { blocks, problems } = parseSshConfig(text)
219
+ const entries = []
220
+ const seen = new Set()
221
+ for (const block of blocks) {
222
+ for (const alias of block.aliases) {
223
+ if (alias === '' || PATTERN_CHARS.test(alias)) continue
224
+ const key = alias.toLowerCase()
225
+ if (seen.has(key)) continue
226
+ seen.add(key)
227
+ // ssh resolves each keyword to the first value met while walking the file,
228
+ // from every block that applies — including `Host *` defaults.
229
+ const options = {}
230
+ for (const candidate of blocks) {
231
+ if (!appliesTo(candidate.patterns, alias)) continue
232
+ for (const [keyword, value] of Object.entries(candidate.options)) {
233
+ if (options[keyword] === undefined) options[keyword] = value
234
+ }
235
+ }
236
+ entries.push(toEntry(alias, options))
237
+ }
238
+ }
239
+ return { entries, problems }
240
+ }
241
+
242
+ /**
243
+ * Read this machine's `~/.ssh/config`.
244
+ * @param path - an override, used by tests.
245
+ * @returns the path, whether it exists, the entries and any parsing problems.
246
+ */
247
+ export function readSshConfigFile(path = join(homedir(), '.ssh', 'config')) {
248
+ let text
249
+ try {
250
+ text = readFileSync(path, 'utf8')
251
+ } catch {
252
+ return { path, exists: false, entries: [], problems: [] }
253
+ }
254
+ const { entries, problems } = readHosts(text)
255
+ return { path, exists: true, entries, problems }
256
+ }
@@ -0,0 +1,336 @@
1
+ // File movement.
2
+ //
3
+ // rsync is preferred when BOTH ends have it, because it resumes and only sends
4
+ // what changed. It is not assumed: this plugin also runs on Windows, where rsync
5
+ // is usually absent, so the fallback streams a tar archive through the ssh
6
+ // connection — one channel, no extra daemon, and the same path for one file,
7
+ // many files, whole directories and patterns.
8
+
9
+ import { spawn } from 'node:child_process'
10
+ import { mkdirSync } from 'node:fs'
11
+
12
+ import { commonParent, expandLocalPaths, relativeTo } from './glob.js'
13
+ import { posixQuote, remotePathExpr } from './shell.js'
14
+ import { controlPath, execProcess, keyList, sshArgv } from './ssh.js'
15
+
16
+ /** Transfers legitimately run longer than a command round trip. */
17
+ const TRANSFER_TIMEOUT_MS = 30 * 60 * 1000
18
+
19
+ /** Whether a local `rsync` exists. Probed once per process, not per call. */
20
+ let localRsync
21
+
22
+ /** server name -> whether that server has rsync. */
23
+ const remoteRsync = new Map()
24
+
25
+ /**
26
+ * Whether the local host can run rsync.
27
+ * @returns true when `rsync --version` succeeds.
28
+ */
29
+ async function hasLocalRsync() {
30
+ if (localRsync !== undefined) return localRsync
31
+ try {
32
+ await execProcess(['rsync', '--version'], { timeoutMs: 8000, maxBytes: 4096 })
33
+ localRsync = true
34
+ } catch {
35
+ localRsync = false
36
+ }
37
+ return localRsync
38
+ }
39
+
40
+ /**
41
+ * Whether one server has rsync.
42
+ * @param context - config, server and key file.
43
+ * @returns true when the remote shell finds `rsync`.
44
+ */
45
+ async function hasRemoteRsync(context) {
46
+ const cached = remoteRsync.get(context.server.name)
47
+ if (cached !== undefined) return cached
48
+ try {
49
+ const result = await execProcess(
50
+ [...sshArgv(context.config, context.server, context.keyFile), 'command -v rsync >/dev/null 2>&1 && echo yes || echo no'],
51
+ { timeoutMs: context.config.connectTimeoutMs + 5000, maxBytes: 1024 },
52
+ )
53
+ const found = result.stdout.toString('utf8').includes('yes')
54
+ remoteRsync.set(context.server.name, found)
55
+ return found
56
+ } catch {
57
+ remoteRsync.set(context.server.name, false)
58
+ return false
59
+ }
60
+ }
61
+
62
+ /**
63
+ * The `-e` value rsync hands to its own ssh invocation.
64
+ *
65
+ * rsync splits this string on spaces, so every ssh option travels in its
66
+ * attached form (`-oName=value`). A spaced `-o Name=value` would be torn apart.
67
+ * @param context - config, server and key file.
68
+ * @returns the rsh command string.
69
+ */
70
+ function rsyncRemoteShell(context) {
71
+ const parts = [
72
+ 'ssh',
73
+ '-p', String(context.server.port),
74
+ '-oBatchMode=yes',
75
+ '-oStrictHostKeyChecking=accept-new',
76
+ `-oConnectTimeout=${Math.max(1, Math.ceil(context.config.connectTimeoutMs / 1000))}`,
77
+ ]
78
+ if (context.keyFile !== undefined && context.keyFile !== null && context.keyFile !== '') {
79
+ for (const file of keyList(context.keyFile)) parts.push('-i', file)
80
+ }
81
+ // rsync splits `-e` on spaces itself, so an extra argument that needs its own
82
+ // space (a ProxyCommand, say) is not expressible here — `-J host` and single
83
+ // tokens are. Documented in the README rather than silently dropped.
84
+ for (const token of context.server.extraArgs ?? []) parts.push(token)
85
+ // rsync splits `-e` on spaces, so the multiplexing options travel attached.
86
+ if (context.config.reuseConnection !== false && process.platform !== 'win32') {
87
+ parts.push(
88
+ '-oControlMaster=auto',
89
+ `-oControlPath=${controlPath(context.server)}`,
90
+ `-oControlPersist=${Math.max(0, Math.round(context.config.reuseIdleSeconds ?? 300))}`,
91
+ )
92
+ }
93
+ return parts.join(' ')
94
+ }
95
+
96
+ /**
97
+ * Split one remote path into the directory tar reads from and the name inside it.
98
+ *
99
+ * Doing this per source lets `tar -C <dir> <name>` name every member relative to
100
+ * its own directory, so downloading `~/dsh-compute/run/out.txt` produces
101
+ * `out.txt` rather than `root/dsh-compute/run/out.txt`.
102
+ * @param source - an absolute or `~`-relative path, possibly ending in a pattern.
103
+ * @returns the directory expression and the name within it.
104
+ */
105
+ function splitRemoteSource(source) {
106
+ // A trailing slash names the directory itself, and `tar -C <dir> ''` fails with a
107
+ // confusing message, so it is removed before the split.
108
+ const text = String(source ?? '').trim().replace(/\/+$/, '')
109
+ if (text === '') return { directory: '/', name: '' }
110
+ const index = text.lastIndexOf('/')
111
+ if (index < 0) return { directory: '.', name: text }
112
+ if (index === 0) return { directory: '/', name: text.slice(1) }
113
+ return { directory: text.slice(0, index), name: text.slice(index + 1) }
114
+ }
115
+
116
+ /**
117
+ * A remote name tar can take: unquoted when it carries a pattern the server
118
+ * should expand, single-quoted otherwise so a space or a dash stays literal.
119
+ * @param name - the last segment of a remote path.
120
+ * @returns the shell word.
121
+ */
122
+ function remoteNameWord(name) {
123
+ return /[*?[\]]/.test(name) ? name : posixQuote(name)
124
+ }
125
+
126
+ /**
127
+ * Pipe one process's stdout into another's stdin and wait for both.
128
+ *
129
+ * Both ends are reported even when one fails: a non-zero producer with a clean
130
+ * consumer means "nothing was sent", which reads very differently from a
131
+ * consumer that could not unpack what arrived.
132
+ * @param producer - the packing side.
133
+ * @param consumer - the unpacking side.
134
+ * @param timeoutMs - deadline for the whole pair.
135
+ * @returns both exit codes and both stderr tails.
136
+ */
137
+ function pipePair(producer, consumer, timeoutMs) {
138
+ return new Promise((resolve, reject) => {
139
+ let producerErr = ''
140
+ let consumerErr = ''
141
+ let producerCode
142
+ let consumerCode
143
+ let settled = false
144
+ const finish = (error, value) => {
145
+ if (settled) return
146
+ settled = true
147
+ if (timer !== undefined) clearTimeout(timer)
148
+ if (error !== undefined) reject(error)
149
+ else resolve(value)
150
+ }
151
+ const timer = timeoutMs > 0
152
+ ? setTimeout(() => {
153
+ try { producer.kill('SIGKILL') } catch { /* gone */ }
154
+ try { consumer.kill('SIGKILL') } catch { /* gone */ }
155
+ finish(new Error(`dsh-ssh-compute: the transfer did not finish within ${Math.round(timeoutMs / 1000)} s and was stopped.`))
156
+ }, timeoutMs)
157
+ : undefined
158
+ timer?.unref?.()
159
+
160
+ producer.on('error', (error) => finish(new Error(`dsh-ssh-compute: ${error.message}`)))
161
+ consumer.on('error', (error) => finish(new Error(`dsh-ssh-compute: ${error.message}`)))
162
+ // A consumer that exits early closes the pipe; the producer's EPIPE is the
163
+ // shape of that failure and its cause is reported by the consumer instead.
164
+ producer.stdout.on('error', () => {})
165
+ consumer.stdin.on('error', () => {})
166
+ producer.stderr.on('data', (chunk) => {
167
+ producerErr += chunk.toString('utf8')
168
+ if (producerErr.length > 16384) producerErr = producerErr.slice(-16384)
169
+ })
170
+ consumer.stderr.on('data', (chunk) => {
171
+ consumerErr += chunk.toString('utf8')
172
+ if (consumerErr.length > 16384) consumerErr = consumerErr.slice(-16384)
173
+ })
174
+ producer.stdout.pipe(consumer.stdin)
175
+ producer.on('close', (code) => {
176
+ producerCode = code
177
+ if (code !== 0) {
178
+ try { consumer.stdin.end() } catch { /* already gone */ }
179
+ }
180
+ if (consumerCode !== undefined) {
181
+ finish(undefined, { producerCode, consumerCode, producerErr, consumerErr })
182
+ }
183
+ })
184
+ consumer.on('close', (code) => {
185
+ consumerCode = code
186
+ if (producerCode !== undefined) {
187
+ finish(undefined, { producerCode, consumerCode, producerErr, consumerErr })
188
+ }
189
+ })
190
+ })
191
+ }
192
+
193
+ /**
194
+ * Copy local paths to a directory on the server.
195
+ * @param context - config, server, key file, local patterns, remote target, cwd
196
+ * and an optional `transport` override used by tests.
197
+ * @returns how many paths were sent, which transport ran, and what matched nothing.
198
+ */
199
+ export async function upload(context) {
200
+ const { config, server } = context
201
+ const sources = Array.isArray(context.local) ? context.local : [context.local]
202
+ const { matches, missing } = expandLocalPaths(sources, context.cwd)
203
+ if (matches.length === 0) {
204
+ throw new Error(`dsh-ssh-compute: none of these local paths exist: ${missing.join(', ')}`)
205
+ }
206
+ const remoteTarget = String(context.remote ?? '').trim()
207
+ if (remoteTarget === '') throw new Error('dsh-ssh-compute: upload needs `remote`, the target directory on the server')
208
+
209
+ const targetExpr = remotePathExpr(remoteTarget)
210
+ await execProcess(
211
+ [...sshArgv(config, server, context.keyFile), `mkdir -p ${targetExpr}`],
212
+ { timeoutMs: config.connectTimeoutMs + 15000 },
213
+ )
214
+
215
+ const allowRsync = context.transport !== 'tar'
216
+ && await hasLocalRsync()
217
+ && await hasRemoteRsync(context)
218
+
219
+ if (allowRsync) {
220
+ const argv = [
221
+ 'rsync', '-az', '--partial',
222
+ '-e', rsyncRemoteShell(context),
223
+ '--', ...matches, `${server.user}@${server.host}:${remoteTarget}`,
224
+ ]
225
+ const result = await execProcess(argv, { timeoutMs: TRANSFER_TIMEOUT_MS, maxBytes: 65536 })
226
+ if (result.code !== 0) {
227
+ throw new Error(
228
+ `dsh-ssh-compute: rsync upload to ${server.name} failed: ` +
229
+ `${result.stderr.trim() || `exit code ${result.code}`}`,
230
+ )
231
+ }
232
+ return { transport: 'rsync', count: matches.length, missing }
233
+ }
234
+
235
+ const base = commonParent(matches)
236
+ if (base === undefined) throw new Error('dsh-ssh-compute: these paths share no common parent directory')
237
+ const relatives = matches.map((path) => relativeTo(base, path).replace(/\\/g, '/'))
238
+ const packer = spawn('tar', ['-cf', '-', '--', ...relatives], {
239
+ cwd: base,
240
+ windowsHide: true,
241
+ stdio: ['ignore', 'pipe', 'pipe'],
242
+ })
243
+ const unpackArgv = sshArgv(config, server, context.keyFile)
244
+ unpackArgv.push(`tar -xf - -C ${targetExpr}`)
245
+ const unpacker = spawn(unpackArgv[0], unpackArgv.slice(1), {
246
+ windowsHide: true,
247
+ stdio: ['pipe', 'pipe', 'pipe'],
248
+ })
249
+ unpacker.stdout.on('data', () => {})
250
+ const outcome = await pipePair(packer, unpacker, TRANSFER_TIMEOUT_MS)
251
+ if (outcome.consumerCode !== 0) {
252
+ throw new Error(
253
+ `dsh-ssh-compute: extracting the archive on ${server.name} failed: ` +
254
+ `${outcome.consumerErr.trim() || `exit code ${outcome.consumerCode}`}`,
255
+ )
256
+ }
257
+ if (outcome.producerCode !== 0) {
258
+ throw new Error(
259
+ `dsh-ssh-compute: packing the local files failed: ` +
260
+ `${outcome.producerErr.trim() || `exit code ${outcome.producerCode}`}`,
261
+ )
262
+ }
263
+ return { transport: 'tar', count: matches.length, missing }
264
+ }
265
+
266
+ /**
267
+ * Copy paths from the server into a local directory.
268
+ * @param context - config, server, key file, remote patterns, local target, cwd
269
+ * and an optional `transport` override used by tests.
270
+ * @returns how many remote arguments were requested and where they landed.
271
+ */
272
+ export async function download(context) {
273
+ const { config, server } = context
274
+ const sources = (Array.isArray(context.remote) ? context.remote : [context.remote])
275
+ .map((value) => String(value ?? '').trim())
276
+ .filter((value) => value !== '')
277
+ if (sources.length === 0) throw new Error('dsh-ssh-compute: download needs at least one remote path')
278
+ if (sources.some((source) => source.replace(/^\/+$|^~\/*$/, '') === '')) {
279
+ throw new Error('dsh-ssh-compute: download needs a file or directory path, not the server root')
280
+ }
281
+ const localTarget = String(context.local ?? '').trim() || context.cwd
282
+ // tar -C needs the directory to exist; creating it is what a user expects from
283
+ // "download into this path", and the alternative is a bare tar error.
284
+ mkdirSync(localTarget, { recursive: true })
285
+
286
+ if (context.transport !== 'tar' && await hasLocalRsync() && await hasRemoteRsync(context)) {
287
+ const argv = [
288
+ 'rsync', '-az', '--partial',
289
+ '-e', rsyncRemoteShell(context),
290
+ '--', ...sources.map((value) => `${server.user}@${server.host}:${value}`), localTarget,
291
+ ]
292
+ const result = await execProcess(argv, { timeoutMs: TRANSFER_TIMEOUT_MS, maxBytes: 65536 })
293
+ if (result.code !== 0) {
294
+ throw new Error(
295
+ `dsh-ssh-compute: rsync download from ${server.name} failed: ` +
296
+ `${result.stderr.trim() || `exit code ${result.code}`}`,
297
+ )
298
+ }
299
+ return { transport: 'rsync', count: sources.length, target: localTarget }
300
+ }
301
+
302
+ // GNU tar and bsdtar both accept repeated `-C`, so every member is named
303
+ // relative to its own directory and the extracted tree stays flat.
304
+ const parts = []
305
+ for (const source of sources) {
306
+ const { directory, name } = splitRemoteSource(source)
307
+ parts.push(`-C ${remotePathExpr(directory)}`, remoteNameWord(name))
308
+ }
309
+ const remoteCommand = `tar -cf - ${parts.join(' ')}`
310
+ const packArgv = sshArgv(config, server, context.keyFile)
311
+ packArgv.push(remoteCommand)
312
+ const packer = spawn(packArgv[0], packArgv.slice(1), {
313
+ windowsHide: true,
314
+ stdio: ['ignore', 'pipe', 'pipe'],
315
+ })
316
+ const unpacker = spawn('tar', ['-xf', '-', '-C', localTarget], {
317
+ windowsHide: true,
318
+ stdio: ['pipe', 'pipe', 'pipe'],
319
+ })
320
+ packer.stdout.on('error', () => {})
321
+ unpacker.stdout.on('data', () => {})
322
+ const outcome = await pipePair(packer, unpacker, TRANSFER_TIMEOUT_MS)
323
+ if (outcome.consumerCode !== 0) {
324
+ throw new Error(
325
+ `dsh-ssh-compute: extracting the archive locally failed: ` +
326
+ `${outcome.consumerErr.trim() || `exit code ${outcome.consumerCode}`}`,
327
+ )
328
+ }
329
+ if (outcome.producerCode !== 0) {
330
+ throw new Error(
331
+ `dsh-ssh-compute: ${server.name} could not produce the archive: ` +
332
+ `${outcome.producerErr.trim() || `exit code ${outcome.producerCode}`}`,
333
+ )
334
+ }
335
+ return { transport: 'tar', count: sources.length, target: localTarget }
336
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "SSH compute",
4
+ "description": "Gives the agent one remote machine over SSH: start a long job there, watch its log, stop it, and move files both ways. Add servers under Settings → Plugins → SSH compute; the tool is called ssh-compute. Nothing is installed on the server, and the plugin installs nothing locally either — the agent probes the machine and decides what to run. Jobs keep running after DSH closes, and their logs stay in <remoteRoot>/<jobId> on the server until you delete them."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "SSH 远程算力",
4
+ "description": "通过 SSH 把一个远程服务器交给 Agent:在那里启动长任务、看日志、停任务,并双向传文件。在「设置 → 插件 → SSH 计算」里添加服务器;工具名为 ssh-compute。服务器上不装任何东西,本机也不装——插件只提供通道,由 Agent 自己探测机器、决定跑什么。任务在 DSH 关闭后仍在服务器上继续,日志留在 <remoteRoot>/<jobId>,不会自动清理。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "dsh-ssh-compute",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.2",
4
+ "description": "Runs compute-heavy work on remote SSH servers: one tool that starts background jobs over SSH, reads their logs, kills them, and moves files both ways.",
5
+ "type": "module",
6
+ "main": "index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./locale/*.json": "./locale/*.json",
12
+ "./icon": "./icon.svg"
13
+ },
14
+ "files": [
15
+ "index.js",
16
+ "lib",
17
+ "client.js",
18
+ "cordis.patch.yml",
19
+ "locale/*.json",
20
+ "icon.svg",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "peerDependencies": {
25
+ "@deepseek-ai/schemastery": "^3.18.1"
26
+ },
27
+ "peerDependenciesMeta": {
28
+ "@deepseek-ai/schemastery": {
29
+ "optional": true
30
+ }
31
+ },
32
+ "engines": {
33
+ "dsh": ">=0.2.2-rc.3"
34
+ },
35
+ "dsh": {
36
+ "bundle": {
37
+ "patch": "./cordis.patch.yml"
38
+ },
39
+ "client": {
40
+ "platform": "web",
41
+ "immediately": true,
42
+ "inject": [
43
+ "@deepseek-ai/dsh-client-ui-plugin-manager"
44
+ ]
45
+ }
46
+ },
47
+ "keywords": [
48
+ "dsh",
49
+ "dsh-plugin",
50
+ "deepseek-harness",
51
+ "ssh",
52
+ "remote",
53
+ "compute",
54
+ "tool"
55
+ ],
56
+ "author": "arcxya09",
57
+ "license": "MIT",
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/arcxya09/dsh-ssh-compute.git"
61
+ },
62
+ "homepage": "https://github.com/arcxya09/dsh-ssh-compute#readme",
63
+ "bugs": {
64
+ "url": "https://github.com/arcxya09/dsh-ssh-compute/issues"
65
+ },
66
+ "publishConfig": {
67
+ "access": "public"
68
+ }
69
+ }