@linxin666/dsh-client-ui-task-board-ssh 0.0.0-stage → 0.4.21

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 (128) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +96 -2
  4. package/README.zh.md +97 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4435 -0
  8. package/lib/index.js +7082 -0
  9. package/lib/types/client/PluginSettingsCard.d.ts +255 -0
  10. package/lib/types/client/RangeBubble.d.ts +46 -0
  11. package/lib/types/client/SegmentGroup.d.ts +28 -0
  12. package/lib/types/client/index.d.ts +100 -0
  13. package/lib/types/client/locales.d.ts +125 -0
  14. package/lib/types/client/seat-props.d.ts +53 -0
  15. package/lib/types/client/settings-entry-form.d.ts +49 -0
  16. package/lib/types/client/settings-form.d.ts +237 -0
  17. package/lib/types/client/ssh/card-decoration.d.ts +23 -0
  18. package/lib/types/client/ssh/compose-section.d.ts +7 -0
  19. package/lib/types/client/ssh/detail-section.d.ts +7 -0
  20. package/lib/types/client/ssh/extension.d.ts +54 -0
  21. package/lib/types/client/ssh/log-buffer.d.ts +128 -0
  22. package/lib/types/client/ssh/log-view.d.ts +37 -0
  23. package/lib/types/client/ssh/model.d.ts +130 -0
  24. package/lib/types/client/ssh/settings-section.d.ts +134 -0
  25. package/lib/types/client/ssh/summary.d.ts +160 -0
  26. package/lib/types/client/ssh/target-form.d.ts +60 -0
  27. package/lib/types/core/action.d.ts +89 -0
  28. package/lib/types/core/adapters/claude.d.ts +15 -0
  29. package/lib/types/core/adapters/codex.d.ts +15 -0
  30. package/lib/types/core/adapters/custom.d.ts +29 -0
  31. package/lib/types/core/adapters/dsh.d.ts +21 -0
  32. package/lib/types/core/adapters/index.d.ts +25 -0
  33. package/lib/types/core/adapters/types.d.ts +76 -0
  34. package/lib/types/core/contract.d.ts +453 -0
  35. package/lib/types/core/launcher-script.d.ts +13 -0
  36. package/lib/types/core/launcher.d.ts +153 -0
  37. package/lib/types/core/ledger.d.ts +123 -0
  38. package/lib/types/core/shell.d.ts +61 -0
  39. package/lib/types/core/target.d.ts +149 -0
  40. package/lib/types/core/task-record.d.ts +74 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +75 -0
  43. package/lib/types/host/engine.d.ts +563 -0
  44. package/lib/types/host/extension.d.ts +61 -0
  45. package/lib/types/host/inspect.d.ts +99 -0
  46. package/lib/types/host/logs.d.ts +135 -0
  47. package/lib/types/host/payload.d.ts +75 -0
  48. package/lib/types/host/prompt.d.ts +44 -0
  49. package/lib/types/host/queue.d.ts +53 -0
  50. package/lib/types/host/remote.d.ts +137 -0
  51. package/lib/types/host/settings.d.ts +149 -0
  52. package/lib/types/host/timers.d.ts +20 -0
  53. package/lib/types/host/tools.d.ts +17 -0
  54. package/lib/types/host/workspace/errors.d.ts +29 -0
  55. package/lib/types/host/workspace/git.d.ts +108 -0
  56. package/lib/types/host/workspace/in-place.d.ts +36 -0
  57. package/lib/types/host/workspace/index.d.ts +28 -0
  58. package/lib/types/host/workspace/layout.d.ts +62 -0
  59. package/lib/types/host/workspace/local-git.d.ts +72 -0
  60. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  61. package/lib/types/host/workspace/remote.d.ts +85 -0
  62. package/lib/types/host/workspace/types.d.ts +28 -0
  63. package/lib/types/host/workspace-seam.d.ts +100 -0
  64. package/lib/types/index.d.ts +97 -0
  65. package/lib/types/mount-once.d.ts +55 -0
  66. package/locale/en.json +6 -0
  67. package/locale/zh.json +6 -0
  68. package/package.json +89 -3
  69. package/src/client/PluginSettingsCard.tsx +838 -0
  70. package/src/client/RangeBubble.tsx +164 -0
  71. package/src/client/SegmentGroup.tsx +93 -0
  72. package/src/client/css-modules.d.ts +5 -0
  73. package/src/client/index.ts +195 -0
  74. package/src/client/locales.ts +257 -0
  75. package/src/client/seat-props.ts +58 -0
  76. package/src/client/settings-card.module.css +821 -0
  77. package/src/client/settings-entry-form.ts +141 -0
  78. package/src/client/settings-form.ts +529 -0
  79. package/src/client/ssh/card-decoration.tsx +55 -0
  80. package/src/client/ssh/compose-section.tsx +147 -0
  81. package/src/client/ssh/detail-section.tsx +345 -0
  82. package/src/client/ssh/extension.ts +271 -0
  83. package/src/client/ssh/log-buffer.ts +224 -0
  84. package/src/client/ssh/log-view.tsx +149 -0
  85. package/src/client/ssh/model.ts +299 -0
  86. package/src/client/ssh/settings-section.tsx +401 -0
  87. package/src/client/ssh/summary.ts +388 -0
  88. package/src/client/ssh/target-form.tsx +380 -0
  89. package/src/client/ssh.module.css +617 -0
  90. package/src/core/action.ts +270 -0
  91. package/src/core/adapters/claude.ts +64 -0
  92. package/src/core/adapters/codex.ts +83 -0
  93. package/src/core/adapters/custom.ts +88 -0
  94. package/src/core/adapters/dsh.ts +87 -0
  95. package/src/core/adapters/index.ts +74 -0
  96. package/src/core/adapters/types.ts +95 -0
  97. package/src/core/contract.ts +515 -0
  98. package/src/core/launcher-script.ts +313 -0
  99. package/src/core/launcher.ts +283 -0
  100. package/src/core/ledger.ts +377 -0
  101. package/src/core/shell.ts +77 -0
  102. package/src/core/target.ts +420 -0
  103. package/src/core/task-record.ts +73 -0
  104. package/src/core/workspace.ts +78 -0
  105. package/src/host/board.ts +107 -0
  106. package/src/host/engine.ts +2026 -0
  107. package/src/host/extension.ts +310 -0
  108. package/src/host/inspect.ts +264 -0
  109. package/src/host/logs.ts +297 -0
  110. package/src/host/payload.ts +134 -0
  111. package/src/host/prompt.ts +89 -0
  112. package/src/host/queue.ts +73 -0
  113. package/src/host/remote.ts +356 -0
  114. package/src/host/settings.ts +294 -0
  115. package/src/host/timers.ts +33 -0
  116. package/src/host/tools.ts +449 -0
  117. package/src/host/workspace/errors.ts +43 -0
  118. package/src/host/workspace/git.ts +305 -0
  119. package/src/host/workspace/in-place.ts +58 -0
  120. package/src/host/workspace/index.ts +37 -0
  121. package/src/host/workspace/layout.ts +122 -0
  122. package/src/host/workspace/local-git.ts +164 -0
  123. package/src/host/workspace/remote-git.ts +244 -0
  124. package/src/host/workspace/remote.ts +181 -0
  125. package/src/host/workspace/types.ts +34 -0
  126. package/src/host/workspace-seam.ts +132 -0
  127. package/src/index.ts +243 -0
  128. package/src/mount-once.ts +142 -0
