dsh-ssh-pty 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-ssh-pty contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,81 @@
1
- # Temporary Holding Version
1
+ # dsh-ssh-pty
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DeepSeek Harness 插件:把**受控 SSH 终端**接进官方 `terminal_*` 工具链。
4
+
5
+ Agent 用 `terminal_open / terminal_send / terminal_read / terminal_signal / terminal_close` 驱动一条进程内 ssh2 PTY 会话(`terminal_open(type:'ssh', cwd:'<主机别名>')`),可以走进堡垒机菜单、跑 vim/top/less;**二次验证(2FA/OTP)与登录密码由用户亲自输入**,不经过模型上下文。
6
+
7
+ - 运行在 Host 侧;安装后自动提供 `ssh` 终端后端、`ssh_term_hosts` 工具和 loopback 人工接管页。
8
+ - 主机清单来自 `~/.ssh/config`(`Host` 别名;首值优先,`ProxyJump` 只解析、不自动级联)。
9
+ - 每个会话一条独立 ssh2 连接 + shell 通道(`xterm-256color`),不启动本地 `ssh.exe`。
10
+ - 视口用 `@xterm/headless` 渲染,`terminal_read` 返回的是**当前屏幕**(vim/top 友好),另有按行/字节封顶的滚动缓冲。
11
+
12
+ 要求:DeepSeek Harness `>= 0.2.2-rc.3`(`dsh.engines.dsh`),Node `>= 22`。
13
+
14
+ ## 安装
15
+
16
+ 本包是 DSH bundle(`package.json` 的 `dsh.bundle.patch` 指向 `cordis.patch.yml`)。在目标 harness 中任选其一:
17
+
18
+ 1. **Plugin Manager(推荐)**:Plugins → Add plugin → 选择本包目录(或已解包的 tarball 目录)→ 启用。
19
+ 2. **让 agent 装**:把本包目录交给 agent,执行
20
+ `plugin_manager action:"install_bundle" target:"<本包绝对路径>"`。
21
+ 3. **npm(发布后)**:`plugin_manager action:"install_bundle" target:"dsh-ssh-pty"`。
22
+
23
+ 新 bundle 可能通过 HMR 直接生效;如果 `terminal_*` 工具或 `/api/dsh-ssh-terminal/*` 路由没出现,**重启 DeepSeek Harness**(替换已安装包时同样必须重启:Node ESM 不会重新执行旧模块)。
24
+
25
+ > ⚠️ 本 bundle 会挂载一整套终端栈(`dsh-terminal` 注册表 + `dsh-terminal-panel` 侧边栏 + `dsh-tool-terminal` 六个工具 + 本后端),放在 `isolate:{terminals:true}` 组里。**如果目标 harness 已经启用了官方 experimental 终端 bundle,请不要再启用本 bundle**——两套同名 `terminal_*` 工具会冲突。
26
+
27
+ ## 用法
28
+
29
+ 1. `ssh_term_hosts` —— 列出 `~/.ssh/config` 里可用的别名(包含主机、端口、用户、密钥、ProxyJump)。
30
+ 2. `terminal_open({ type: "ssh", cwd: "<别名>" })` —— 打开交互式会话。别名取 `cwd` 最后一段(官方工具会对 `cwd` 做 `path.resolve`,插件只还原末段)。
31
+ 3. `terminal_send({ sessionId, text: "..." })` —— 发一行命令或按键(vim 里发 `i`、`:wq\r` 都行)。
32
+ 4. `terminal_read({ sessionId, offset, count })` —— 分页回看滚动缓冲(`offset` 从最新行往回数)。
33
+ 5. `terminal_signal({ sessionId, signal: "SIGINT" })` —— 仅支持 `SIGINT`(Ctrl-C) / `SIGTSTP`(Ctrl-Z)。
34
+ 6. `terminal_close({ sessionId })` —— 关闭会话。
35
+
36
+ 等待判定:`inferred_idle`(输出静默 `idleSilenceMs`,默认 3s)/ `timeout`(`sendTimeoutMs`,默认 30s)/ `session_exit`。**静默不代表前台命令已退出**。
37
+
38
+ ## 人工接管页
39
+
40
+ 浏览器打开 `<web origin>/api/dsh-ssh-terminal/ui`(仅 loopback;`takeoverEnabled` 关闭时不可用),得到自包含暗色终端:
41
+
42
+ - 会话列表(别名 / 主机 / 用户 / 状态)+ 下拉切换;
43
+ - WebSocket 每 150ms 推送整屏 + 光标位置,vim/top 等全屏程序可用;
44
+ - 点击视口直接打字:Enter/Backspace/Esc/方向键/PgUp/PgDn/F1-F12/Ctrl+字母 按终端转义序列发送;
45
+ - 快捷按钮 Ctrl+C / Ctrl+D / Ctrl+Z / Esc / Tab,`resize` 改 PTY 尺寸,「关闭会话」等同 `terminal_close`;
46
+ - **密码、2FA、菜单选择从这里直进 PTY,不经过模型。**
47
+
48
+ ## 认证与密钥
49
+
50
+ - 支持 `publickey`(自动读取 `IdentityFile`,含 `~` 展开)、`password`、`keyboard-interactive`、`agent`。
51
+ - `keyboard-interactive` 的每个 prompt 会以**提问卡片**(`userQuestions.ask`)交给用户;全部留空 = 放弃(`AUTH_SKIPPED`),最多 `maxKeyRetries` 次(默认 3)。
52
+ - 插件不缓存、不打印任何密码或验证码;agent 侧只应提醒用户去卡片/接管页输入,**不要把密码写进 `terminal_send`**。
53
+ - 已知边界:SSH 通道拿不到对端前台进程组,因此没有 `stdin_read` 判定;`SIGTERM/SIGKILL/SIGHUP` 无跨 SSH 语义,直接拒绝;不支持 ProxyJump 自动级联(菜单式堡垒机不需要)。
54
+
55
+ ## 配置
56
+
57
+ 在 Settings / 插件配置里改,`volatile` 热更新,无需重启:
58
+
59
+ | 键 | 默认 | 说明 |
60
+ | --- | --- | --- |
61
+ | `enabled` | true | 关闭后卸载工具、后端与指引 |
62
+ | `announceToAgent` | true | 向 system prompt 注入使用指引 + 接管页 URL |
63
+ | `takeoverEnabled` | true | 启用 loopback 人工接管页 |
64
+ | `sshConfigPath` | `''` | 覆盖 `~/.ssh/config` 路径;空 = 默认 |
65
+ | `connectTimeoutMs` | 30000 | TCP/握手超时 |
66
+ | `authTimeoutMs` | 120000 | 人工验证等待预算 |
67
+ | `cols` / `rows` | 120 / 40 | PTY 尺寸 |
68
+ | `sendTimeoutMs` | 30000 | 单次 `terminal_send` 上限 |
69
+ | `idleSilenceMs` | 3000 | 输出静默判定 |
70
+ | `warmupTimeoutMs` | 8000 | 首屏 banner 等待 |
71
+ | `maxScrollbackLines` / `maxScrollbackBytes` | 5000 / 2MB | 滚动缓冲封顶 |
72
+ | `maxReadBytes` | 262144 | `terminal_read` 单次字节上限 |
73
+ | `maxKeyRetries` | 3 | keyboard-interactive 重试上限 |
74
+
75
+ ## 开发
76
+
77
+ 源码在 `lib/`:`index.js`(入口:后端注册 / `ssh_term_hosts` / 指引)、`backend.js`(ssh2 连接与认证)、`ssh-session.js`(滚动缓冲 + headless 视口 + 发送生命周期)、`ssh-config.js`(`~/.ssh/config` 子集解析)、`takeover.js`(接管页路由 + WS)。
78
+
79
+ - `node --check lib/*.js` 做语法检查;`npm pack --dry-run` 核对发布文件清单。
80
+ - `test/sshd-fake.mjs 2277` 本地假堡垒机(2FA=123456,菜单 → 密码 → shell/vim);`test/runner-e2e.mjs` 把后端 + 接管页挂到独立 http 服务器(8977),用 `/__test/{spawn,send,read,sessions}` 驱动完整链路。
81
+ - 宿主内改代码对当前进程无效(Node ESM 缓存),重启后生效;`dsh-tools` 的工具层不随插件卸载清理,改工具逻辑后务必重启。
@@ -0,0 +1,20 @@
1
+ # Mounts the PTY stack (registry + sidebar panel + agent tools) and this SSH backend
2
+ # into one isolated group, mirroring @deepseek-ai/dsh-experimental-terminal-bundle.
3
+ # Bundles listed in the profile only contribute patches; the rows below do the mounting.
4
+ - insert:
5
+ - id: ssh-controlled-terminals
6
+ name: cordis:group
7
+ group: true
8
+ isolate:
9
+ terminals: true
10
+ config:
11
+ - id: ssh-terminal-registry
12
+ name: '@deepseek-ai/dsh-terminal'
13
+ - id: ssh-terminal-panel
14
+ name: '@deepseek-ai/dsh-terminal-panel'
15
+ config:
16
+ preferredShells: !!js "process.platform === 'win32' ? ['pwsh', 'powershell'] : []"
17
+ - id: ssh-tool-terminal
18
+ name: '@deepseek-ai/dsh-tool-terminal'
19
+ - id: ssh-terminal-backend
20
+ name: dsh-ssh-pty
package/icon.svg ADDED
@@ -0,0 +1,25 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512" role="img" aria-label="SSH controlled terminal">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#1e2430"/>
5
+ <stop offset="1" stop-color="#0f1319"/>
6
+ </linearGradient>
7
+ <linearGradient id="accent" x1="0" y1="0" x2="1" y2="1">
8
+ <stop offset="0" stop-color="#6ea8fe"/>
9
+ <stop offset="1" stop-color="#4d6bfe"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect x="16" y="16" width="480" height="480" rx="112" fill="url(#bg)"/>
13
+ <rect x="16" y="16" width="480" height="480" rx="112" fill="none" stroke="#2b3444" stroke-width="8"/>
14
+ <rect x="96" y="128" width="320" height="232" rx="28" fill="#141a23" stroke="#2b3444" stroke-width="8"/>
15
+ <circle cx="136" cy="164" r="10" fill="#ff6b6b"/>
16
+ <circle cx="168" cy="164" r="10" fill="#ffd166"/>
17
+ <circle cx="200" cy="164" r="10" fill="#4ade80"/>
18
+ <path d="M144 236 L192 276 L144 316" fill="none" stroke="url(#accent)" stroke-width="24" stroke-linecap="round" stroke-linejoin="round"/>
19
+ <rect x="228" y="300" width="92" height="20" rx="10" fill="#e8eefc"/>
20
+ <circle cx="368" cy="348" r="64" fill="#0f1319" stroke="url(#accent)" stroke-width="10"/>
21
+ <path d="M344 338 v-18 a24 24 0 0 1 48 0 v18" fill="none" stroke="#e8eefc" stroke-width="12" stroke-linecap="round"/>
22
+ <rect x="332" y="338" width="72" height="56" rx="12" fill="#e8eefc"/>
23
+ <circle cx="368" cy="360" r="7" fill="#141a23"/>
24
+ <rect x="364" y="360" width="8" height="18" rx="4" fill="#141a23"/>
25
+ </svg>
package/lib/backend.js ADDED
@@ -0,0 +1,234 @@
1
+ // SSH TerminalBackend: process-internal ssh2 PTY per session, no local shell process.
2
+ // Human-in-the-loop auth: ssh2 keyboard-interactive prompts become user question cards.
3
+ import { readFileSync, existsSync } from 'node:fs';
4
+ import { Client } from 'ssh2';
5
+ import { TerminalError } from '@deepseek-ai/dsh-terminal';
6
+ import { loadSshHosts, defaultSshConfigPath, aliasFromCwd } from './ssh-config.js';
7
+ import { SshSession } from './ssh-session.js';
8
+
9
+ export class SshTerminalBackend {
10
+ constructor(deps) {
11
+ this.type = 'ssh';
12
+ this.deps = deps; // { resolve(): resolvedConfig, askHuman(owner, questions, signal): Promise<{answers}> }
13
+ this.sessions = new Map();
14
+ }
15
+
16
+ async spawn(spec) {
17
+ const cfg = this.deps.resolve();
18
+ if (spec.signal?.aborted) {
19
+ throw new TerminalError('terminal spawn aborted before connect', 'SPAWN_ABORTED');
20
+ }
21
+ const alias = aliasFromCwd(spec.cwd);
22
+ if (!alias) {
23
+ throw new TerminalError(
24
+ "SSH 终端需要主机别名:terminal_open(type:'ssh', cwd:'<主机别名>')。先用 ssh_term_hosts 查看可用别名。",
25
+ 'NO_HOST_ALIAS',
26
+ );
27
+ }
28
+ const configPath = cfg.sshConfigPath || defaultSshConfigPath();
29
+ const hosts = loadSshHosts(configPath);
30
+ const host = hosts.find((entry) => entry.alias.toLowerCase() === alias.toLowerCase());
31
+ if (!host) {
32
+ throw new TerminalError(
33
+ `~/.ssh/config(${configPath})中没有 Host "${alias}"。用 ssh_term_hosts 列出可用主机,` +
34
+ `或在 ~/.ssh/config 添加该 Host 后重试。`,
35
+ 'NO_SUCH_HOST',
36
+ );
37
+ }
38
+ if (!host.user) {
39
+ throw new TerminalError(
40
+ `Host "${alias}" 没有设置 User。请在 ~/.ssh/config 的该 Host 块中补一行 "User <用户名>" 后重试。`,
41
+ 'NO_SSH_USER',
42
+ );
43
+ }
44
+ const { conn, stream } = await this._connectAndShell(spec, host, cfg);
45
+ const session = new SshSession({
46
+ sessionId: spec.sessionId,
47
+ alias: host.alias,
48
+ conn,
49
+ stream,
50
+ config: cfg,
51
+ host: {
52
+ alias: host.alias,
53
+ hostname: host.hostname ?? host.alias,
54
+ port: host.port ?? 22,
55
+ user: host.user,
56
+ },
57
+ owner: spec.owner ? { id: spec.owner.id, name: spec.owner.name } : undefined,
58
+ onClosed: (id) => this.sessions.delete(id),
59
+ });
60
+ this.sessions.set(spec.sessionId, session);
61
+ try {
62
+ await session.warmup(spec.signal);
63
+ } catch (error) {
64
+ await session.close('warmup failed').catch(() => {});
65
+ throw error;
66
+ }
67
+ return session;
68
+ }
69
+
70
+ _connectAndShell(spec, host, cfg) {
71
+ return new Promise((resolvePromise, rejectPromise) => {
72
+ const conn = new Client();
73
+ let settled = false;
74
+ let authCancelled = false;
75
+ let kiRetries = 0;
76
+ const totalTimeoutMs = cfg.connectTimeoutMs + cfg.authTimeoutMs;
77
+
78
+ const cleanup = () => {
79
+ clearTimeout(deadline);
80
+ spec.signal?.removeEventListener('abort', onAbort);
81
+ };
82
+ const fail = (error) => {
83
+ if (settled) return;
84
+ settled = true;
85
+ authCancelled = true;
86
+ cleanup();
87
+ try {
88
+ conn.end();
89
+ } catch {
90
+ // connection never established
91
+ }
92
+ rejectPromise(error);
93
+ };
94
+ const onAbort = () => {
95
+ fail(new TerminalError('SSH 终端创建已被取消。', 'SPAWN_ABORTED'));
96
+ };
97
+
98
+ const deadline = setTimeout(() => {
99
+ fail(
100
+ new TerminalError(
101
+ `SSH 连接/人工验证在 ${Math.round(totalTimeoutMs / 1000)} 秒内未完成。` +
102
+ '若提问卡片出现过但没来得及输入,请重新 terminal_open 并尽快在卡片中输入验证信息。',
103
+ 'AUTH_TIMEOUT',
104
+ ),
105
+ );
106
+ }, totalTimeoutMs);
107
+ spec.signal?.addEventListener('abort', onAbort, { once: true });
108
+
109
+ conn.on('error', (err) => {
110
+ fail(
111
+ new TerminalError(
112
+ `SSH 连接失败:${err?.message ?? String(err)}(host=${host.hostname ?? host.alias}:${host.port ?? 22})`,
113
+ 'CONNECT_FAILED',
114
+ ),
115
+ );
116
+ });
117
+ conn.on('close', () => {
118
+ if (!settled) {
119
+ fail(new TerminalError('SSH 连接在就绪前关闭。', 'CONNECT_FAILED'));
120
+ }
121
+ });
122
+ conn.on('keyboard-interactive', (name, instructions, lang, prompts, finish) => {
123
+ if (settled || authCancelled) return;
124
+ kiRetries += 1;
125
+ if (kiRetries > cfg.maxKeyRetries) {
126
+ fail(
127
+ new TerminalError(
128
+ `二次验证重试超过 ${cfg.maxKeyRetries} 次,放弃连接。请确认验证码/密码是否正确后重试。`,
129
+ 'AUTH_RETRIES_EXCEEDED',
130
+ ),
131
+ );
132
+ return;
133
+ }
134
+ const detailParts = [
135
+ `主机:${host.alias}(${host.hostname ?? host.alias}:${host.port ?? 22}${host.user ? `,用户 ${host.user}` : ''})`,
136
+ name ? `服务端提示:${name}` : '',
137
+ instructions ? String(instructions).trim() : '',
138
+ '回答仅用于完成本次 SSH 认证,不会被保存或复述。',
139
+ ].filter(Boolean);
140
+ const questions = prompts.map((prompt, index) => ({
141
+ id: `ki-${kiRetries}-${index}`,
142
+ question: String(prompt?.prompt ?? '验证输入').replace(/\s+$/, '') || '验证输入',
143
+ header: 'SSH 人工验证',
144
+ detail: detailParts.join('\n'),
145
+ multiSelect: false,
146
+ }));
147
+ Promise.resolve()
148
+ .then(() => {
149
+ const ask = this.deps.askHuman;
150
+ if (!ask) {
151
+ throw new TerminalError(
152
+ '本会话没有可用的人工提问通道(userQuestions 服务缺失),无法完成二次验证。',
153
+ 'NO_ASK_CHANNEL',
154
+ );
155
+ }
156
+ return ask(spec.owner, questions, spec.signal);
157
+ })
158
+ .then((result) => {
159
+ if (settled || authCancelled) return;
160
+ const byId = new Map((result?.answers ?? []).map((answer) => [answer.id, answer]));
161
+ const responses = prompts.map((prompt, index) => {
162
+ const answer = byId.get(`ki-${kiRetries}-${index}`);
163
+ const custom = typeof answer?.custom === 'string' ? answer.custom : '';
164
+ const selected =
165
+ Array.isArray(answer?.selected) && answer.selected.length > 0 ? String(answer.selected[0]) : '';
166
+ return custom || selected;
167
+ });
168
+ if (responses.every((response) => response === '')) {
169
+ fail(
170
+ new TerminalError(
171
+ '人工验证被跳过(未输入内容),SSH 终端创建已取消。如需继续,请重新 terminal_open 并在提问卡片中输入验证信息。',
172
+ 'AUTH_SKIPPED',
173
+ ),
174
+ );
175
+ return;
176
+ }
177
+ finish(responses);
178
+ })
179
+ .catch((error) => {
180
+ fail(
181
+ error instanceof TerminalError
182
+ ? error
183
+ : new TerminalError(`人工验证通道失败:${error?.message ?? String(error)}`, 'ASK_FAILED'),
184
+ );
185
+ });
186
+ });
187
+
188
+ conn.once('ready', () => {
189
+ conn.shell({ term: 'xterm-256color', cols: cfg.cols, rows: cfg.rows }, (err, stream) => {
190
+ if (err) {
191
+ fail(new TerminalError(`SSH shell 通道打开失败:${err.message}`, 'SHELL_FAILED'));
192
+ return;
193
+ }
194
+ if (settled) {
195
+ try {
196
+ stream.close();
197
+ } catch {
198
+ // never used
199
+ }
200
+ try {
201
+ conn.end();
202
+ } catch {
203
+ // never used
204
+ }
205
+ return;
206
+ }
207
+ settled = true;
208
+ cleanup();
209
+ resolvePromise({ conn, stream });
210
+ });
211
+ });
212
+
213
+ const connectConfig = {
214
+ host: host.hostname ?? host.alias,
215
+ port: host.port ?? 22,
216
+ username: host.user,
217
+ readyTimeout: cfg.connectTimeoutMs,
218
+ tryKeyboard: true,
219
+ keepaliveInterval: 15000,
220
+ keepaliveCountMax: 10,
221
+ };
222
+ const keyPath = host.identityFiles.find((path) => existsSync(path));
223
+ if (keyPath) {
224
+ try {
225
+ connectConfig.privateKey = readFileSync(keyPath);
226
+ } catch (error) {
227
+ fail(new TerminalError(`读取私钥 ${keyPath} 失败:${error.message}`, 'KEY_READ_FAILED'));
228
+ return;
229
+ }
230
+ }
231
+ conn.connect(connectConfig);
232
+ });
233
+ }
234
+ }
package/lib/index.js ADDED
@@ -0,0 +1,216 @@
1
+ // dsh-ssh-terminal: mounts an SSH TerminalBackend so terminal_* tools can drive
2
+ // interactive SSH sessions (bastion menu, 2FA and passwords answered by the human).
3
+ import { existsSync } from 'node:fs';
4
+ import z from '@deepseek-ai/schemastery';
5
+ import { TerminalError } from '@deepseek-ai/dsh-terminal';
6
+ import { defineTool } from '@deepseek-ai/dsh-tools';
7
+ import { SshTerminalBackend } from './backend.js';
8
+ import { loadSshHosts, defaultSshConfigPath } from './ssh-config.js';
9
+ import { makeTakeover } from './takeover.js';
10
+ import { snapshotJsonValue } from '@deepseek-ai/dsh-util-values';
11
+
12
+ export const name = 'dsh-ssh-pty';
13
+
14
+ export const inject = ['terminals', 'tools', 'systemPrompt', 'userQuestions', 'webServer'];
15
+
16
+ function readConfigField(field, fallback) {
17
+ if (field === undefined || field === null) return fallback;
18
+ if (typeof field === 'object' && typeof field.get === 'function') {
19
+ const value = field.get();
20
+ return value === undefined || value === null ? fallback : value;
21
+ }
22
+ return field;
23
+ }
24
+
25
+ export const Config = z
26
+ .object({
27
+ enabled: z.boolean().default(true).volatile(),
28
+ announceToAgent: z.boolean().default(true).volatile(),
29
+ takeoverEnabled: z.boolean().default(true).volatile(),
30
+ sshConfigPath: z.string().default('').volatile(),
31
+ connectTimeoutMs: z.number().step(1).min(1000).max(600000).default(30000).volatile(),
32
+ authTimeoutMs: z.number().step(1).min(10000).max(900000).default(120000).volatile(),
33
+ cols: z.number().step(1).min(20).max(500).default(120).volatile(),
34
+ rows: z.number().step(1).min(10).max(200).default(40).volatile(),
35
+ sendTimeoutMs: z.number().step(1).min(1000).max(600000).default(30000).volatile(),
36
+ idleSilenceMs: z.number().step(1).min(500).max(600000).default(3000).volatile(),
37
+ warmupTimeoutMs: z.number().step(1).min(1000).max(60000).default(8000).volatile(),
38
+ maxScrollbackLines: z.number().step(1).min(100).max(100000).default(5000).volatile(),
39
+ maxScrollbackBytes: z.number().step(1).min(65536).max(16777216).default(2097152).volatile(),
40
+ maxReadBytes: z.number().step(1).min(1024).max(4194304).default(262144).volatile(),
41
+ maxKeyRetries: z.number().step(1).min(1).max(5).default(3).volatile(),
42
+ });
43
+
44
+ const SSH_TOOL_NAMES = ['ssh_term_hosts'];
45
+
46
+ const GUIDANCE = [
47
+ 'SSH 受控终端(dsh-ssh-terminal):terminal_open(type:\'ssh\', cwd:\'<主机别名>\') 打开 ~/.ssh/config 中该主机的交互式 SSH 会话,先用 ssh_term_hosts 列出可用别名。',
48
+ '遇到二次验证(OTP/2FA)或登录密码时会弹出提问卡片:请提醒用户在卡片中输入,绝不要索要、记录或复述密码/验证码,也不要把密码写进 terminal_send。',
49
+ '菜单式堡垒机(JumpServer 等):登录后用 terminal_send 发送选项编号选择目标服务器;目标服务器的密码同样走提问卡片。',
50
+ '交互式程序(vim/top/less)直接 terminal_send 按键即可(vim 退出用 Esc+:q!+回车);返回的 viewport 就是当前屏幕内容。',
51
+ 'waitReason 含义:inferred_idle=输出已静默(不代表前台命令已退出)、timeout=到达 sendTimeoutMs、session_exit=连接已关闭。长输出用 terminal_read(offset,count) 分页回看(offset 从最新行往回数)。',
52
+ 'terminal_signal 仅支持 SIGINT(Ctrl-C) 与 SIGTSTP(Ctrl-Z)。排障路径:ssh_term_hosts → terminal_open → terminal_send 逐条观察输出 → 决定下一步。',
53
+ ].join('\n');
54
+
55
+ function applyImpl(ctx, config) {
56
+ const snapshot = () => ({
57
+ enabled: readConfigField(config?.enabled, true),
58
+ announceToAgent: readConfigField(config?.announceToAgent, true),
59
+ takeoverEnabled: readConfigField(config?.takeoverEnabled, true),
60
+ sshConfigPath: readConfigField(config?.sshConfigPath, ''),
61
+ connectTimeoutMs: readConfigField(config?.connectTimeoutMs, 30000),
62
+ authTimeoutMs: readConfigField(config?.authTimeoutMs, 120000),
63
+ cols: readConfigField(config?.cols, 120),
64
+ rows: readConfigField(config?.rows, 40),
65
+ sendTimeoutMs: readConfigField(config?.sendTimeoutMs, 30000),
66
+ idleSilenceMs: readConfigField(config?.idleSilenceMs, 3000),
67
+ warmupTimeoutMs: readConfigField(config?.warmupTimeoutMs, 8000),
68
+ maxScrollbackLines: readConfigField(config?.maxScrollbackLines, 5000),
69
+ maxScrollbackBytes: readConfigField(config?.maxScrollbackBytes, 2097152),
70
+ maxReadBytes: readConfigField(config?.maxReadBytes, 262144),
71
+ maxKeyRetries: readConfigField(config?.maxKeyRetries, 3),
72
+ });
73
+
74
+ const askHuman = (owner, questions, signal) => {
75
+ const service = ctx.userQuestions;
76
+ if (!service || typeof service.ask !== 'function') {
77
+ throw new TerminalError(
78
+ '本会话没有可用的人工提问通道(userQuestions 服务缺失),无法完成 SSH 二次验证。',
79
+ 'NO_ASK_CHANNEL',
80
+ );
81
+ }
82
+ return service.ask({ questions, agent: owner, signal, wait: true });
83
+ };
84
+
85
+ const backend = new SshTerminalBackend({ resolve: snapshot, askHuman });
86
+
87
+ // Takeover page + WS mirror: registered once for the plugin lifetime (the
88
+ // webserver route registry rejects duplicate (kind, path)); enable/disable
89
+ // is checked per request against the live config snapshot.
90
+ const takeover = makeTakeover({ backend, resolve: snapshot });
91
+ ctx.effect(() => {
92
+ const disposers = [
93
+ ...takeover.routes.map((route) => ctx.webServer.register(route)),
94
+ ctx.webServer.registerUpgrade(takeover.upgrade),
95
+ ];
96
+ return () => {
97
+ for (const dispose of disposers) {
98
+ try {
99
+ dispose?.();
100
+ } catch {
101
+ // server already gone
102
+ }
103
+ }
104
+ };
105
+ }, 'dsh-ssh-terminal: takeover web');
106
+
107
+ const hostsTool = defineTool({
108
+ name: 'ssh_term_hosts',
109
+ description:
110
+ 'List SSH host aliases from ~/.ssh/config available for controlled terminals. Open one with terminal_open(type:"ssh", cwd:"<alias>").',
111
+ parameters: {},
112
+ output: {
113
+ schema: {
114
+ type: 'object',
115
+ additionalProperties: false,
116
+ properties: {
117
+ configPath: { type: 'string', required: true },
118
+ hosts: { type: 'array', required: true },
119
+ },
120
+ },
121
+ render: (_args, value) => {
122
+ if (!value.hosts.length) {
123
+ return [{ type: 'text', text: `No usable Host entries found in ${value.configPath}.` }];
124
+ }
125
+ const lines = value.hosts.map((host) => {
126
+ const parts = [host.alias];
127
+ if (host.hostname && host.hostname !== host.alias) parts.push(`→ ${host.hostname}`);
128
+ if (host.port && host.port !== 22) parts.push(`:${host.port}`);
129
+ if (host.user) parts.push(`(user: ${host.user})`);
130
+ if (host.identityFile) parts.push(`[key: ${host.identityFile}]`);
131
+ if (host.proxyJump && host.proxyJump.length) parts.push(`(proxyjump: ${host.proxyJump.join(',')})`);
132
+ return `- ${parts.join(' ')}`;
133
+ });
134
+ return [
135
+ {
136
+ type: 'text',
137
+ text: `SSH hosts for controlled terminals (open with terminal_open type:"ssh", cwd:"<alias>"):\n${lines.join('\n')}`,
138
+ },
139
+ ];
140
+ },
141
+ },
142
+ isConcurrencySafe: () => true,
143
+ async execute() {
144
+ const cfg = snapshot();
145
+ const configPath = cfg.sshConfigPath || defaultSshConfigPath();
146
+ // DSH tool outputs must be lossless JSON: no undefined-valued fields, only plain primitives/arrays.
147
+ const hosts = loadSshHosts(configPath).map((host) => {
148
+ const key = (host.identityFiles || []).find((path) => existsSync(path));
149
+ const proxyJump = Array.isArray(host.proxyJump)
150
+ ? host.proxyJump.map(String)
151
+ : String(host.proxyJump ?? '').split(/[\s,]+/).filter(Boolean);
152
+ return {
153
+ alias: String(host.alias),
154
+ hostname: String(host.hostname ?? host.alias),
155
+ port: Number.isFinite(host.port) ? host.port : 22,
156
+ user: String(host.user ?? ''),
157
+ identityFile: key ? String(key) : '',
158
+ proxyJump,
159
+ };
160
+ });
161
+ const value = { configPath, hosts };
162
+ const snap = snapshotJsonValue(value);
163
+ if (snap === undefined) {
164
+ throw new Error('ssh_term_hosts output is not lossless JSON: ' + JSON.stringify(value));
165
+ }
166
+ return value;
167
+ },
168
+ });
169
+
170
+ let disposeSurfaces;
171
+ const sync = () => {
172
+ if (disposeSurfaces) {
173
+ disposeSurfaces();
174
+ disposeSurfaces = undefined;
175
+ }
176
+ const cfg = snapshot();
177
+ if (!cfg.enabled) return;
178
+ const takeoverUrl = (() => {
179
+ try {
180
+ const origin = typeof ctx.webServer?.getOrigin === 'function' ? ctx.webServer.getOrigin() : '';
181
+ return origin ? origin.replace(/\/$/, '') + '/api/dsh-ssh-terminal/ui' : '';
182
+ } catch {
183
+ return '';
184
+ }
185
+ })();
186
+ const guidance = takeoverUrl
187
+ ? GUIDANCE + '\n人工接管页(用户可直接往终端输入密码/2FA/菜单选择,不经过模型):' + takeoverUrl
188
+ : GUIDANCE;
189
+ disposeSurfaces = ctx.effect(() => {
190
+ const disposers = [];
191
+ disposers.push(ctx.terminals.registerBackend(backend));
192
+ for (const tool of [hostsTool]) {
193
+ disposers.push(ctx.tools.register(tool));
194
+ }
195
+ if (cfg.announceToAgent) {
196
+ disposers.push(
197
+ ctx.systemPrompt.section({ name: 'plugin:dsh-ssh-terminal', order: 151, text: guidance }),
198
+ );
199
+ }
200
+ return () => {
201
+ for (const dispose of disposers) {
202
+ try {
203
+ dispose?.();
204
+ } catch {
205
+ // surface already gone
206
+ }
207
+ }
208
+ };
209
+ }, 'dsh-ssh-terminal: surfaces');
210
+ };
211
+
212
+ ctx.on('loader/volatile-update', () => sync());
213
+ sync();
214
+ }
215
+
216
+ export const apply = applyImpl;