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

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 (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +85 -2
  4. package/README.zh.md +86 -0
  5. package/cordis.patch.yml +15 -0
  6. package/icon.svg +5 -0
  7. package/lib/client.js +4429 -0
  8. package/lib/index.js +6100 -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 +445 -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 +143 -0
  40. package/lib/types/core/task-record.d.ts +63 -0
  41. package/lib/types/core/workspace.d.ts +74 -0
  42. package/lib/types/host/board.d.ts +71 -0
  43. package/lib/types/host/engine.d.ts +418 -0
  44. package/lib/types/host/extension.d.ts +59 -0
  45. package/lib/types/host/logs.d.ts +135 -0
  46. package/lib/types/host/payload.d.ts +75 -0
  47. package/lib/types/host/prompt.d.ts +44 -0
  48. package/lib/types/host/queue.d.ts +53 -0
  49. package/lib/types/host/remote.d.ts +120 -0
  50. package/lib/types/host/settings.d.ts +149 -0
  51. package/lib/types/host/timers.d.ts +20 -0
  52. package/lib/types/host/tools.d.ts +15 -0
  53. package/lib/types/host/workspace/errors.d.ts +29 -0
  54. package/lib/types/host/workspace/git.d.ts +108 -0
  55. package/lib/types/host/workspace/in-place.d.ts +36 -0
  56. package/lib/types/host/workspace/index.d.ts +28 -0
  57. package/lib/types/host/workspace/layout.d.ts +62 -0
  58. package/lib/types/host/workspace/local-git.d.ts +72 -0
  59. package/lib/types/host/workspace/remote-git.d.ts +111 -0
  60. package/lib/types/host/workspace/remote.d.ts +85 -0
  61. package/lib/types/host/workspace/types.d.ts +28 -0
  62. package/lib/types/host/workspace-seam.d.ts +100 -0
  63. package/lib/types/index.d.ts +97 -0
  64. package/lib/types/mount-once.d.ts +55 -0
  65. package/locale/en.json +6 -0
  66. package/locale/zh.json +6 -0
  67. package/package.json +89 -3
  68. package/src/client/PluginSettingsCard.tsx +838 -0
  69. package/src/client/RangeBubble.tsx +164 -0
  70. package/src/client/SegmentGroup.tsx +93 -0
  71. package/src/client/css-modules.d.ts +5 -0
  72. package/src/client/index.ts +195 -0
  73. package/src/client/locales.ts +257 -0
  74. package/src/client/seat-props.ts +58 -0
  75. package/src/client/settings-card.module.css +821 -0
  76. package/src/client/settings-entry-form.ts +141 -0
  77. package/src/client/settings-form.ts +529 -0
  78. package/src/client/ssh/card-decoration.tsx +55 -0
  79. package/src/client/ssh/compose-section.tsx +147 -0
  80. package/src/client/ssh/detail-section.tsx +345 -0
  81. package/src/client/ssh/extension.ts +271 -0
  82. package/src/client/ssh/log-buffer.ts +224 -0
  83. package/src/client/ssh/log-view.tsx +149 -0
  84. package/src/client/ssh/model.ts +299 -0
  85. package/src/client/ssh/settings-section.tsx +401 -0
  86. package/src/client/ssh/summary.ts +388 -0
  87. package/src/client/ssh/target-form.tsx +380 -0
  88. package/src/client/ssh.module.css +617 -0
  89. package/src/core/action.ts +270 -0
  90. package/src/core/adapters/claude.ts +64 -0
  91. package/src/core/adapters/codex.ts +83 -0
  92. package/src/core/adapters/custom.ts +88 -0
  93. package/src/core/adapters/dsh.ts +87 -0
  94. package/src/core/adapters/index.ts +74 -0
  95. package/src/core/adapters/types.ts +95 -0
  96. package/src/core/contract.ts +510 -0
  97. package/src/core/launcher-script.ts +313 -0
  98. package/src/core/launcher.ts +283 -0
  99. package/src/core/ledger.ts +372 -0
  100. package/src/core/shell.ts +77 -0
  101. package/src/core/target.ts +413 -0
  102. package/src/core/task-record.ts +65 -0
  103. package/src/core/workspace.ts +78 -0
  104. package/src/host/board.ts +103 -0
  105. package/src/host/engine.ts +1602 -0
  106. package/src/host/extension.ts +304 -0
  107. package/src/host/logs.ts +297 -0
  108. package/src/host/payload.ts +134 -0
  109. package/src/host/prompt.ts +89 -0
  110. package/src/host/queue.ts +73 -0
  111. package/src/host/remote.ts +328 -0
  112. package/src/host/settings.ts +294 -0
  113. package/src/host/timers.ts +33 -0
  114. package/src/host/tools.ts +259 -0
  115. package/src/host/workspace/errors.ts +43 -0
  116. package/src/host/workspace/git.ts +305 -0
  117. package/src/host/workspace/in-place.ts +58 -0
  118. package/src/host/workspace/index.ts +37 -0
  119. package/src/host/workspace/layout.ts +122 -0
  120. package/src/host/workspace/local-git.ts +164 -0
  121. package/src/host/workspace/remote-git.ts +244 -0
  122. package/src/host/workspace/remote.ts +181 -0
  123. package/src/host/workspace/types.ts +34 -0
  124. package/src/host/workspace-seam.ts +132 -0
  125. package/src/index.ts +243 -0
  126. package/src/mount-once.ts +142 -0
@@ -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
+ }
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The three model-visible tools this extension contributes.
3
+ *
4
+ * They live with the provider — the board's own agent-tools module never learns
5
+ * SSH vocabulary — and they register through the extension capability face, so
6
+ * they follow the same board-enabled x extension-enabled gate as every other
7
+ * provider surface: switching either off withdraws all three.
8
+ *
9
+ * What a tool returns is a projection, never a host entry: an alias, an address,
10
+ * a port and a user are what a card needs to name its host, and a credential is
11
+ * not part of this surface at all (the `dshSsh` face carries none, and the
12
+ * projection here would drop one that appeared anyway).
13
+ *
14
+ * @module dsh-task-board-ssh/host/tools
15
+ */
16
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
17
+ import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'
18
+ import { TASK_BOARD_MESSAGE_MAX_LENGTH, type DshSshHost } from '../core/contract.ts'
19
+ import { SSH_AGENT_KINDS, parseSshTarget, type SshExecutionMode } from '../core/target.ts'
20
+ import type { SshRunEngine } from './engine.ts'
21
+
22
+ /** Tool names, in registration order. */
23
+ export const SSH_TOOL_NAMES = ['task_board_ssh_target', 'task_board_ssh_status', 'task_board_ssh_follow_up'] as const
24
+
25
+ /** One tool name. */
26
+ export type SshToolName = (typeof SSH_TOOL_NAMES)[number]
27
+
28
+ type Json = null | boolean | number | string | Json[] | { [key: string]: Json }
29
+
30
+ /** Model-facing JSON rendering shared by the three tools. */
31
+ function renderJson(_args: unknown, value: unknown): ContentBlock[] {
32
+ return [{ type: 'text' as const, text: JSON.stringify(value, null, 2) }]
33
+ }
34
+
35
+ /** Mark an already JSON-safe projection as the tool's canonical value. */
36
+ function json(value: unknown): Json {
37
+ return value as Json
38
+ }
39
+
40
+ /** A domain refusal the model is expected to read and act on. */
41
+ function refused(code: string, message: string): Json {
42
+ return json({ ok: false, code, message })
43
+ }
44
+
45
+ /** The message of anything thrown by a caller below. */
46
+ function messageOf(error: unknown): string {
47
+ return error instanceof Error ? error.message : String(error)
48
+ }
49
+
50
+ /**
51
+ * Project one host as a tool may report it.
52
+ *
53
+ * Written field by field on purpose: a deployment's host summary may grow a
54
+ * member tomorrow, and the model-facing surface must not grow it too by
55
+ * accident.
56
+ * @param host - the secret-free host the `dshSsh` face reports.
57
+ * @returns the projection.
58
+ */
59
+ function hostView(host: DshSshHost): Record<string, unknown> {
60
+ return {
61
+ alias: host.alias,
62
+ host: host.host,
63
+ port: host.port,
64
+ user: host.user,
65
+ tags: [...host.tags],
66
+ proxyJump: [...host.proxyJump],
67
+ forwardAgent: host.forwardAgent,
68
+ keyReady: host.keyReady,
69
+ ...(host.description === undefined ? {} : { description: host.description }),
70
+ ...(host.environment === undefined ? {} : { environment: host.environment }),
71
+ ...(host.location === undefined ? {} : { location: host.location }),
72
+ }
73
+ }
74
+
75
+ /** Every host this deployment can pin a card to, in the same projection. */
76
+ function hostViews(engine: SshRunEngine): Record<string, unknown>[] {
77
+ return engine.hosts().slice(0, 50).map(hostView)
78
+ }
79
+
80
+ /** Read one string parameter, or undefined when it is absent or blank. */
81
+ function text(value: unknown): string | undefined {
82
+ if (typeof value !== 'string') return undefined
83
+ const trimmed = value.trim()
84
+ return trimmed === '' ? undefined : trimmed
85
+ }
86
+
87
+ /** Read one number parameter, or undefined when it is absent or unusable. */
88
+ function count(value: unknown): number | undefined {
89
+ return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined
90
+ }
91
+
92
+ /**
93
+ * Assemble a target out of the flat parameters a tool call carries.
94
+ * @param args - the tool arguments.
95
+ * @returns the candidate target, still to be validated by the parser.
96
+ */
97
+ function targetFromArgs(args: Record<string, unknown>): unknown {
98
+ const host = text(args.host) ?? ''
99
+ const mode = args.mode === undefined ? 'direct' : args.mode
100
+ const agentKind = args.agent === undefined ? 'dsh' : args.agent
101
+ const agentCommand = text(args.agentCommand)
102
+ const agentResumeCommand = text(args.agentResumeCommand)
103
+ const workspaceKind = args.workspaceKind === undefined ? 'in-place' : args.workspaceKind
104
+ let workspace: unknown
105
+ if (workspaceKind === 'git') {
106
+ workspace = text(args.repositoryUrl) !== undefined
107
+ ? {
108
+ kind: 'git',
109
+ source: {
110
+ kind: 'url',
111
+ url: text(args.repositoryUrl),
112
+ ...(text(args.repositoryBase) === undefined ? {} : { base: text(args.repositoryBase) }),
113
+ },
114
+ }
115
+ : { kind: 'git', source: { kind: 'workspace', workspaceId: text(args.workspaceId) ?? '' } }
116
+ } else if (workspaceKind === 'in-place') {
117
+ workspace = { kind: 'in-place', path: text(args.workspacePath) ?? '' }
118
+ } else {
119
+ workspace = { kind: workspaceKind }
120
+ }
121
+ const agent: Record<string, unknown> = { kind: agentKind }
122
+ if (agentCommand !== undefined) agent.command = agentCommand
123
+ if (agentResumeCommand !== undefined) agent.resumeCommand = agentResumeCommand
124
+ return {
125
+ mode,
126
+ host,
127
+ agent,
128
+ workspace,
129
+ }
130
+ }
131
+
132
+ /** The target tool: read or pin where one card runs. */
133
+ function buildTargetTool(engine: SshRunEngine): ToolDefinition {
134
+ return defineTool({
135
+ name: 'task_board_ssh_target',
136
+ description: 'Read or pin the SSH execution target of one task board card: whether it runs remotely at all (direct) or through a local session that drives the host (proxy), which dsh-ssh host alias it addresses, which agent CLI runs there and where the work happens. Pinning a target makes the card run on that host the next time it is started; a direct card gets no local session at all. Read the current pin and the available hosts first when the user has not named an alias.',
137
+ parameters: {
138
+ action: { type: 'string', required: true, enum: ['read', 'set'], description: 'read reports the current pin and the hosts available; set stores a new pin.' },
139
+ taskId: { type: 'string', required: true, description: 'Card to read or retarget.' },
140
+ mode: { type: 'string', enum: ['direct', 'proxy'], description: 'direct starts a headless agent on the host and keeps no local session; proxy runs a local session told to drive the host through the ssh_* tools. Defaults to direct.' },
141
+ host: { type: 'string', description: 'dsh-ssh host alias the card addresses. Required by set.' },
142
+ agent: { type: 'string', enum: [...SSH_AGENT_KINDS], description: 'Agent CLI the remote run starts (default dsh).' },
143
+ workspaceKind: { type: 'string', enum: ['in-place', 'git'], description: 'in-place works in an existing remote directory; git creates a per-run worktree. Defaults to in-place.' },
144
+ workspacePath: { type: 'string', description: 'Absolute remote directory of an in-place target.' },
145
+ repositoryUrl: { type: 'string', description: 'Clone URL a git target prepares its worktree from, when the host can reach it.' },
146
+ repositoryBase: { type: 'string', description: 'Base branch that worktree starts from; the remote HEAD when absent.' },
147
+ workspaceId: { type: 'string', description: 'Local workspace id a git target runs from, when its repository is not reachable from the host.' },
148
+ agentCommand: { type: 'string', description: 'Start command template of a custom agent; must reference {prompt_file}.' },
149
+ agentResumeCommand: { type: 'string', description: 'Resume command template of a custom agent; without one a follow-up runs fresh.' },
150
+ },
151
+ output: { schema: { type: 'json' }, render: renderJson },
152
+ async execute(args) {
153
+ const taskId = text(args.taskId)
154
+ if (taskId === undefined) return refused('task-required', 'taskId is required')
155
+ const action = text(args.action) ?? 'read'
156
+ if (action === 'read') {
157
+ const target = engine.targetOf(taskId)
158
+ return json({ ok: true, target: target ?? null, hosts: hostViews(engine) })
159
+ }
160
+ if (action !== 'set') return refused('unknown-action', 'action must be read or set')
161
+ const parsed = parseSshTarget(targetFromArgs(args as Record<string, unknown>))
162
+ if (!parsed.ok) {
163
+ return json({ ok: false, code: 'invalid-target', issues: parsed.errors.map(issue => ({ path: issue.path, message: issue.message })) })
164
+ }
165
+ const reply = engine.setTarget(taskId, parsed.value)
166
+ if (!reply.ok) return refused(reply.code, reply.error)
167
+ return json({ ok: true, target: parsed.value, hosts: hostViews(engine) })
168
+ },
169
+ })
170
+ }
171
+
172
+ /** The status tool: one card's remote run, and optionally a page of its log. */
173
+ function buildStatusTool(engine: SshRunEngine): ToolDefinition {
174
+ return defineTool({
175
+ name: 'task_board_ssh_status',
176
+ description: 'Read the remote run state of one task board card: the phase of the run in flight (queued, running, succeeded, failed, cancelled, lost), its remote exit code, how many log bytes the host reported, the session it reported and the recent run history. Pass logOffset and logLimit to read one page of the run log by byte offset; the log is a file on the host, never part of the card, so page it instead of asking for everything.',
177
+ parameters: {
178
+ taskId: { type: 'string', required: true, description: 'Card whose remote run to inspect.' },
179
+ runId: { type: 'string', description: 'One specific run to read the log of; the active run when absent.' },
180
+ logOffset: { type: 'number', description: 'Byte offset the log page starts at (default 0).' },
181
+ logLimit: { type: 'number', description: 'Largest page to return, in bytes (default 65536, at most 131072).' },
182
+ },
183
+ output: { schema: { type: 'json' }, render: renderJson },
184
+ async execute(args) {
185
+ const taskId = text(args.taskId)
186
+ if (taskId === undefined) return refused('task-required', 'taskId is required')
187
+ const status = engine.status(taskId)
188
+ const runId = text(args.runId)
189
+ const offset = count(args.logOffset)
190
+ const limit = count(args.logLimit)
191
+ if (runId === undefined && offset === undefined && limit === undefined) return json({ ok: true, status })
192
+ const page = await engine.readLog(taskId, {
193
+ ...(runId === undefined ? {} : { runId }),
194
+ ...(offset === undefined ? {} : { offset }),
195
+ ...(limit === undefined ? {} : { limit }),
196
+ })
197
+ if (!page.ok) return json({ ok: false, status, code: page.code, message: page.error })
198
+ return json({
199
+ ok: true,
200
+ status,
201
+ log: { runId: page.runId, offset: page.offset, nextOffset: page.nextOffset, bytes: page.bytes, eof: page.eof, text: page.text },
202
+ })
203
+ },
204
+ })
205
+ }
206
+
207
+ /** The follow-up tool: one more instruction for the card's remote session. */
208
+ function buildFollowUpTool(engine: SshRunEngine): ToolDefinition {
209
+ return defineTool({
210
+ name: 'task_board_ssh_follow_up',
211
+ description: 'Send one more instruction to the remote agent session of a task board card. On a card whose run is still going the instruction waits for that run to finish and then continues the same remote session; on a settled card it re-enters the card run with the earlier session resumed. An agent that cannot resume degrades to a fresh run that carries the previous summary, which the execution record says.',
212
+ parameters: {
213
+ taskId: { type: 'string', required: true, description: 'Card whose remote session receives the instruction.' },
214
+ text: { type: 'string', required: true, description: 'The instruction itself.' },
215
+ kind: { type: 'string', enum: ['follow-up', 'rework'], description: 'follow-up adds work; rework asks again for work the previous run got wrong. Defaults to follow-up.' },
216
+ },
217
+ output: { schema: { type: 'json' }, render: renderJson },
218
+ async execute(args) {
219
+ const taskId = text(args.taskId)
220
+ const rawText = typeof args.text === 'string' ? args.text : ''
221
+ const instruction = rawText.trim()
222
+ if (taskId === undefined) return refused('task-required', 'taskId is required')
223
+ if (instruction === '') return refused('text-required', 'text must be a non-blank instruction')
224
+ if (rawText.length > TASK_BOARD_MESSAGE_MAX_LENGTH) {
225
+ return refused('text-too-long', `text must be at most ${TASK_BOARD_MESSAGE_MAX_LENGTH} characters`)
226
+ }
227
+ const rawKind = args.kind
228
+ if (rawKind !== undefined && rawKind !== 'follow-up' && rawKind !== 'rework') {
229
+ return refused('invalid-kind', 'kind must be "follow-up" or "rework"')
230
+ }
231
+ const kind = rawKind ?? 'follow-up'
232
+ try {
233
+ const reply = await engine.instruct(taskId, instruction, kind)
234
+ if (!reply.ok) return refused(reply.code, reply.error)
235
+ return json({
236
+ ok: true,
237
+ taskId: reply.taskId,
238
+ ...(reply.runId === undefined ? {} : { runId: reply.runId }),
239
+ ...(reply.phase === undefined ? {} : { phase: reply.phase }),
240
+ message: reply.message ?? '',
241
+ })
242
+ } catch (error) {
243
+ return refused('follow-up-failed', messageOf(error))
244
+ }
245
+ },
246
+ })
247
+ }
248
+
249
+ /**
250
+ * Build every tool this extension registers.
251
+ * @param engine - the live run engine behind them.
252
+ * @returns the tool definitions, in registration order.
253
+ */
254
+ export function buildSshTools(engine: SshRunEngine): ToolDefinition[] {
255
+ return [buildTargetTool(engine), buildStatusTool(engine), buildFollowUpTool(engine)]
256
+ }
257
+
258
+ /** Re-exported for the specs: the modes a target may pin. */
259
+ export type { SshExecutionMode }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The one failure type the workspace strategies raise.
3
+ *
4
+ * Every failure a strategy throws is this class, so the run engine can record a
5
+ * workspace that could not be prepared as a run failure without matching on
6
+ * message text. Each message names what was attempted and the host, path or
7
+ * command it failed on, because it lands in a card where the user has no shell
8
+ * to look behind it.
9
+ *
10
+ * @module dsh-task-board-ssh/host/workspace/errors
11
+ */
12
+
13
+ /** Longest failure text one message carries, in characters. */
14
+ const DETAIL_LIMIT = 400
15
+
16
+ /** A workspace that cannot be prepared or collected. */
17
+ export class SshWorkspaceError extends Error {
18
+ /**
19
+ * @param message - what failed, in one sentence a person can act on.
20
+ * @param options - standard error options, used to keep the underlying failure.
21
+ */
22
+ constructor(message: string, options?: ErrorOptions) {
23
+ super(message, options)
24
+ this.name = 'SshWorkspaceError'
25
+ }
26
+ }
27
+
28
+ /**
29
+ * The one line worth quoting out of a command's failure text.
30
+ *
31
+ * A tool prints progress first and the diagnosis last, so the last non-empty
32
+ * line is the part a person needs; the whole output is bounded away because it
33
+ * would bury the sentence it is quoted in.
34
+ * @param text - captured stderr, stdout or an error message.
35
+ * @returns that line, or undefined when there is nothing to quote.
36
+ */
37
+ export function boundedLine(text: string | undefined): string | undefined {
38
+ if (text === undefined) return undefined
39
+ const lines = text.split('\n').map(line => line.trim()).filter(line => line !== '')
40
+ const last = lines.at(-1)
41
+ if (last === undefined) return undefined
42
+ return last.length <= DETAIL_LIMIT ? last : `${last.slice(0, DETAIL_LIMIT)}...`
43
+ }