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.
package/lib/schema.js ADDED
@@ -0,0 +1,108 @@
1
+ // How this plugin gets the schema builder behind `Config`.
2
+ //
3
+ // Two facts make this more than a one-line import:
4
+ //
5
+ // 1. `@deepseek-ai/schemastery` exports the builder as its DEFAULT export, so
6
+ // the namespace of `await import(...)` is `{ default: Schema }`. Destructuring
7
+ // a named `Schema` yields `undefined` without any error, the plugin then
8
+ // declares no `Config`, and its settings page silently disappears.
9
+ // 2. A bundle installed from a local directory is a `link:` symlink. Node
10
+ // resolves a module to its REAL path, so `@deepseek-ai/schemastery` is looked
11
+ // up beside the source checkout instead of beside the profile that provides
12
+ // it — and is not found. The settings page would be missing for exactly the
13
+ // install shape this plugin ships in.
14
+ //
15
+ // So resolution tries the normal way first and then the profile's own copy, and
16
+ // failing both costs only the settings page: the tool keeps working on defaults.
17
+
18
+ import { readFileSync } from 'node:fs'
19
+ import { createRequire } from 'node:module'
20
+ import { join } from 'node:path'
21
+ import { pathToFileURL } from 'node:url'
22
+
23
+ const PACKAGE = '@deepseek-ai/schemastery'
24
+
25
+ /**
26
+ * Pick the schema builder out of a module namespace.
27
+ *
28
+ * A named `Schema` export and a `Schema` property on the default are accepted
29
+ * too: other DSH packages re-export the builder in those shapes, and the check
30
+ * is about what can actually build a schema, not about one package.
31
+ * @param namespace - a module namespace (`await import(...)`), or anything else.
32
+ * @returns the builder, or null when the namespace carries none.
33
+ */
34
+ export function pickSchemaBuilder(namespace) {
35
+ if (namespace === null || typeof namespace !== 'object') return null
36
+ const candidates = [namespace.Schema, namespace.default?.Schema, namespace.default]
37
+ for (const candidate of candidates) {
38
+ // `object` is the entry point every Config needs: requiring it turns a wrong
39
+ // export shape into "no settings page" instead of a throw while the
40
+ // composition is already being built.
41
+ if (candidate !== null && candidate !== undefined && typeof candidate.object === 'function') {
42
+ return candidate
43
+ }
44
+ }
45
+ return null
46
+ }
47
+
48
+ /**
49
+ * The entry file of an installed copy of the package.
50
+ * @param directory - a directory whose `node_modules` holds the package.
51
+ * @returns an absolute path, or undefined when it is not installed there.
52
+ */
53
+ function entryIn(directory) {
54
+ const root = join(directory, 'node_modules', ...PACKAGE.split('/'))
55
+ try {
56
+ const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
57
+ const exported = manifest.exports?.['.']
58
+ const relative = typeof exported === 'string'
59
+ ? exported
60
+ : exported?.import ?? exported?.default ?? manifest.module ?? manifest.main
61
+ if (typeof relative === 'string') return join(root, relative)
62
+ } catch {
63
+ // Fall through to `createRequire`, which honours the exports map itself.
64
+ }
65
+ try {
66
+ return createRequire(join(directory, 'noop.cjs')).resolve(PACKAGE)
67
+ } catch {
68
+ return undefined
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Load the schema builder, wherever this installation keeps it.
74
+ * @param env - the process environment; `DSH_PROFILE_DIR` is the useful one.
75
+ * @returns the builder, or null when no usable copy was found.
76
+ */
77
+ export async function loadSchemaBuilder(env = process.env) {
78
+ const tried = []
79
+ try {
80
+ const builder = pickSchemaBuilder(await import(PACKAGE))
81
+ if (builder !== null) return builder
82
+ tried.push('package resolved but exported no builder')
83
+ } catch (error) {
84
+ tried.push(`package not resolvable from the plugin: ${error.message}`)
85
+ }
86
+
87
+ const directories = [env.DSH_PROFILE_DIR]
88
+ // A checkout launched without a profile still has the installation beside it.
89
+ if (env.DSH_HOME !== undefined) directories.push(env.DSH_HOME)
90
+ for (const directory of directories) {
91
+ if (typeof directory !== 'string' || directory === '') continue
92
+ const entry = entryIn(directory)
93
+ if (entry === undefined) {
94
+ tried.push(`no copy in ${directory}`)
95
+ continue
96
+ }
97
+ try {
98
+ const builder = pickSchemaBuilder(await import(pathToFileURL(entry).href))
99
+ if (builder !== null) return builder
100
+ tried.push(`no builder exported by ${entry}`)
101
+ } catch (error) {
102
+ tried.push(`${entry}: ${error.message}`)
103
+ }
104
+ }
105
+
106
+ console.warn(`dsh-ssh-compute: no settings schema (${tried.join('; ')})`)
107
+ return null
108
+ }
package/lib/shell.js ADDED
@@ -0,0 +1,69 @@
1
+ // Quoting helpers for the one place this plugin builds shell text: the command
2
+ // string that travels to a remote POSIX shell.
3
+ //
4
+ // Nothing here quotes for the LOCAL side. `ssh` is spawned from an argv array
5
+ // with no shell, so a path with spaces or `"` reaches ssh as one argument and
6
+ // only the remote shell ever parses it.
7
+
8
+ /**
9
+ * Wrap a value in POSIX single quotes, escaping embedded quotes.
10
+ * @param value - the text to quote.
11
+ * @returns the quoted shell word.
12
+ */
13
+ export function posixQuote(value) {
14
+ const text = String(value)
15
+ if (text === '') return "''"
16
+ return `'${text.replace(/'/g, "'\\''")}'`
17
+ }
18
+
19
+ /**
20
+ * Escape a value for use INSIDE an already-double-quoted shell string.
21
+ * `$HOME` expansion is why some paths use double quotes; anything else in the
22
+ * value must not be re-expanded by the remote shell.
23
+ * @param value - the text to escape.
24
+ * @returns the escaped text with no surrounding quotes.
25
+ */
26
+ export function doubleQuoteSafe(value) {
27
+ return String(value).replace(/[\\"$`]/g, (character) => `\\${character}`)
28
+ }
29
+
30
+ /**
31
+ * A remote directory expression that the remote shell can expand.
32
+ *
33
+ * `~/…` has to become `"$HOME/…"`, because a tilde inside quotes is literal. An
34
+ * absolute path stays a single-quoted literal. The result always ends in a
35
+ * closed quote, so callers may append `/segment` for generated names that need
36
+ * no quoting.
37
+ * @param remotePath - the configured directory, absolute or `~`-relative.
38
+ * @returns the shell expression naming it.
39
+ */
40
+ export function remotePathExpr(remotePath) {
41
+ const text = String(remotePath ?? '').trim()
42
+ const withoutTrailing = text.replace(/[/\\]+$/, '')
43
+ if (text.startsWith('/') && withoutTrailing === '') return posixQuote('/')
44
+ if (withoutTrailing === '' || withoutTrailing === '~') return '"$HOME"'
45
+ if (withoutTrailing.startsWith('~/')) {
46
+ return `"$HOME/${doubleQuoteSafe(withoutTrailing.slice(2))}"`
47
+ }
48
+ return posixQuote(withoutTrailing)
49
+ }
50
+
51
+ /**
52
+ * The last path segment of a remote path, for display only.
53
+ * @param remotePath - any path.
54
+ * @returns the final segment.
55
+ */
56
+ export function baseName(remotePath) {
57
+ const text = String(remotePath ?? '').replace(/[/\\]+$/, '')
58
+ const index = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
59
+ return index < 0 ? text : text.slice(index + 1)
60
+ }
61
+
62
+ /**
63
+ * Trim a trailing `\n` that a remote command adds to every one-line answer.
64
+ * @param text - a captured stdout value.
65
+ * @returns the value without its line ending.
66
+ */
67
+ export function stripLineEnding(text) {
68
+ return String(text ?? '').replace(/\r?\n$/, '')
69
+ }
package/lib/ssh.js ADDED
@@ -0,0 +1,312 @@
1
+ // The one process path.
2
+ //
3
+ // Everything here spawns from an argv array with no shell, so no local quoting
4
+ // is ever needed and a path with spaces reaches ssh intact. The remote command
5
+ // string is the only text a shell parses, and it is built in `remote.js`,
6
+ // `transfer.js` and `guard.js`.
7
+
8
+ import { spawn } from 'node:child_process'
9
+ import { createHash } from 'node:crypto'
10
+ import { mkdirSync, readdirSync, rmSync } from 'node:fs'
11
+ import { tmpdir } from 'node:os'
12
+ import { join } from 'node:path'
13
+
14
+ /** Captured stdout beyond this is dropped; a job log belongs in `logs`, not here. */
15
+ const MAX_CAPTURE = 8 * 1024 * 1024
16
+
17
+ /**
18
+ * Normalize a key option into a list of paths.
19
+ * @param keyFiles - one path, several, or nothing.
20
+ * @returns the paths to pass as `-i`.
21
+ */
22
+ export function keyList(keyFiles) {
23
+ if (keyFiles === undefined || keyFiles === null || keyFiles === '') return []
24
+ return Array.isArray(keyFiles) ? keyFiles.filter((value) => typeof value === 'string' && value !== '') : [keyFiles]
25
+ }
26
+
27
+ /**
28
+ * Whether a persistent master connection can be used on THIS host.
29
+ *
30
+ * Windows OpenSSH is not merely unsupported here, it is hostile: with a
31
+ * ControlPath set it tries to create an AF_UNIX socket, fails with
32
+ * `getsockname failed: Not a socket`, and tears down the connection it was
33
+ * opening (measured on OpenSSH_for_Windows_9.5p2). `ssh -G` still prints
34
+ * `controlmaster auto` there, so parsing the config cannot tell us; the platform
35
+ * is the only honest signal.
36
+ * @returns true when multiplexing is worth offering.
37
+ */
38
+ export function supportsConnectionReuse() {
39
+ return process.platform !== 'win32'
40
+ }
41
+
42
+ /** Where this plugin keeps the master sockets it created. */
43
+ export function controlDirectory() {
44
+ return join(tmpdir(), 'dsh-ssh-compute', 'cm')
45
+ }
46
+
47
+ /**
48
+ * The master socket path for one server.
49
+ *
50
+ * Short and content-addressed: a ControlPath has a small length limit on some
51
+ * systems, and two entries must not share a master unless they would open the
52
+ * SAME connection. The extra arguments are part of that identity — an entry with
53
+ * `-J bastion` riding a master opened without the jump host would connect
54
+ * somewhere else, or fail for no visible reason (measured: ssh ignores
55
+ * connection options when a live master already answers for the path).
56
+ * @param server - the target entry.
57
+ * @returns an absolute socket path.
58
+ */
59
+ export function controlPath(server) {
60
+ const identity = [server.user, server.host, server.port, ...(server.extraArgs ?? [])].join('\u0000')
61
+ const digest = createHash('sha1')
62
+ .update(identity)
63
+ .digest('hex')
64
+ .slice(0, 16)
65
+ // ssh does not create the directory it is told to put a socket in.
66
+ mkdirSync(controlDirectory(), { recursive: true, mode: 0o700 })
67
+ return join(controlDirectory(), `${digest}.sock`)
68
+ }
69
+
70
+ /**
71
+ * The `-o` options that turn one connection into a reusable master.
72
+ * @param config - the resolved configuration.
73
+ * @param server - the target entry.
74
+ * @returns argv pairs, or an empty array when reuse is off or unavailable.
75
+ */
76
+ export function controlOptions(config, server) {
77
+ if (config.reuseConnection === false || !supportsConnectionReuse()) return []
78
+ const persist = Math.max(0, Math.round((config.reuseIdleSeconds ?? 300)))
79
+ return [
80
+ '-o', 'ControlMaster=auto',
81
+ '-o', `ControlPath=${controlPath(server)}`,
82
+ '-o', `ControlPersist=${persist}`,
83
+ ]
84
+ }
85
+
86
+ /**
87
+ * Remove the socket files this plugin created.
88
+ *
89
+ * Best effort: a master that already expired leaves nothing to close, and a
90
+ * leftover socket file costs nothing next run. The masters are started with
91
+ * `ControlPersist`, so they expire on their own.
92
+ */
93
+ export function cleanupControlSockets() {
94
+ if (!supportsConnectionReuse()) return
95
+ let names = []
96
+ try {
97
+ names = readdirSync(controlDirectory())
98
+ } catch {
99
+ return
100
+ }
101
+ for (const name of names) {
102
+ if (name.endsWith('.sock')) {
103
+ try { rmSync(join(controlDirectory(), name), { force: true }) } catch { /* gone */ }
104
+ }
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Build the ssh argv for one server.
110
+ *
111
+ * `BatchMode=yes` matters more than it looks: without it ssh asks for a
112
+ * password on a terminal this process does not have, and the call hangs until
113
+ * it times out. `accept-new` records an unknown host key once and still refuses
114
+ * a CHANGED one, which is the only policy that works unattended.
115
+ * @param config - the resolved configuration.
116
+ * @param server - the target entry.
117
+ * @param keyFiles - `-i` paths, or nothing to let ssh decide.
118
+ * @returns the argv prefix, ending before the remote command.
119
+ */
120
+ export function sshArgv(config, server, keyFiles) {
121
+ const seconds = Math.max(1, Math.ceil(config.connectTimeoutMs / 1000))
122
+ const argv = [
123
+ 'ssh',
124
+ '-T',
125
+ '-o', 'BatchMode=yes',
126
+ '-o', 'StrictHostKeyChecking=accept-new',
127
+ '-o', `ConnectTimeout=${seconds}`,
128
+ '-o', 'ServerAliveInterval=15',
129
+ '-o', 'ServerAliveCountMax=4',
130
+ '-o', 'LogLevel=ERROR',
131
+ '-p', String(server.port),
132
+ ]
133
+ // Every discovered key is offered in turn: a machine commonly holds two, and
134
+ // only one of them is authorised on a given server.
135
+ for (const file of keyList(keyFiles)) argv.push('-i', file)
136
+ // A server may need a jump host or an option this plugin has no field for.
137
+ // These tokens are already split and validated (`lib/config.js`) and travel as
138
+ // argv, never through a shell.
139
+ for (const token of server.extraArgs ?? []) argv.push(token)
140
+ for (const token of controlOptions(config, server)) argv.push(token)
141
+ argv.push(`${server.user}@${server.host}`)
142
+ return argv
143
+ }
144
+
145
+ /**
146
+ * Run a process to completion, capturing bounded stdout.
147
+ * @param argv - the program and its arguments.
148
+ * @param options - stdin payload, working directory, deadline and abort signal.
149
+ * @returns stdout bytes, stderr text, exit code and elapsed time.
150
+ */
151
+ export function execProcess(argv, options = {}) {
152
+ const { input, cwd, timeoutMs, signal, maxBytes = MAX_CAPTURE } = options
153
+ return new Promise((resolve, reject) => {
154
+ let settled = false
155
+ const startedAt = Date.now()
156
+ let child
157
+ try {
158
+ child = spawn(argv[0], argv.slice(1), {
159
+ cwd,
160
+ windowsHide: true,
161
+ stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'],
162
+ })
163
+ } catch (error) {
164
+ reject(new Error(`dsh-ssh-compute: cannot start ${argv[0]}: ${error.message}`))
165
+ return
166
+ }
167
+
168
+ const chunks = []
169
+ let captured = 0
170
+ let truncated = false
171
+ let stderr = ''
172
+ let timedOut = false
173
+ let timer
174
+
175
+ const finish = (error, code) => {
176
+ if (settled) return
177
+ settled = true
178
+ if (timer !== undefined) clearTimeout(timer)
179
+ signal?.removeEventListener?.('abort', onAbort)
180
+ if (error !== undefined) {
181
+ reject(error)
182
+ return
183
+ }
184
+ resolve({
185
+ argv,
186
+ code,
187
+ stdout: Buffer.concat(chunks),
188
+ stderr,
189
+ truncated,
190
+ timedOut,
191
+ durationMs: Date.now() - startedAt,
192
+ })
193
+ }
194
+
195
+ const onAbort = () => {
196
+ try {
197
+ child.kill('SIGKILL')
198
+ } catch {
199
+ // Already gone.
200
+ }
201
+ finish(new Error('dsh-ssh-compute: the call was cancelled'))
202
+ }
203
+ signal?.addEventListener?.('abort', onAbort, { once: true })
204
+ if (signal?.aborted === true) {
205
+ onAbort()
206
+ return
207
+ }
208
+
209
+ child.stdout?.on('data', (chunk) => {
210
+ const room = maxBytes - captured
211
+ if (room <= 0) {
212
+ truncated = true
213
+ return
214
+ }
215
+ const slice = chunk.length > room ? chunk.subarray(0, room) : chunk
216
+ chunks.push(Buffer.from(slice))
217
+ captured += slice.length
218
+ if (slice.length < chunk.length) truncated = true
219
+ })
220
+ child.stderr?.on('data', (chunk) => {
221
+ // ssh diagnostics are short; keep the tail rather than growing forever.
222
+ stderr += chunk.toString('utf8')
223
+ if (stderr.length > 16384) stderr = stderr.slice(-16384)
224
+ })
225
+
226
+ child.on('error', (error) => {
227
+ if (error.code === 'ENOENT') {
228
+ finish(new Error(
229
+ `dsh-ssh-compute: "${argv[0]}" was not found. SSH must be installed and on PATH for this plugin.`,
230
+ ))
231
+ return
232
+ }
233
+ finish(new Error(`dsh-ssh-compute: ${argv[0]} failed: ${error.message}`))
234
+ })
235
+
236
+ child.on('close', (code) => {
237
+ if (timedOut) {
238
+ finish(new Error(
239
+ `dsh-ssh-compute: "${argv[0]}" did not finish within ${timeoutMs} ms and was stopped.`,
240
+ ))
241
+ return
242
+ }
243
+ finish(undefined, code)
244
+ })
245
+
246
+ if (timeoutMs !== undefined && timeoutMs > 0) {
247
+ timer = setTimeout(() => {
248
+ timedOut = true
249
+ try {
250
+ child.kill('SIGKILL')
251
+ } catch {
252
+ // Already gone.
253
+ }
254
+ }, timeoutMs)
255
+ timer.unref?.()
256
+ }
257
+
258
+ if (input !== undefined && child.stdin !== null) {
259
+ child.stdin.on('error', () => {
260
+ // A closed pipe here means the remote end already gave up; the exit code
261
+ // and stderr carry the reason.
262
+ })
263
+ child.stdin.end(input)
264
+ }
265
+ })
266
+ }
267
+
268
+ /**
269
+ * Start a process whose stdin and stdout the caller pipes (file transfer).
270
+ * @param argv - the program and its arguments.
271
+ * @param options - working directory and stdio shape.
272
+ * @returns the child process.
273
+ */
274
+ export function spawnStreaming(argv, options = {}) {
275
+ return spawn(argv[0], argv.slice(1), {
276
+ cwd: options.cwd,
277
+ windowsHide: true,
278
+ stdio: ['pipe', 'pipe', 'pipe'],
279
+ })
280
+ }
281
+
282
+ /**
283
+ * Run one ssh command and require success.
284
+ * @param context - resolved configuration, server, key file and deadline.
285
+ * @param command - the remote command string.
286
+ * @returns the raw process result.
287
+ */
288
+ export async function runSsh(context, command, options = {}) {
289
+ const argv = [...sshArgv(context.config, context.server, context.keyFile), command]
290
+ const result = await execProcess(argv, {
291
+ timeoutMs: options.timeoutMs ?? context.config.commandTimeoutMs,
292
+ maxBytes: options.maxBytes,
293
+ input: options.input,
294
+ signal: options.signal,
295
+ })
296
+ // A remote script may exit non-zero on purpose to report "no such job"; the
297
+ // caller decides which codes are answers rather than failures.
298
+ const answered = (options.expectedCodes ?? []).includes(result.code)
299
+ if (result.code !== 0 && !answered) {
300
+ // Windows OpenSSH returns 255 with an EMPTY stderr for some connection
301
+ // failures (measured: a failing ProxyCommand). "exit code 255" alone tells an
302
+ // agent nothing, so name the things that could be wrong instead.
303
+ const detail = result.stderr.trim() || (result.code === 255
304
+ ? 'ssh exited 255 without a message — check the address, port, user, key and extra ssh arguments'
305
+ : `exit code ${result.code}`)
306
+ throw new Error(
307
+ `dsh-ssh-compute: ${context.server.name} (${context.server.user}@${context.server.host}) ` +
308
+ `refused or failed the call: ${detail}`,
309
+ )
310
+ }
311
+ return result
312
+ }