@@ -0,0 +1,356 @@
1
+ /**
2
+ * Every remote operation one run performs, over the `dshSsh` face.
3
+ *
4
+ * The remote side is one POSIX `sh` script the provider installs once per host
5
+ * (`src/core/launcher.ts` builds every command and reads every answer); this
6
+ * module is the only place that composes those commands with the `dshSsh`
7
+ * `exec` forwarder, so no other file in the host half talks to a host directly.
8
+ *
9
+ * Three guarantees live here and nowhere else:
10
+ *
11
+ * - The state directory is resolved once per host from the host's own `$HOME`
12
+ * and cached, so no command depends on the remote shell expanding a tilde.
13
+ * - `start` is de-duplicated in flight: the pool may replay a command when it
14
+ * reconnects, and a replayed start must join the start already running instead
15
+ * of spawning a second agent (the script is idempotent on the run id as well,
16
+ * which covers a replay that arrives after this process forgot the first one).
17
+ * - A failed remote command is one diagnosable error carrying the host's own
18
+ * stderr, bounded, instead of a silent `success: false` a caller can ignore.
19
+ *
20
+ * @module dsh-task-board-ssh/host/remote
21
+ */
22
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
23
+ import { tmpdir } from 'node:os'
24
+ import { join } from 'node:path'
25
+ import type { DshSshService } from '../core/contract.ts'
26
+ import type { SshAgentCommand } from '../core/adapters/types.ts'
27
+ import {
28
+ agentScript,
29
+ buildLauncherCommand,
30
+ buildLauncherInstallCommand,
31
+ buildRunFileCommands,
32
+ parseLauncherStatus,
33
+ runDirectory,
34
+ runFilePath,
35
+ stateDirForHome,
36
+ type LauncherStatus,
37
+ } from '../core/launcher.ts'
38
+ import { shellEnsureDir, shellRemoveDir, shellWriteFile } from '../core/shell.ts'
39
+
40
+ /** Ceiling for one remote command, in milliseconds. */
41
+ export const DEFAULT_COMMAND_TIMEOUT_MS = 30_000
42
+
43
+ /**
44
+ * Prompts whose shell-quoted command exceeds this threshold are uploaded via
45
+ * SFTP instead of inlined into `sh -c`, staying well below Linux's 128 KiB
46
+ * `MAX_ARG_STRLEN` limit (E2BIG).
47
+ */
48
+ const INLINE_PROMPT_COMMAND_LIMIT_BYTES = 32 * 1024
49
+
50
+ /** Longest remote error text this module carries into a message, in characters. */
51
+ const ERROR_TEXT_MAX = 400
52
+
53
+ /** What one remote call addresses. */
54
+ export interface SshRemoteRef {
55
+ /** `dshSsh` host alias. */
56
+ alias: string
57
+ /** Absolute remote state directory the provider owns on that host. */
58
+ stateDir: string
59
+ /** Run the call addresses. */
60
+ runId: string
61
+ }
62
+
63
+ /** The files one run's start writes before the launcher runs it. */
64
+ export interface SshRemoteRunFiles {
65
+ /** Prompt text the agent reads. */
66
+ prompt: string
67
+ /** Quoted command line the launcher executes. */
68
+ command: SshAgentCommand
69
+ /** Absolute remote directory the run works in. */
70
+ cwd: string
71
+ /** Opaque spec the provider keeps for its own reconciliation. */
72
+ spec: unknown
73
+ }
74
+
75
+ /** A remote command that could not be completed, in the host's own words. */
76
+ export class SshRemoteError extends Error {
77
+ /** Host the command addressed. */
78
+ readonly alias: string
79
+ /** What the command was for. */
80
+ readonly what: string
81
+
82
+ constructor(alias: string, what: string, message: string) {
83
+ super(`remote ${what} on ${alias} failed: ${message}`)
84
+ this.name = 'SshRemoteError'
85
+ this.alias = alias
86
+ this.what = what
87
+ }
88
+ }
89
+
90
+ /** One page of a run's log, as the read verb returned it. */
91
+ export interface SshTailPage {
92
+ /** Bytes the remote log held from the requested offset to its end, as text. */
93
+ text: string
94
+ /** Byte offset the next read starts at. */
95
+ bytes: number
96
+ }
97
+
98
+ /** Options of {@link SshRemote}. */
99
+ export interface SshRemoteOptions {
100
+ /** Ceiling for one remote command, in milliseconds. */
101
+ timeoutMs?: number
102
+ }
103
+
104
+ /** Bound a remote message before it reaches a card, a log line or a summary. */
105
+ function bounded(text: string): string {
106
+ const trimmed = text.trim()
107
+ return trimmed.length <= ERROR_TEXT_MAX ? trimmed : trimmed.slice(0, ERROR_TEXT_MAX) + '...'
108
+ }
109
+
110
+ export class SshRemote {
111
+ private readonly ssh: DshSshService
112
+ private readonly timeoutMs: number
113
+ private readonly stateDirs = new Map<string, string>()
114
+ private readonly starting = new Map<string, Promise<LauncherStatus>>()
115
+ private readonly installing = new Map<string, Promise<void>>()
116
+
117
+ constructor(ssh: DshSshService, options: SshRemoteOptions = {}) {
118
+ this.ssh = ssh
119
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS
120
+ }
121
+
122
+ /** The state directory of a host when it was already resolved, without a round trip. */
123
+ cachedStateDir(alias: string): string | undefined {
124
+ return this.stateDirs.get(alias)
125
+ }
126
+
127
+ /** Forget every cached path of one host, or of all hosts when none is named. */
128
+ forget(alias?: string): void {
129
+ if (alias === undefined) {
130
+ this.stateDirs.clear()
131
+ this.installing.clear()
132
+ } else {
133
+ this.stateDirs.delete(alias)
134
+ for (const key of this.installing.keys()) {
135
+ if (key.startsWith(alias + '/')) this.installing.delete(key)
136
+ }
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Resolve (and cache) the absolute state directory of one host.
142
+ * @param alias - host alias.
143
+ * @returns the directory the provider installs the launcher and its runs under.
144
+ */
145
+ async stateDir(alias: string): Promise<string> {
146
+ const cached = this.stateDirs.get(alias)
147
+ if (cached !== undefined) return cached
148
+ const result = await this.ssh.exec(alias, 'printf %s "$HOME"', { timeoutMs: this.timeoutMs })
149
+ const home = result.success ? result.stdout.trim() : ''
150
+ if (home === '' || !home.startsWith('/')) {
151
+ throw new SshRemoteError(alias, 'home lookup', result.error ?? (result.stderr.trim() || 'the host reported no home directory'))
152
+ }
153
+ const stateDir = stateDirForHome(home)
154
+ this.stateDirs.set(alias, stateDir)
155
+ return stateDir
156
+ }
157
+
158
+ /**
159
+ * Install (or refresh) the launcher script on one host, deduplicating
160
+ * concurrent installs on the same host and state directory.
161
+ * @param ref - host and state directory.
162
+ */
163
+ async installLauncher(ref: { alias: string; stateDir: string }): Promise<void> {
164
+ const key = ref.alias + '/' + ref.stateDir
165
+ const inflight = this.installing.get(key)
166
+ if (inflight !== undefined) return await inflight
167
+ const task = (async (): Promise<void> => {
168
+ try {
169
+ await this.run(ref.alias, buildLauncherInstallCommand(ref.stateDir), 'launcher install')
170
+ } finally {
171
+ this.installing.delete(key)
172
+ }
173
+ })()
174
+ this.installing.set(key, task)
175
+ return await task
176
+ }
177
+
178
+ /**
179
+ * Write every file one run needs before `start`.
180
+ *
181
+ * Large prompts are uploaded through SFTP instead of inlined into a single
182
+ * shell command line so multi-megabyte prompts never trip Linux `E2BIG`.
183
+ * @param ref - host, state directory and run.
184
+ * @param files - prompt, command line, working directory and spec.
185
+ */
186
+ async writeRunFiles(ref: SshRemoteRef, files: SshRemoteRunFiles): Promise<void> {
187
+ const commands = buildRunFileCommands({
188
+ stateDir: ref.stateDir,
189
+ runId: ref.runId,
190
+ prompt: files.prompt,
191
+ command: files.command,
192
+ cwd: files.cwd,
193
+ spec: files.spec,
194
+ })
195
+ const combined = commands.join(' && ')
196
+ if (new TextEncoder().encode(combined).length <= INLINE_PROMPT_COMMAND_LIMIT_BYTES) {
197
+ await this.run(ref.alias, combined, 'run file write')
198
+ return
199
+ }
200
+ const directory = runDirectory(ref.stateDir, ref.runId)
201
+ const metadataCommands = [
202
+ shellEnsureDir(directory),
203
+ shellWriteFile(runFilePath(ref.stateDir, ref.runId, 'cmd.sh'), agentScript(files.command)),
204
+ shellWriteFile(runFilePath(ref.stateDir, ref.runId, 'cwd'), files.cwd),
205
+ shellWriteFile(runFilePath(ref.stateDir, ref.runId, 'spec.json'), JSON.stringify(files.spec)),
206
+ ]
207
+ await this.run(ref.alias, metadataCommands.join(' && '), 'run file write')
208
+ const scratch = await mkdtemp(join(tmpdir(), 'dsh-task-board-ssh-prompt-'))
209
+ try {
210
+ const localPrompt = join(scratch, 'prompt.txt')
211
+ await writeFile(localPrompt, files.prompt, 'utf8')
212
+ await this.ssh.upload(ref.alias, localPrompt, runFilePath(ref.stateDir, ref.runId, 'prompt.txt'))
213
+ } catch (error) {
214
+ throw new SshRemoteError(ref.alias, 'prompt upload', error instanceof Error ? error.message : String(error))
215
+ } finally {
216
+ await rm(scratch, { recursive: true, force: true })
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Ask the launcher to start one run, joining a start already in flight.
222
+ * @param ref - host, state directory and run.
223
+ * @returns the state line the launcher printed.
224
+ */
225
+ async start(ref: SshRemoteRef): Promise<LauncherStatus> {
226
+ const key = ref.alias + '/' + ref.runId
227
+ const inflight = this.starting.get(key)
228
+ if (inflight !== undefined) return await inflight
229
+ const started = (async (): Promise<LauncherStatus> => {
230
+ try {
231
+ const result = await this.run(ref.alias, buildLauncherCommand({
232
+ stateDir: ref.stateDir,
233
+ verb: 'start',
234
+ runId: ref.runId,
235
+ }), 'start')
236
+ return parseLauncherStatus(result.stdout)
237
+ } finally {
238
+ this.starting.delete(key)
239
+ }
240
+ })()
241
+ this.starting.set(key, started)
242
+ return await started
243
+ }
244
+
245
+ /**
246
+ * Read one run's state.
247
+ * @param ref - host, state directory and run.
248
+ * @returns the state line the launcher printed.
249
+ */
250
+ async status(ref: SshRemoteRef): Promise<LauncherStatus> {
251
+ const result = await this.run(ref.alias, buildLauncherCommand({
252
+ stateDir: ref.stateDir,
253
+ verb: 'status',
254
+ runId: ref.runId,
255
+ }), 'status')
256
+ return parseLauncherStatus(result.stdout)
257
+ }
258
+
259
+ /**
260
+ * Read a run's log from a byte offset, optionally capped to `limit` bytes.
261
+ * @param ref - host, state directory and run.
262
+ * @param offset - first byte to return.
263
+ * @param limit - optional maximum byte count to return (prevents hitting dsh-ssh's 2 MiB output cap).
264
+ * @returns the text and the offset the next read starts at.
265
+ */
266
+ async tail(ref: SshRemoteRef, offset: number, limit?: number): Promise<SshTailPage> {
267
+ const result = await this.run(ref.alias, buildLauncherCommand({
268
+ stateDir: ref.stateDir,
269
+ verb: 'tail',
270
+ runId: ref.runId,
271
+ offset,
272
+ ...(limit === undefined ? {} : { limit }),
273
+ }), 'tail')
274
+ const text = result.stdout
275
+ return { text, bytes: offset + new TextEncoder().encode(text).length }
276
+ }
277
+
278
+ /**
279
+ * Read the bounded tail of a run's `stderr.log`, for diagnosing failures when
280
+ * `stdout.log` carries no structured agent event.
281
+ * @param ref - host, state directory and run.
282
+ * @param limit - maximum bytes from the end of `stderr.log`.
283
+ * @returns trimmed stderr text, or empty string when unavailable.
284
+ */
285
+ async stderr(ref: SshRemoteRef, limit = 4096): Promise<string> {
286
+ try {
287
+ const result = await this.run(ref.alias, buildLauncherCommand({
288
+ stateDir: ref.stateDir,
289
+ verb: 'stderr',
290
+ runId: ref.runId,
291
+ limit,
292
+ }), 'stderr')
293
+ return result.stdout.trim()
294
+ } catch {
295
+ return ''
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Ask the launcher to cancel one run.
301
+ * @param ref - host, state directory and run.
302
+ * @returns the state line the launcher printed.
303
+ */
304
+ async cancel(ref: SshRemoteRef): Promise<LauncherStatus> {
305
+ const result = await this.run(ref.alias, buildLauncherCommand({
306
+ stateDir: ref.stateDir,
307
+ verb: 'cancel',
308
+ runId: ref.runId,
309
+ }), 'cancel', 15_000)
310
+ return parseLauncherStatus(result.stdout)
311
+ }
312
+
313
+ /**
314
+ * Remove one run directory from the host, tolerating its absence.
315
+ * @param ref - host, state directory and run.
316
+ */
317
+ async removeRun(ref: SshRemoteRef): Promise<void> {
318
+ await this.run(ref.alias, shellRemoveDir(runDirectory(ref.stateDir, ref.runId)), 'run directory removal')
319
+ }
320
+
321
+ /**
322
+ * Run one read-only diagnostic command and hand back the raw result, whether
323
+ * or not it succeeded: the caller decides what a failure means.
324
+ * @param alias - host alias.
325
+ * @param command - command line, already quoted.
326
+ * @param timeoutMs - ceiling for this command.
327
+ * @returns what the forwarder reported; a thrown forwarder becomes a failed result.
328
+ */
329
+ async probe(alias: string, command: string, timeoutMs = this.timeoutMs): Promise<{ success: boolean; stdout: string; stderr: string; error?: string; timedOut: boolean }> {
330
+ try {
331
+ const result = await this.ssh.exec(alias, command, { timeoutMs })
332
+ return {
333
+ success: result.success,
334
+ stdout: result.stdout,
335
+ stderr: result.stderr,
336
+ timedOut: result.timedOut,
337
+ ...(result.error === undefined ? {} : { error: result.error }),
338
+ }
339
+ } catch (error) {
340
+ return { success: false, stdout: '', stderr: '', timedOut: false, error: error instanceof Error ? error.message : String(error) }
341
+ }
342
+ }
343
+
344
+ /** Run one command and refuse a failed one in the host's own words. */
345
+ private async run(alias: string, command: string, what: string, timeoutMs = this.timeoutMs): Promise<{ stdout: string }> {
346
+ const result = await this.ssh.exec(alias, command, { timeoutMs })
347
+ if (result.success) return { stdout: result.stdout }
348
+ const detail = result.error ?? result.stderr.trim()
349
+ const reason = detail !== ''
350
+ ? bounded(detail)
351
+ : result.timedOut
352
+ ? `it did not finish within ${String(timeoutMs)} ms`
353
+ : `the command exited with code ${String(result.exitCode ?? 'none')}`
354
+ throw new SshRemoteError(alias, what, reason)
355
+ }
356
+ }
@@ -0,0 +1,294 @@
1
+ /**
2
+ * This extension's own configuration: reading it live, and the single path that
3
+ * writes it back.
4
+ *
5
+ * The fields are `volatile()` in the Config schema, so the Host's settings
6
+ * surface commits a write into the running fiber without a remount and every
7
+ * consumer here reads them at use time. That is why this module has no cache and
8
+ * no second store: a settings write reaches the next admission, the next run and
9
+ * the next tool call through {@link SshProviderSettings} alone.
10
+ *
11
+ * @module dsh-task-board-ssh/host/settings
12
+ */
13
+ import { validateCustomTemplate, type SshCustomTemplates } from '../core/adapters/index.ts'
14
+ import { SSH_AGENT_KINDS, type SshAgentKind, type SshExecutionMode } from '../core/target.ts'
15
+ import { DEFAULT_PER_HOST_CAP, normalizePerHostCap } from './queue.ts'
16
+
17
+ /** Default agent CLI a card starts when neither the card nor the deployment pins one. */
18
+ export const DEFAULT_AGENT_KIND: SshAgentKind = 'dsh'
19
+
20
+ /** Default execution mode of a card that pins no target yet. */
21
+ export const DEFAULT_EXECUTION_MODE: SshExecutionMode = 'direct'
22
+
23
+ /** Profile entry ids this package's rows carry, most specific first. */
24
+ export const SSH_ENTRY_IDS: readonly string[] = ['web-ui-task-board-ssh', 'ui-task-board-ssh', 'dsh-task-board-ssh']
25
+
26
+ /** Host alias grammar the target parser accepts, restated for the writer. */
27
+ const HOST_ALIAS_RE = /^[A-Za-z0-9._-]{1,128}$/
28
+
29
+ /** The effective configuration of one mount. */
30
+ export interface SshProviderSettings {
31
+ /** Master switch of the extension. */
32
+ enabled: boolean
33
+ /** Host a card opens with when neither the card nor the browser pins one. */
34
+ defaultHost: string
35
+ /** Agent CLI a card opens with. */
36
+ defaultAgent: SshAgentKind
37
+ /** Execution mode a card opens with. */
38
+ defaultMode: SshExecutionMode
39
+ /** How many runs one host executes at once; the rest wait in the queue. */
40
+ perHostCap: number
41
+ /** Per-agent command templates that replace the built-in command line. */
42
+ agentCommands: Partial<Record<SshAgentKind, SshCustomTemplates>>
43
+ }
44
+
45
+ /** What a deployment that configured nothing gets. */
46
+ export const DEFAULT_SSH_SETTINGS: SshProviderSettings = {
47
+ enabled: true,
48
+ defaultHost: '',
49
+ defaultAgent: DEFAULT_AGENT_KIND,
50
+ defaultMode: DEFAULT_EXECUTION_MODE,
51
+ perHostCap: DEFAULT_PER_HOST_CAP,
52
+ agentCommands: {},
53
+ }
54
+
55
+ /**
56
+ * Read one config field's live value.
57
+ *
58
+ * A `volatile()` field arrives as a live reference the Loader updates in place,
59
+ * so it is unwrapped on every read instead of being captured once.
60
+ * @param field - the field as the Loader handed it.
61
+ * @param fallback - value when the field is absent.
62
+ * @returns the effective value.
63
+ */
64
+ export function readConfigField<T>(field: unknown, fallback: T): T {
65
+ if (field === undefined || field === null) return fallback
66
+ if (typeof field === 'object' && typeof (field as { get?: unknown }).get === 'function') {
67
+ return (field as { get: () => unknown }).get() as T
68
+ }
69
+ return field as T
70
+ }
71
+
72
+ /** Read one configured agent-command row. */
73
+ function readAgentCommandRow(row: unknown): { kind: SshAgentKind; templates: SshCustomTemplates } | undefined {
74
+ if (typeof row !== 'object' || row === null) return undefined
75
+ const record = row as Record<string, unknown>
76
+ const kind = (SSH_AGENT_KINDS as readonly string[]).includes(String(record.kind))
77
+ ? String(record.kind) as SshAgentKind
78
+ : undefined
79
+ const command = typeof record.command === 'string' ? record.command : ''
80
+ const resumeCommand = typeof record.resumeCommand === 'string' ? record.resumeCommand : ''
81
+ if (kind === undefined || command.trim() === '') return undefined
82
+ if (validateCustomTemplate(command) !== undefined) return undefined
83
+ if (resumeCommand.trim() !== '' && validateCustomTemplate(resumeCommand) !== undefined) return undefined
84
+ return {
85
+ kind,
86
+ templates: {
87
+ command,
88
+ ...(resumeCommand.trim() === '' ? {} : { resumeCommand }),
89
+ },
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Normalize the row's own configuration.
95
+ * @param config - the config the Loader activated this row with.
96
+ * @returns the settings every consumer reads.
97
+ */
98
+ export function parseSshSettings(config: unknown): SshProviderSettings {
99
+ const source = typeof config === 'object' && config !== null ? config as Record<string, unknown> : {}
100
+ const agent = readConfigField<unknown>(source.defaultAgent, DEFAULT_AGENT_KIND)
101
+ const mode = readConfigField<unknown>(source.defaultMode, DEFAULT_EXECUTION_MODE)
102
+ const host = readConfigField<unknown>(source.defaultHost, '')
103
+ const rows = readConfigField<unknown>(source.agentCommands, [])
104
+ const agentCommands: Partial<Record<SshAgentKind, SshCustomTemplates>> = {}
105
+ if (Array.isArray(rows)) {
106
+ for (const row of rows) {
107
+ const parsed = readAgentCommandRow(row)
108
+ if (parsed !== undefined) agentCommands[parsed.kind] = parsed.templates
109
+ }
110
+ }
111
+ return {
112
+ enabled: readConfigField<unknown>(source.enabled, true) !== false,
113
+ defaultHost: typeof host === 'string' && HOST_ALIAS_RE.test(host.trim()) ? host.trim() : '',
114
+ defaultAgent: (SSH_AGENT_KINDS as readonly string[]).includes(String(agent)) ? String(agent) as SshAgentKind : DEFAULT_AGENT_KIND,
115
+ defaultMode: mode === 'proxy' ? 'proxy' : DEFAULT_EXECUTION_MODE,
116
+ perHostCap: normalizePerHostCap(readConfigField<unknown>(source.perHostCap, DEFAULT_PER_HOST_CAP)),
117
+ agentCommands,
118
+ }
119
+ }
120
+
121
+ /** One path-addressed edit the settings surface accepts. */
122
+ export type SettingsPathOp =
123
+ | { op: 'set'; path: readonly string[]; value: unknown }
124
+ | { op: 'unset'; path: readonly string[] }
125
+
126
+ /** One entry the settings surface reports. */
127
+ export interface SettingsDescriptor {
128
+ /** Profile entry id the form belongs to. */
129
+ ns?: unknown
130
+ /** Revision the form was built from. */
131
+ revision?: unknown
132
+ }
133
+
134
+ /** The slice of the Host settings surface this extension uses. */
135
+ export interface SettingsFace {
136
+ /** Whether the active profile accepts form edits. */
137
+ readonly writable: boolean
138
+ /** Read the live forms. */
139
+ describe(options?: { redactSecrets?: boolean }): SettingsDescriptor[]
140
+ /** Apply field edits to one entry against the revision it was read at. */
141
+ mutate(ns: string, ops: readonly SettingsPathOp[], expectedRevision?: number): Promise<void>
142
+ }
143
+
144
+ /** A configuration write this deployment refused, in the term the caller acts on. */
145
+ export class SshSettingsError extends Error {
146
+ /** Stable machine code the action reply and the tool carry. */
147
+ readonly code: string
148
+
149
+ constructor(code: string, message: string) {
150
+ super(`task-board-ssh settings [${code}]: ${message}`)
151
+ this.name = 'SshSettingsError'
152
+ this.code = code
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Read the settings surface off the injected `settings` service.
158
+ * @param value - the service as the injected scope carries it.
159
+ * @returns the face, or undefined when this deployment serves none.
160
+ */
161
+ export function readSettingsFace(value: unknown): SettingsFace | undefined {
162
+ if (typeof value !== 'object' || value === null) return undefined
163
+ const face = value as { describe?: unknown; mutate?: unknown }
164
+ if (typeof face.describe !== 'function' || typeof face.mutate !== 'function') return undefined
165
+ return value as SettingsFace
166
+ }
167
+
168
+ /**
169
+ * Find this extension's own entry among the settings surface's forms.
170
+ * @param face - the settings surface.
171
+ * @returns the entry id and its current revision, or undefined when this
172
+ * deployment exposes no form for this extension.
173
+ */
174
+ export function findSshSettingsEntry(face: SettingsFace): { ns: string; revision: number } | undefined {
175
+ let descriptors: SettingsDescriptor[]
176
+ try {
177
+ descriptors = face.describe({ redactSecrets: true })
178
+ } catch {
179
+ return undefined
180
+ }
181
+ for (const wanted of SSH_ENTRY_IDS) {
182
+ const hit = descriptors.find(descriptor => descriptor.ns === wanted)
183
+ if (hit !== undefined) {
184
+ return { ns: wanted, revision: typeof hit.revision === 'number' ? hit.revision : 0 }
185
+ }
186
+ }
187
+ return undefined
188
+ }
189
+
190
+ /** One configuration change a caller may ask for. */
191
+ export interface SshSettingsPatch {
192
+ /** Master switch. */
193
+ enabled?: boolean
194
+ /** Host a card opens with. */
195
+ defaultHost?: string
196
+ /** Agent CLI a card opens with. */
197
+ defaultAgent?: SshAgentKind
198
+ /** Execution mode a card opens with. */
199
+ defaultMode?: SshExecutionMode
200
+ /** Concurrent runs per host. */
201
+ perHostCap?: number
202
+ /** Full replacement of the per-agent command overrides. */
203
+ agentCommands?: ReadonlyArray<{ kind: SshAgentKind; command: string; resumeCommand?: string }>
204
+ }
205
+
206
+ /** What one accepted write stored. */
207
+ export interface SshSettingsWriteResult {
208
+ /** Profile entry the write landed in. */
209
+ entry: string
210
+ /** Fields the write addressed, in the order they were applied. */
211
+ fields: string[]
212
+ }
213
+
214
+ /**
215
+ * The one write path of this extension's configuration.
216
+ *
217
+ * Every caller — a settings card, an action, a future host route — composes a
218
+ * patch and hands it here; nothing else calls `settings.mutate` for this
219
+ * extension, so there is exactly one place where a value is validated, one
220
+ * revision it is written against, and one set of volatile fields it may name.
221
+ */
222
+ export class SshSettingsWriter {
223
+ private readonly face: () => SettingsFace | undefined
224
+
225
+ constructor(face: () => SettingsFace | undefined) {
226
+ this.face = face
227
+ }
228
+
229
+ /** Whether a write can be attempted at all right now. */
230
+ available(): boolean {
231
+ return this.face() !== undefined
232
+ }
233
+
234
+ /**
235
+ * Validate one patch and write it in a single batch.
236
+ * @param patch - the change to store.
237
+ * @returns which entry and fields the write addressed.
238
+ * @throws SshSettingsError when the patch is unusable or the deployment refuses.
239
+ */
240
+ async save(patch: SshSettingsPatch): Promise<SshSettingsWriteResult> {
241
+ const ops: SettingsPathOp[] = []
242
+ if (patch.enabled !== undefined) ops.push({ op: 'set', path: ['enabled'], value: patch.enabled })
243
+ if (patch.defaultHost !== undefined) {
244
+ const host = patch.defaultHost.trim()
245
+ if (host !== '' && !HOST_ALIAS_RE.test(host)) {
246
+ throw new SshSettingsError('invalid-host', 'the default host must be a dshSsh host alias of letters, digits, dots, hyphens and underscores')
247
+ }
248
+ ops.push({ op: 'set', path: ['defaultHost'], value: host })
249
+ }
250
+ if (patch.defaultAgent !== undefined) {
251
+ if (!(SSH_AGENT_KINDS as readonly string[]).includes(patch.defaultAgent)) {
252
+ throw new SshSettingsError('invalid-agent', `the default agent must be one of: ${SSH_AGENT_KINDS.join(', ')}`)
253
+ }
254
+ ops.push({ op: 'set', path: ['defaultAgent'], value: patch.defaultAgent })
255
+ }
256
+ if (patch.defaultMode !== undefined) {
257
+ if (patch.defaultMode !== 'direct' && patch.defaultMode !== 'proxy') {
258
+ throw new SshSettingsError('invalid-mode', 'the default mode must be "direct" or "proxy"')
259
+ }
260
+ ops.push({ op: 'set', path: ['defaultMode'], value: patch.defaultMode })
261
+ }
262
+ if (patch.perHostCap !== undefined) {
263
+ if (typeof patch.perHostCap !== 'number' || !Number.isFinite(patch.perHostCap)) {
264
+ throw new SshSettingsError('invalid-cap', 'the per-host cap must be a number')
265
+ }
266
+ ops.push({ op: 'set', path: ['perHostCap'], value: normalizePerHostCap(patch.perHostCap) })
267
+ }
268
+ if (patch.agentCommands !== undefined) {
269
+ const rows: Array<{ kind: string; command: string; resumeCommand: string }> = []
270
+ for (const row of patch.agentCommands) {
271
+ if (!(SSH_AGENT_KINDS as readonly string[]).includes(row.kind)) {
272
+ throw new SshSettingsError('invalid-agent', `a command override names an unknown agent: ${String(row.kind)}`)
273
+ }
274
+ const problem = validateCustomTemplate(row.command)
275
+ if (problem !== undefined) throw new SshSettingsError('invalid-command', `the ${row.kind} command override: ${problem}`)
276
+ const resumeCommand = row.resumeCommand?.trim() ?? ''
277
+ if (resumeCommand !== '') {
278
+ const resumeProblem = validateCustomTemplate(resumeCommand)
279
+ if (resumeProblem !== undefined) throw new SshSettingsError('invalid-command', `the ${row.kind} resume override: ${resumeProblem}`)
280
+ }
281
+ rows.push({ kind: row.kind, command: row.command, resumeCommand })
282
+ }
283
+ ops.push({ op: 'set', path: ['agentCommands'], value: rows })
284
+ }
285
+ if (ops.length === 0) throw new SshSettingsError('empty-patch', 'the patch addresses no configuration field')
286
+ const face = this.face()
287
+ if (face === undefined) throw new SshSettingsError('settings-unavailable', 'this deployment serves no settings surface')
288
+ if (face.writable === false) throw new SshSettingsError('settings-readonly', 'this deployment serves configuration read-only')
289
+ const entry = findSshSettingsEntry(face)
290
+ if (entry === undefined) throw new SshSettingsError('settings-entry-missing', 'this deployment exposes no settings form for the SSH extension')
291
+ await face.mutate(entry.ns, ops, entry.revision)
292
+ return { entry: entry.ns, fields: ops.map(op => op.path.join('.')) }
293
+ }
294
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The timer seat the run engine schedules through.
3
+ *
4
+ * The engine never reaches for a global timer directly: the host entry injects
5
+ * this face, so the poll cadence is observable, cancellable and — in tests —
6
+ * advanced by hand instead of waited on. A deployment with no opinion gets
7
+ * {@link processTimers}, which unrefs both handles so a board that is polling
8
+ * nothing keeps the process free to exit.
9
+ *
10
+ * @module dsh-task-board-ssh/host/timers
11
+ */
12
+
13
+ /** The timer operations the engine needs, each returning its own canceller. */
14
+ export interface HostTimerFace {
15
+ /** Run `callback` once after `delay` ms. */
16
+ timeout(callback: () => void, delay: number): () => void
17
+ /** Run `callback` every `delay` ms. */
18
+ interval(callback: () => void, delay: number): () => void
19
+ }
20
+
21
+ /** The process timer face: what a real Host mount uses. */
22
+ export const processTimers: HostTimerFace = {
23
+ timeout(callback, delay) {
24
+ const handle = setTimeout(callback, delay)
25
+ handle.unref?.()
26
+ return () => { clearTimeout(handle) }
27
+ },
28
+ interval(callback, delay) {
29
+ const handle = setInterval(callback, delay)
30
+ handle.unref?.()
31
+ return () => { clearInterval(handle) }
32
+ },
33
+ }