dsh-ssh-hub 0.0.0-stage → 0.2.0

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 (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +271 -2
  3. package/cordis.patch.yml +16 -0
  4. package/icon.svg +3 -0
  5. package/lib/client.js +13975 -0
  6. package/lib/index.js +6908 -0
  7. package/lib/types/activity/history.d.ts +50 -0
  8. package/lib/types/alerting/notify.d.ts +89 -0
  9. package/lib/types/alerting/prompt-summary.d.ts +28 -0
  10. package/lib/types/alerting/rules.d.ts +135 -0
  11. package/lib/types/alerting/tools.d.ts +30 -0
  12. package/lib/types/audit/audit-log.d.ts +84 -0
  13. package/lib/types/audit/recorder.d.ts +50 -0
  14. package/lib/types/client/api.d.ts +222 -0
  15. package/lib/types/client/index.d.ts +45 -0
  16. package/lib/types/client/locales.d.ts +319 -0
  17. package/lib/types/client/native-panel.d.ts +70 -0
  18. package/lib/types/client/panel/ClusterTab.d.ts +7 -0
  19. package/lib/types/client/panel/DeployTab.d.ts +10 -0
  20. package/lib/types/client/panel/FleetTab.d.ts +10 -0
  21. package/lib/types/client/panel/HostFormDialog.d.ts +12 -0
  22. package/lib/types/client/panel/HostsTab.d.ts +25 -0
  23. package/lib/types/client/panel/LogsTab.d.ts +10 -0
  24. package/lib/types/client/panel/SshPanel.d.ts +14 -0
  25. package/lib/types/client/panel/TerminalTab.d.ts +27 -0
  26. package/lib/types/client/panel/TransferTab.d.ts +7 -0
  27. package/lib/types/client/panel/TunnelEditDialog.d.ts +15 -0
  28. package/lib/types/client/panel/TunnelsTab.d.ts +27 -0
  29. package/lib/types/client/panel/controller.d.ts +253 -0
  30. package/lib/types/client/panel/helpers.d.ts +45 -0
  31. package/lib/types/client/panel/tabs.d.ts +62 -0
  32. package/lib/types/client/panel/xterm.css.d.ts +2 -0
  33. package/lib/types/client/settings-binding.d.ts +71 -0
  34. package/lib/types/deploy/orchestrator.d.ts +158 -0
  35. package/lib/types/deploy/tools.d.ts +14 -0
  36. package/lib/types/dsh-home.d.ts +16 -0
  37. package/lib/types/engine/cluster.d.ts +19 -0
  38. package/lib/types/engine/connection-pool.d.ts +183 -0
  39. package/lib/types/engine/proxy-command.d.ts +36 -0
  40. package/lib/types/engine/pty.d.ts +32 -0
  41. package/lib/types/engine/sftp.d.ts +20 -0
  42. package/lib/types/engine/terminal-sessions.d.ts +67 -0
  43. package/lib/types/engine/tunnel-discovery.d.ts +89 -0
  44. package/lib/types/engine/tunnel-remarks.d.ts +49 -0
  45. package/lib/types/engine/tunnel.d.ts +76 -0
  46. package/lib/types/engine.d.ts +103 -0
  47. package/lib/types/http.d.ts +59 -0
  48. package/lib/types/index.d.ts +128 -0
  49. package/lib/types/inspect/checks.d.ts +118 -0
  50. package/lib/types/inspect/inspection.d.ts +111 -0
  51. package/lib/types/inspect/tools.d.ts +50 -0
  52. package/lib/types/logs/search.d.ts +131 -0
  53. package/lib/types/logs/tools.d.ts +6 -0
  54. package/lib/types/loopback.d.ts +64 -0
  55. package/lib/types/monitor/loop.d.ts +133 -0
  56. package/lib/types/monitor/metrics.d.ts +151 -0
  57. package/lib/types/mount-once.d.ts +55 -0
  58. package/lib/types/protocol.d.ts +524 -0
  59. package/lib/types/routes.d.ts +82 -0
  60. package/lib/types/security/known-hosts.d.ts +153 -0
  61. package/lib/types/security/master-secret.d.ts +157 -0
  62. package/lib/types/security/redact.d.ts +44 -0
  63. package/lib/types/security/secrets.d.ts +70 -0
  64. package/lib/types/ssh-config.d.ts +42 -0
  65. package/lib/types/store.d.ts +183 -0
  66. package/lib/types/tool-surface.d.ts +72 -0
  67. package/lib/types/tools.d.ts +56 -0
  68. package/locale/en.json +6 -0
  69. package/locale/zh.json +6 -0
  70. package/package.json +126 -6
  71. package/src/activity/history.ts +117 -0
  72. package/src/alerting/notify.ts +212 -0
  73. package/src/alerting/prompt-summary.ts +71 -0
  74. package/src/alerting/rules.ts +281 -0
  75. package/src/alerting/tools.ts +263 -0
  76. package/src/audit/audit-log.ts +199 -0
  77. package/src/audit/recorder.ts +73 -0
  78. package/src/client/api.ts +782 -0
  79. package/src/client/css-modules.d.ts +5 -0
  80. package/src/client/index.ts +150 -0
  81. package/src/client/locales.ts +654 -0
  82. package/src/client/native-panel.tsx +141 -0
  83. package/src/client/panel/ClusterTab.tsx +141 -0
  84. package/src/client/panel/DeployTab.tsx +314 -0
  85. package/src/client/panel/FleetTab.tsx +494 -0
  86. package/src/client/panel/HostFormDialog.tsx +289 -0
  87. package/src/client/panel/HostsTab.tsx +395 -0
  88. package/src/client/panel/LogsTab.tsx +208 -0
  89. package/src/client/panel/SshPanel.tsx +105 -0
  90. package/src/client/panel/TerminalTab.tsx +550 -0
  91. package/src/client/panel/TransferTab.tsx +238 -0
  92. package/src/client/panel/TunnelEditDialog.tsx +174 -0
  93. package/src/client/panel/TunnelsTab.tsx +328 -0
  94. package/src/client/panel/controller.ts +507 -0
  95. package/src/client/panel/helpers.ts +84 -0
  96. package/src/client/panel/panel.module.css +1734 -0
  97. package/src/client/panel/tabs.ts +52 -0
  98. package/src/client/panel/xterm.css.ts +2 -0
  99. package/src/client/settings-binding.ts +184 -0
  100. package/src/deploy/orchestrator.ts +326 -0
  101. package/src/deploy/tools.ts +225 -0
  102. package/src/dsh-home.ts +42 -0
  103. package/src/engine/cluster.ts +60 -0
  104. package/src/engine/connection-pool.ts +721 -0
  105. package/src/engine/proxy-command.ts +248 -0
  106. package/src/engine/pty.ts +78 -0
  107. package/src/engine/sftp.ts +229 -0
  108. package/src/engine/terminal-sessions.ts +280 -0
  109. package/src/engine/tunnel-discovery.ts +353 -0
  110. package/src/engine/tunnel-remarks.ts +120 -0
  111. package/src/engine/tunnel.ts +300 -0
  112. package/src/engine.ts +195 -0
  113. package/src/http.ts +127 -0
  114. package/src/index.ts +690 -0
  115. package/src/inspect/checks.ts +251 -0
  116. package/src/inspect/inspection.ts +321 -0
  117. package/src/inspect/tools.ts +366 -0
  118. package/src/logs/search.ts +251 -0
  119. package/src/logs/tools.ts +160 -0
  120. package/src/loopback.ts +119 -0
  121. package/src/monitor/loop.ts +265 -0
  122. package/src/monitor/metrics.ts +333 -0
  123. package/src/mount-once.ts +142 -0
  124. package/src/protocol.ts +534 -0
  125. package/src/routes.ts +998 -0
  126. package/src/security/known-hosts.ts +342 -0
  127. package/src/security/master-secret.ts +334 -0
  128. package/src/security/redact.ts +119 -0
  129. package/src/security/secrets.ts +152 -0
  130. package/src/ssh-config.ts +182 -0
  131. package/src/store.ts +757 -0
  132. package/src/tool-surface.ts +96 -0
  133. package/src/tools.ts +550 -0
@@ -0,0 +1,225 @@
1
+ /**
2
+ * Agent tool for deployment orchestration.
3
+ *
4
+ * The tool is deliberately plan-driven: the agent supplies the steps, the
5
+ * health probe and the rollback commands, and the orchestrator runs them in
6
+ * batches. A tool that invented a deployment shape would be a tool that
7
+ * deployed the wrong thing confidently.
8
+ */
9
+
10
+ import { defineTool } from '@deepseek-ai/dsh-tools'
11
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
12
+ import type { SshEngine } from '../engine.ts'
13
+ import { deploy, renderDeploy, type DeployPlan } from './orchestrator.ts'
14
+ import type { AuditRecorder } from '../audit/recorder.ts'
15
+
16
+ /** One text content block (the only render shape these tools emit). */
17
+ function text(value: string): ContentBlock[] {
18
+ return [{ type: 'text', text: value }]
19
+ }
20
+
21
+ /** The deployment tool. */
22
+ export function hubDeployTool(engine: SshEngine, audit?: AuditRecorder) {
23
+ return defineTool({
24
+ name: 'hub_deploy',
25
+ description: 'Roll a change out to selected SSH hosts in batches, run a health probe after each batch, and roll the batch back when the probe fails. Every step needs a rollbackCommand to be undoable; without one the tool reports honestly that the host cannot be rolled back instead of pretending it is fine. Use ssh_cluster for a one-off command across hosts; use hub_deploy when the change must be verified and undone on failure.',
26
+ parameters: {
27
+ planId: { type: 'string', required: true, description: 'A short name for this deployment, e.g. release-2026-11-16.' },
28
+ steps: {
29
+ type: 'array',
30
+ required: true,
31
+ items: {
32
+ type: 'object',
33
+ additionalProperties: false,
34
+ properties: {
35
+ name: { type: 'string', required: true },
36
+ command: { type: 'string', required: true },
37
+ rollbackCommand: { type: 'string' },
38
+ },
39
+ },
40
+ description: 'The steps to run on each host, in order. Give each one a rollbackCommand so a failed host can be undone.',
41
+ },
42
+ healthCheckCommand: { type: 'string', description: 'The command that verifies the host came up healthy (exit code 0 = healthy). Omit to trust the steps alone.' },
43
+ healthCheckExpectExitCode: { type: 'integer', description: 'The exit code that means healthy (default 0).' },
44
+ healthCheckSettleMs: { type: 'integer', description: 'How long to wait before probing, so the service can start (default 0).' },
45
+ aliases: { type: 'array', items: { type: 'string' }, description: 'Host aliases to deploy to. Optional when environment or tags is given.' },
46
+ environment: { type: 'string', description: 'Deploy only to hosts with this environment label (exact match).' },
47
+ tags: { type: 'array', items: { type: 'string' }, description: 'Deploy only to hosts carrying ALL of these tags.' },
48
+ batchSize: { type: 'integer', description: 'How many hosts to deploy to at once (default 5).' },
49
+ timeoutMs: { type: 'integer', description: 'Per-command timeout in milliseconds (default 120000).' },
50
+ stopOnFailure: { type: 'boolean', description: 'Stop the rollout at the first failing batch (default true).' },
51
+ },
52
+ output: {
53
+ schema: {
54
+ type: 'object',
55
+ additionalProperties: false,
56
+ properties: {
57
+ ok: { type: 'boolean', required: true },
58
+ planId: { type: 'string', required: true },
59
+ targets: { type: 'array', items: { type: 'string' }, required: true },
60
+ skipped: { type: 'array', items: { type: 'string' }, required: true },
61
+ batches: {
62
+ type: 'array',
63
+ required: true,
64
+ items: {
65
+ type: 'object',
66
+ additionalProperties: false,
67
+ properties: {
68
+ index: { type: 'integer', required: true },
69
+ aliases: { type: 'array', items: { type: 'string' }, required: true },
70
+ ok: { type: 'boolean', required: true },
71
+ },
72
+ },
73
+ },
74
+ durationMs: { type: 'integer', required: true },
75
+ error: { type: 'string' },
76
+ },
77
+ },
78
+ render: (_args, value: { ok: boolean; planId: string; targets: string[]; skipped: string[]; batches: Array<{ index: number; aliases: string[]; ok: boolean }>; durationMs: number; error?: string }) => {
79
+ const lines = [
80
+ `部署 ${value.planId}:${value.ok ? '成功' : '失败'}(${value.targets.length} 台,耗时 ${value.durationMs}ms)`,
81
+ ]
82
+ if (value.error !== undefined) lines.push(`失败原因:${value.error}`)
83
+ for (const batch of value.batches) {
84
+ lines.push(`批次 ${batch.index}:${batch.aliases.join(', ')} — ${batch.ok ? '正常' : '异常'}`)
85
+ }
86
+ if (value.skipped.length > 0) {
87
+ lines.push(`未部署(因前序批次失败而跳过):${value.skipped.join(', ')}`)
88
+ }
89
+ return text(lines.join('\n'))
90
+ },
91
+ },
92
+ async execute(args) {
93
+ const targets = resolveDeployTargets(engine, toStringArray(args.aliases), args.environment, toStringArray(args.tags))
94
+ const steps = toSteps(args.steps)
95
+ if (steps.length === 0) {
96
+ throw new Error('hub_deploy requires at least one step')
97
+ }
98
+ const plan: DeployPlan = {
99
+ id: args.planId,
100
+ steps,
101
+ batchSize: args.batchSize ?? 5,
102
+ timeoutMs: args.timeoutMs ?? 120_000,
103
+ ...(args.healthCheckCommand !== undefined
104
+ ? {
105
+ healthCheck: {
106
+ command: args.healthCheckCommand,
107
+ ...(args.healthCheckExpectExitCode !== undefined ? { expectExitCode: args.healthCheckExpectExitCode } : {}),
108
+ ...(args.healthCheckSettleMs !== undefined ? { settleMs: args.healthCheckSettleMs } : {}),
109
+ },
110
+ }
111
+ : {}),
112
+ ...(args.stopOnFailure !== undefined ? { stopOnFailure: args.stopOnFailure } : {}),
113
+ }
114
+ const result = await deploy(engine, plan, targets)
115
+ audit?.record('deploy', {
116
+ ok: result.ok,
117
+ targets: result.targets,
118
+ summary: `deploy ${result.planId}: ${result.ok ? 'ok' : 'failed'}`,
119
+ detail: {
120
+ batches: result.batches.length,
121
+ failedHosts: result.batches.flatMap(batch => batch.results.filter(host => !host.ok).map(host => host.alias)),
122
+ rolledBack: result.batches.flatMap(batch => batch.results.filter(host => host.rolledBack === true).map(host => host.alias)),
123
+ skipped: result.skipped,
124
+ },
125
+ })
126
+ return {
127
+ ok: result.ok,
128
+ planId: result.planId,
129
+ targets: result.targets,
130
+ skipped: result.skipped,
131
+ batches: result.batches.map(batch => ({
132
+ index: batch.index,
133
+ aliases: batch.aliases,
134
+ ok: batch.ok,
135
+ })),
136
+ durationMs: result.durationMs,
137
+ ...(result.error !== undefined ? { error: result.error } : {}),
138
+ }
139
+ },
140
+ })
141
+ }
142
+
143
+ /**
144
+ * Resolve the hosts to deploy to.
145
+ *
146
+ * An empty selector is refused: deploying to an unspecified set of hosts
147
+ * is the most expensive possible mistake.
148
+ *
149
+ * @param engine - the SSH engine.
150
+ * @param aliases - explicit aliases.
151
+ * @param environment - an environment label.
152
+ * @param tags - tags that must all be present.
153
+ * @returns the selected aliases.
154
+ */
155
+ function resolveDeployTargets(
156
+ engine: SshEngine,
157
+ aliases?: string[],
158
+ environment?: string,
159
+ tags?: string[],
160
+ ): string[] {
161
+ const hasAlias = aliases !== undefined && aliases.length > 0
162
+ const hasEnvironment = environment !== undefined && environment !== ''
163
+ const hasTags = tags !== undefined && tags.length > 0
164
+ if (!hasAlias && !hasEnvironment && !hasTags) {
165
+ throw new Error('hub_deploy requires aliases, environment, or tags to limit the target set')
166
+ }
167
+ let hosts = engine.store.list()
168
+ if (hasAlias) {
169
+ const wanted = new Set(aliases as string[])
170
+ hosts = hosts.filter(host => wanted.has(host.alias))
171
+ }
172
+ if (hasEnvironment) {
173
+ hosts = hosts.filter(host => host.environment === environment)
174
+ }
175
+ if (hasTags) {
176
+ const wanted = tags as string[]
177
+ hosts = hosts.filter(host => wanted.every(tag => host.tags.includes(tag)))
178
+ }
179
+ return hosts.map(host => host.alias)
180
+ }
181
+
182
+ // `renderDeploy` is exported for callers that want the full report text
183
+ // (the panel uses it); the tool renders a compact summary.
184
+ export { renderDeploy }
185
+
186
+ /**
187
+ * Narrow a tool argument to a string array.
188
+ *
189
+ * @param value - the raw argument.
190
+ * @returns the strings, or undefined when the value is absent or unusable.
191
+ */
192
+ function toStringArray(value: unknown): string[] | undefined {
193
+ if (!Array.isArray(value)) return undefined
194
+ const strings = value.filter((item): item is string => typeof item === 'string' && item.trim() !== '')
195
+ return strings.length === 0 ? undefined : strings
196
+ }
197
+
198
+ /**
199
+ * Narrow the steps argument to the deploy-step shape.
200
+ *
201
+ * A malformed step is dropped rather than passed on: a step without a
202
+ * command cannot run, and running a half-specified step is worse than
203
+ * reporting that the plan is malformed.
204
+ *
205
+ * @param value - the raw argument.
206
+ * @returns the usable steps.
207
+ */
208
+ function toSteps(value: unknown): Array<{ name: string; command: string; rollbackCommand?: string }> {
209
+ if (!Array.isArray(value)) return []
210
+ const steps: Array<{ name: string; command: string; rollbackCommand?: string }> = []
211
+ for (const item of value) {
212
+ if (typeof item !== 'object' || item === null) continue
213
+ const record = item as Record<string, unknown>
214
+ const command = record['command']
215
+ if (typeof command !== 'string' || command.trim() === '') continue
216
+ const name = record['name']
217
+ const rollback = record['rollbackCommand']
218
+ steps.push({
219
+ name: typeof name === 'string' && name !== '' ? name : command.slice(0, 40),
220
+ command,
221
+ ...(typeof rollback === 'string' && rollback !== '' ? { rollbackCommand: rollback } : {}),
222
+ })
223
+ }
224
+ return steps
225
+ }
@@ -0,0 +1,42 @@
1
+ // Generated by scripts/sync-shared.mjs from shared/host/dsh-home.ts. Do not edit this copy; edit the shared source and run "node scripts/sync-shared.mjs".
2
+ /**
3
+ * DSH_HOME resolution shared by the plugin family's Host halves: the
4
+ * environment override wins, the platform home fallback follows. Mirrors
5
+ * what dsh-pet and dsh-liangshen each used to implement locally.
6
+ */
7
+
8
+ import { homedir } from 'node:os'
9
+ import { isAbsolute, join } from 'node:path'
10
+ import { isAbsolute as posixIsAbsolute, join as posixJoin } from 'node:path/posix'
11
+
12
+ /** Expand a leading ~ (or ~user) in a path, platform-style. */
13
+ export function expandHome(path: string, home: string = homedir()): string {
14
+ const isPosix = home.startsWith('/')
15
+ const j = isPosix ? posixJoin : join
16
+ if (path === '~') return home
17
+ if (path.startsWith('~/') || path.startsWith('~\\')) return j(home, path.slice(2))
18
+ return path
19
+ }
20
+
21
+ /**
22
+ * Resolve the DSH home directory.
23
+ * @param env - process environment to read DSH_HOME from.
24
+ * @param home - platform home directory fallback (test seam).
25
+ * @returns the absolute DSH home path.
26
+ */
27
+ export function resolveDshHome(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
28
+ const isPosix = home.startsWith('/')
29
+ const j = isPosix ? posixJoin : join
30
+ const isAbs = isPosix ? posixIsAbsolute : isAbsolute
31
+ const raw = env.DSH_HOME
32
+ if (raw !== undefined && raw.trim() !== '') {
33
+ const expanded = expandHome(raw.trim(), home)
34
+ return isAbs(expanded) ? expanded : j(process.cwd(), expanded)
35
+ }
36
+ return j(home, '.dsh')
37
+ }
38
+
39
+ /** Resolve the DSH home directory from the live environment. */
40
+ export function dshHome(): string {
41
+ return resolveDshHome()
42
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Cluster execution: run one command concurrently across selected hosts; the
3
+ * caller must provide at least one non-empty aliases / environment / tags filter.
4
+ */
5
+
6
+ import type { ClusterResult } from '../protocol.ts'
7
+ import { execCommand, type PoolEngine } from './connection-pool.ts'
8
+
9
+ interface ClusterOptions {
10
+ command: string
11
+ aliases?: string[]
12
+ environment?: string
13
+ tags?: string[]
14
+ timeoutMs?: number
15
+ maxWorkers?: number
16
+ /** Caller cancellation, forwarded to every host's command. */
17
+ signal?: AbortSignal
18
+ }
19
+
20
+ /** Run one command against many hosts concurrently. */
21
+ export async function cluster(engine: PoolEngine, options: ClusterOptions): Promise<ClusterResult[]> {
22
+ const hasAliases = Array.isArray(options.aliases) && options.aliases.some(alias => typeof alias === 'string' && alias.trim() !== '')
23
+ const hasEnvironment = typeof options.environment === 'string' && options.environment.trim() !== ''
24
+ const hasTags = Array.isArray(options.tags) && options.tags.some(tag => typeof tag === 'string' && tag.trim() !== '')
25
+ if (!hasAliases && !hasEnvironment && !hasTags) {
26
+ throw new Error('ssh_cluster requires aliases, environment, or tags to limit the target set')
27
+ }
28
+
29
+ let targets = engine.store.list()
30
+ if (options.aliases !== undefined && options.aliases.length > 0) {
31
+ targets = targets.filter(entry => options.aliases!.includes(entry.alias))
32
+ }
33
+ if (options.environment !== undefined && options.environment !== '') {
34
+ targets = targets.filter(entry => entry.environment === options.environment)
35
+ }
36
+ if (options.tags !== undefined && options.tags.length > 0) {
37
+ // ALL semantics (matches the ssh_cluster tool description).
38
+ targets = targets.filter(entry => options.tags!.every(tag => entry.tags.includes(tag)))
39
+ }
40
+ if (targets.length === 0) return []
41
+ if (options.maxWorkers !== undefined && (!Number.isInteger(options.maxWorkers) || options.maxWorkers < 1)) {
42
+ throw new Error('maxWorkers must be a positive integer')
43
+ }
44
+ const workers = Math.min(engine.opts.defaultMaxWorkers, options.maxWorkers ?? engine.opts.defaultMaxWorkers, targets.length)
45
+ const results: ClusterResult[] = []
46
+ const queue = [...targets]
47
+ const run = async (): Promise<void> => {
48
+ while (queue.length > 0) {
49
+ const entry = queue.shift()!
50
+ try {
51
+ const result = await execCommand(engine, entry.alias, options.command, options.timeoutMs, options.signal)
52
+ results.push({ alias: entry.alias, ok: result.success, exitCode: result.exitCode, timedOut: result.timedOut, stdout: result.stdout, stderr: result.stderr, durationMs: result.durationMs })
53
+ } catch (error) {
54
+ results.push({ alias: entry.alias, ok: false, error: error instanceof Error ? error.message : String(error) })
55
+ }
56
+ }
57
+ }
58
+ await Promise.all(Array.from({ length: workers }, () => run()))
59
+ return results
60
+ }