@nsyan/ssh 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) 2024 pi-plugins 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,11 @@
1
- # Temporary Holding Version
1
+ # @nsyan/ssh
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
+ pi 的远程运维扩展:SSH/SFTP/FTP。设计见 `docs/superpowers/specs/2026-11-18-ssh-plugin-design.md`。
4
+
5
+ 工具已经注册:`ssh_hosts`、`ssh_exec`、`ssh_sudo`、`ssh_ls`、`ssh_read`、`ssh_put`、`ssh_get`、`ssh_deploy`、`ssh_rollback`、`ssh_tunnel`、`ssh_doctor`、`ssh_scan_sources`、`ssh_host_save`。管理命令是 `/ssh`。
6
+
7
+ 部署只读主机配置里的 `deploy` 布局。重启命令和健康检查不能在调用时临时传入。密码不进工具参数;macOS 上新密码写入 `~/.pi/agent/ssh-secrets.json`,不传给 `security -w`。
8
+
9
+ ```bash
10
+ pnpm --filter @nsyan/ssh test
11
+ ```
package/index.ts ADDED
@@ -0,0 +1,573 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { readAudit, defaultAuditPath } from "./src/core/audit.js";
4
+ import { loadHosts, saveHosts, defaultConfigPath } from "./src/core/config.js";
5
+ import { doctorLines } from "./src/core/doctor.js";
6
+ import { parseSshConfig } from "./src/scan/ssh-config.js";
7
+ import { projectDeployFiles } from "./src/scan/project.js";
8
+ import { saveHostCandidate } from "./src/scan/save.js";
9
+ import { defaultSecretsPath, putSecret } from "./src/core/secrets.js";
10
+ import { HostKeyUnknownError } from "./src/core/types.js";
11
+ import { readFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+ import { describeHosts } from "./src/prompt.js";
15
+ import { createRuntime } from "./src/runtime.js";
16
+
17
+ const runtime = createRuntime();
18
+
19
+ function text(value: string, details: unknown, isError = false) {
20
+ return { content: [{ type: "text" as const, text: value }], details, isError };
21
+ }
22
+
23
+ function failure(error: unknown) {
24
+ const message = error instanceof Error ? error.message : String(error);
25
+ return text(message, { error: message }, true);
26
+ }
27
+
28
+ async function readSecret(
29
+ ctx: { ui: { confirm: (title: string, message: string) => Promise<boolean>; input: (title: string, placeholder?: string) => Promise<string | undefined>; onTerminalInput?: (handler: (data: string) => { consume?: boolean } | undefined) => () => void; setStatus?: (key: string, value: string | undefined) => void } },
30
+ title: string,
31
+ prompt: string,
32
+ ): Promise<string | undefined> {
33
+ if (!ctx.ui.onTerminalInput || !ctx.ui.setStatus) {
34
+ const accepted = await ctx.ui.confirm(title, "当前界面不能掩码。密码会明文输入,并且只进本次调用,不写入命令。继续?");
35
+ if (!accepted) return undefined;
36
+ return ctx.ui.input(prompt, title);
37
+ }
38
+ const setStatus = ctx.ui.setStatus.bind(ctx.ui);
39
+ setStatus("ssh-secret", prompt);
40
+ return new Promise((resolve) => {
41
+ let value = "";
42
+ const off = ctx.ui.onTerminalInput!((data) => {
43
+ if (data === "\r" || data === "\n") {
44
+ off();
45
+ setStatus("ssh-secret", undefined);
46
+ resolve(value);
47
+ return { consume: true };
48
+ }
49
+ if (data === "\u0003" || data === "\u001b") {
50
+ off();
51
+ setStatus("ssh-secret", undefined);
52
+ resolve(undefined);
53
+ return { consume: true };
54
+ }
55
+ if (data === "\u007f" || data === "\b") value = value.slice(0, -1);
56
+ else value += data;
57
+ setStatus("ssh-secret", "*".repeat(value.length) || prompt);
58
+ return { consume: true };
59
+ });
60
+ });
61
+ }
62
+
63
+ /**
64
+ * 首次连接的指纹必须给人看过才算数。
65
+ * 未知密钥先失败,把指纹摆出来让人确认,确认后才写 known_hosts。
66
+ */
67
+ async function testWithTofu(
68
+ hostName: string | undefined,
69
+ ui: { confirm: (title: string, message: string) => Promise<boolean> },
70
+ ): Promise<{ ok: boolean; auth: string; fingerprint: string; keyType: string; latencyMs: number; transport: string }> {
71
+ try {
72
+ return await runtime.testHost({ host: hostName });
73
+ } catch (error) {
74
+ if (!(error instanceof HostKeyUnknownError)) throw error;
75
+ const accepted = await ui.confirm("未知主机密钥", `${error.message}\n\n用 ssh-keygen -lf 核对后,确认记录这个指纹并继续?`);
76
+ if (!accepted) throw new Error("用户没有确认主机密钥,已停止。");
77
+ return runtime.testHost({ host: hostName, acceptNewHostKey: true });
78
+ }
79
+ }
80
+
81
+ export default function sshExtension(pi: ExtensionAPI) {
82
+ pi.on("session_shutdown", () => {
83
+ void runtime.closeTunnels();
84
+ });
85
+
86
+ pi.registerTool({
87
+ name: "ssh_hosts",
88
+ label: "SSH 主机",
89
+ description: "列出已配置主机,或测试某一台的连接。",
90
+ promptSnippet: "查看或测试 SSH 主机。",
91
+ parameters: Type.Object({
92
+ action: Type.Union([Type.Literal("list"), Type.Literal("test")]),
93
+ name: Type.Optional(Type.String({ description: "test 时的主机名" })),
94
+ acceptNewHostKey: Type.Optional(Type.Boolean({ description: "首次连接时记录主机密钥" })),
95
+ }),
96
+ async execute(_toolCallId, params) {
97
+ try {
98
+ const file = loadHosts();
99
+ if (params.action === "list") return text(describeHosts(file), { count: Object.keys(file.hosts).length });
100
+ const result = await runtime.testHost({ host: params.name, acceptNewHostKey: params.acceptNewHostKey });
101
+ return text(`${params.name ?? "活动主机"} ${result.transport} ${result.auth} ${result.fingerprint} ${result.latencyMs}ms`, result);
102
+ } catch (error) {
103
+ return failure(error);
104
+ }
105
+ },
106
+ });
107
+
108
+ pi.registerTool({
109
+ name: "ssh_ls",
110
+ label: "SSH 列目录",
111
+ description: "用 SFTP 列出远端目录,返回类型、大小和文件名。",
112
+ promptSnippet: "列出远端目录。",
113
+ parameters: Type.Object({
114
+ path: Type.String({ description: "远端目录" }),
115
+ host: Type.Optional(Type.String({ description: "主机名" })),
116
+ }),
117
+ async execute(_toolCallId, params) {
118
+ try {
119
+ return text(await runtime.list(params), { path: params.path });
120
+ } catch (error) {
121
+ return failure(error);
122
+ }
123
+ },
124
+ });
125
+
126
+ pi.registerTool({
127
+ name: "ssh_read",
128
+ label: "SSH 读文件",
129
+ description: "读取远端文本文件的一段。offset 从 1 开始,默认 200 行。单次最多 200 行或 512KB,按 UTF-8 字符边界截断。",
130
+ promptSnippet: "按行读取远端文件。",
131
+ parameters: Type.Object({
132
+ path: Type.String({ description: "远端文件" }),
133
+ host: Type.Optional(Type.String({ description: "主机名" })),
134
+ offset: Type.Optional(Type.Number({ description: "起始行,从 1 开始" })),
135
+ limit: Type.Optional(Type.Number({ description: "行数" })),
136
+ }),
137
+ async execute(_toolCallId, params) {
138
+ try {
139
+ return text(await runtime.read(params), { path: params.path });
140
+ } catch (error) {
141
+ return failure(error);
142
+ }
143
+ },
144
+ });
145
+
146
+ pi.registerTool({
147
+ name: "ssh_exec",
148
+ label: "SSH 执行",
149
+ description: "在已配置的主机上执行一条非交互命令。没有 TTY,sudo 和 top 不能用。破坏性命令会先请用户确认。",
150
+ promptSnippet: "在远端主机执行命令。两台及以上主机必须传 host。",
151
+ promptGuidelines: [
152
+ "用 ssh_exec 跑远端命令,不要用本机 bash 里的 ssh。",
153
+ "已配置多台主机时,ssh_exec 必须传 host。",
154
+ "用户拒绝后不要改写命令再试。",
155
+ ],
156
+ parameters: Type.Object({
157
+ command: Type.String({ description: "远端命令" }),
158
+ host: Type.Optional(Type.String({ description: "主机名。只有一台时可以省略" })),
159
+ cwd: Type.Optional(Type.String({ description: "远端工作目录" })),
160
+ timeoutSec: Type.Optional(Type.Number({ description: "超时秒数" })),
161
+ reason: Type.Optional(Type.String({ description: "生产主机破坏性操作必填:动机和影响范围" })),
162
+ waitFor: Type.Optional(Type.Object({
163
+ port: Type.Optional(Type.Number()),
164
+ http: Type.Optional(Type.String()),
165
+ file: Type.Optional(Type.String()),
166
+ timeoutSec: Type.Number(),
167
+ })),
168
+ }),
169
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
170
+ try {
171
+ let lastAt = 0;
172
+ let pending = "";
173
+ let lastBytes = 0;
174
+ const flush = (force = false) => {
175
+ const now = Date.now();
176
+ if (!force && now - lastAt < 100 && Buffer.byteLength(pending) < 8192) return;
177
+ if (!pending) return;
178
+ lastAt = now;
179
+ const textChunk = pending;
180
+ pending = "";
181
+ onUpdate?.({ content: [{ type: "text", text: textChunk }], details: { bytes: lastBytes } });
182
+ };
183
+ const result = await runtime.exec({
184
+ host: params.host,
185
+ command: params.command,
186
+ cwd: params.cwd,
187
+ timeoutSec: params.timeoutSec,
188
+ reason: params.reason,
189
+ waitFor: params.waitFor,
190
+ signal,
191
+ onData: (chunk) => {
192
+ pending += chunk;
193
+ lastBytes += chunk.length;
194
+ flush();
195
+ },
196
+ ui: ctx.ui,
197
+ });
198
+ flush(true);
199
+ const status = result.exitCode === null ? "超时或中止" : `退出码 ${result.exitCode}`;
200
+ return text(`${status}\n${result.text}`, { exitCode: result.exitCode, truncated: result.truncated });
201
+ } catch (error) {
202
+ return failure(error);
203
+ }
204
+ },
205
+ });
206
+
207
+ pi.registerTool({
208
+ name: "ssh_put",
209
+ label: "SSH 上传",
210
+ description: "用 SFTP 上传一个文件。先写 .part,校验 sha256 后转正。覆盖已有文件前会备份并请用户确认。不接受目录。",
211
+ promptSnippet: "上传本地文件到远端。目录要先在本地打包。",
212
+ promptGuidelines: ["目录不要逐个 ssh_put。先打成一个包再传。"],
213
+ parameters: Type.Object({
214
+ localPath: Type.String({ description: "本地文件" }),
215
+ remotePath: Type.String({ description: "远端文件路径" }),
216
+ host: Type.Optional(Type.String({ description: "主机名" })),
217
+ }),
218
+ async execute(_toolCallId, params, _signal, onUpdate, ctx) {
219
+ try {
220
+ let lastAt = 0;
221
+ let lastBytes = 0;
222
+ const result = await runtime.put({
223
+ ...params,
224
+ ui: ctx.ui,
225
+ onProgress: (sent, total) => {
226
+ const now = Date.now();
227
+ if (now - lastAt < 100 && sent - lastBytes < 8192 && sent < total) return;
228
+ lastAt = now;
229
+ lastBytes = sent;
230
+ onUpdate?.({ content: [{ type: "text", text: `已传 ${sent}/${total}` }], details: { sent, total } });
231
+ },
232
+ });
233
+ return text(`已上传 ${result.bytes} 字节,sha256 ${result.sha256}${result.backupPath ? `,原文件备份在 ${result.backupPath}` : ""}`, result);
234
+ } catch (error) {
235
+ return failure(error);
236
+ }
237
+ },
238
+ });
239
+
240
+ pi.registerTool({
241
+ name: "ssh_get",
242
+ label: "SSH 下载",
243
+ description: "用 SFTP 把远端文件下载到本地。",
244
+ promptSnippet: "下载远端文件到本地。",
245
+ parameters: Type.Object({
246
+ remotePath: Type.String({ description: "远端文件" }),
247
+ localPath: Type.String({ description: "本地保存路径" }),
248
+ host: Type.Optional(Type.String({ description: "主机名" })),
249
+ }),
250
+ async execute(_toolCallId, params) {
251
+ try {
252
+ const result = await runtime.get(params);
253
+ return text(`已下载 ${result.bytes} 字节,sha256 ${result.sha256}`, result);
254
+ } catch (error) {
255
+ return failure(error);
256
+ }
257
+ },
258
+ });
259
+
260
+ pi.registerTool({
261
+ name: "ssh_sudo",
262
+ label: "SSH sudo",
263
+ description: "在远端用 sudo 执行命令。密码由用户在本地输入,不作为工具参数,也不写入命令文本。",
264
+ promptSnippet: "需要 root 时用 ssh_sudo,不要把密码写进命令。",
265
+ promptGuidelines: ["不要在 ssh_exec 里拼接 sudo 密码。改用 ssh_sudo。"],
266
+ parameters: Type.Object({
267
+ command: Type.String({ description: "交给 sudo 的命令" }),
268
+ host: Type.Optional(Type.String({ description: "主机名" })),
269
+ reason: Type.Optional(Type.String({ description: "生产主机的破坏性命令必填" })),
270
+ }),
271
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
272
+ try {
273
+ const result = await runtime.sudo({
274
+ ...params,
275
+ ui: {
276
+ confirm: (title, message) => ctx.ui.confirm(title, message),
277
+ secret: async (title, prompt) => readSecret(ctx, title, prompt),
278
+ },
279
+ });
280
+ return text(`退出码 ${result.exitCode}\n${result.text}`, { exitCode: result.exitCode });
281
+ } catch (error) {
282
+ return failure(error);
283
+ }
284
+ },
285
+ });
286
+
287
+ pi.registerTool({
288
+ name: "ssh_tunnel",
289
+ label: "SSH 端口转发",
290
+ description: "把远端才能访问的地址转到本机 127.0.0.1。listenPort 由调用方指定,0 表示让系统选空闲端口。只监听本机回环,不对外网卡开放。",
291
+ promptSnippet: "把远端服务转到本机回环端口。",
292
+ parameters: Type.Object({
293
+ listenPort: Type.Number({ description: "本机端口。0 表示自动选择" }),
294
+ destHost: Type.String({ description: "从远端看到的目标主机" }),
295
+ destPort: Type.Number({ description: "目标端口" }),
296
+ direction: Type.Optional(Type.Union([Type.Literal("local"), Type.Literal("remote")])),
297
+ host: Type.Optional(Type.String({ description: "跳板主机名" })),
298
+ }),
299
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
300
+ try {
301
+ const opened = await runtime.tunnel({ ...params, ui: ctx.ui });
302
+ return text(`127.0.0.1:${opened.port} -> ${params.destHost}:${params.destPort}`, { port: opened.port });
303
+ } catch (error) {
304
+ return failure(error);
305
+ }
306
+ },
307
+ });
308
+
309
+ pi.registerTool({
310
+ name: "ssh_deploy",
311
+ label: "SSH 部署",
312
+ description: "按主机配置里的 deploy 布局发布。缺省是 tar。重启命令和健康检查只读配置,不接受调用时临时传入。",
313
+ promptSnippet: "按主机上的 deploy 布局发布。",
314
+ parameters: Type.Object({
315
+ localPath: Type.String({ description: "本地制品" }),
316
+ host: Type.Optional(Type.String({ description: "主机名" })),
317
+ kind: Type.Optional(Type.Union([Type.Literal("tar"), Type.Literal("file")])),
318
+ releaseId: Type.Optional(Type.String({ description: "发布号,缺省用时间" })),
319
+ dryRun: Type.Optional(Type.Boolean({ description: "只返回剧本,不上传不切换" })),
320
+ reason: Type.Optional(Type.String({ description: "生产主机必填" })),
321
+ }),
322
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
323
+ try {
324
+ const result = await runtime.deploy({
325
+ ...params,
326
+ signal,
327
+ onStep: (message) => onUpdate?.({ content: [{ type: "text", text: message }], details: { step: message } }),
328
+ ui: ctx.ui,
329
+ });
330
+ if (result.dryRun) return text(`只生成剧本,未执行。目标 ${result.current}`, result);
331
+ return text(result.rolledBack ? `健康检查失败,已切回 ${result.current}` : `已切换到 ${result.current}`, result);
332
+ } catch (error) {
333
+ return failure(error);
334
+ }
335
+ },
336
+ });
337
+
338
+ pi.registerTool({
339
+ name: "ssh_rollback",
340
+ label: "SSH 回滚",
341
+ description: "按主机上的 deploy 布局回滚,或恢复一个带 .bak 的文件。",
342
+ promptSnippet: "回滚远端 release 或文件。",
343
+ parameters: Type.Object({
344
+ host: Type.Optional(Type.String({ description: "主机名" })),
345
+ target: Type.Object({
346
+ kind: Type.Union([Type.Literal("file"), Type.Literal("release")]),
347
+ path: Type.Optional(Type.String({ description: "kind 为 file 时的远端文件" })),
348
+ to: Type.Optional(Type.String({ description: "kind 为 release 时的发布号,缺省上一版" })),
349
+ }),
350
+ reason: Type.Optional(Type.String({ description: "生产主机必填" })),
351
+ }),
352
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
353
+ try {
354
+ if (params.target.kind === "file" && !params.target.path) return failure(new Error("文件回滚需要 target.path"));
355
+ const result = await runtime.rollback({
356
+ host: params.host,
357
+ file: params.target.kind === "file" ? params.target.path : undefined,
358
+ to: params.target.kind === "release" ? params.target.to : undefined,
359
+ reason: params.reason,
360
+ ui: ctx.ui,
361
+ });
362
+ return text(`已回滚到 ${result.current}`, result);
363
+ } catch (error) {
364
+ return failure(error);
365
+ }
366
+ },
367
+ });
368
+
369
+ pi.registerTool({
370
+ name: "ssh_doctor",
371
+ label: "SSH 体检",
372
+ description: "检查本机 ssh2、系统 ssh、known_hosts 和审计目录,不连接远端。",
373
+ promptSnippet: "检查本机 SSH 插件环境。",
374
+ parameters: Type.Object({}),
375
+ async execute() {
376
+ return text(doctorLines().join("\n"), {});
377
+ },
378
+ });
379
+
380
+ pi.registerTool({
381
+ name: "ssh_scan_sources",
382
+ label: "扫描 SSH 来源",
383
+ description: "解析本机 ~/.ssh/config 的具体 Host,并列出当前目录里可能含部署目标的文件。不写入配置。",
384
+ promptSnippet: "扫描已有 SSH 配置和项目里的部署文件。",
385
+ parameters: Type.Object({
386
+ cwd: Type.Optional(Type.String({ description: "项目目录,缺省当前目录" })),
387
+ }),
388
+ async execute(_toolCallId, params) {
389
+ let configText = "";
390
+ try {
391
+ configText = readFileSync(join(homedir(), ".ssh", "config"), "utf8");
392
+ } catch {
393
+ configText = "";
394
+ }
395
+ const hosts = parseSshConfig(configText);
396
+ const files = projectDeployFiles(params.cwd ?? process.cwd());
397
+ const hostLines = hosts.map((item) => `${item.name} ${item.user ?? ""}@${item.hostName ?? item.name}`);
398
+ return text([...hostLines, ...files.map((file) => `file ${file}`)].join("\n") || "没有具体 Host", { hosts, files });
399
+ },
400
+ });
401
+
402
+ pi.registerTool({
403
+ name: "ssh_host_save",
404
+ label: "保存 SSH 主机",
405
+ description: "先实测连接,再把主机写入配置。没有私钥时密码进 0600 文件,不进参数。同名时覆盖、改名或跳过。",
406
+ promptSnippet: "实测通过后再保存一台 SSH 主机。",
407
+ parameters: Type.Object({
408
+ name: Type.String(),
409
+ host: Type.String(),
410
+ user: Type.String(),
411
+ port: Type.Optional(Type.Number()),
412
+ privateKeyPath: Type.Optional(Type.String()),
413
+ tags: Type.Optional(Type.Array(Type.String({ description: "含 prod 时按生产主机处理" }))),
414
+ choice: Type.Optional(Type.Union([Type.Literal("overwrite"), Type.Literal("rename"), Type.Literal("skip")])),
415
+ acceptNewHostKey: Type.Optional(Type.Boolean()),
416
+ }),
417
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
418
+ const accepted = await ctx.ui.confirm("保存主机", `${params.user}@${params.host}`);
419
+ if (!accepted) return text("已跳过", { saved: false });
420
+ const current = loadHosts();
421
+ const choice = params.choice ?? (current.hosts[params.name] ? undefined : "rename");
422
+ if (!choice) return text("同名主机已存在。choice 需要是 overwrite、rename 或 skip。", { saved: false });
423
+ let secretRef: string | undefined;
424
+ if (!params.privateKeyPath) {
425
+ const password = await readSecret(ctx, "登录密码", "密码不进入对话记录");
426
+ if (!password) return text("没有密码,未保存", { saved: false });
427
+ secretRef = `pending:${password}`;
428
+ }
429
+ const saved = saveHostCandidate(current, { ...params, secretRef }, choice);
430
+ if (!saved.saved) return text("同名主机已跳过", { saved: false });
431
+ if (secretRef?.startsWith("pending:")) {
432
+ putSecret(defaultSecretsPath(), saved.name, secretRef.slice("pending:".length));
433
+ saved.file.hosts[saved.name].auth.secretRef = `file:${defaultSecretsPath()}#${saved.name}`;
434
+ }
435
+ saveHosts(defaultConfigPath(), saved.file);
436
+ try {
437
+ const tested = params.acceptNewHostKey === true
438
+ ? await runtime.testHost({ host: saved.name, acceptNewHostKey: true })
439
+ : await testWithTofu(saved.name, ctx.ui);
440
+ return text(`已保存 ${saved.name},${tested.auth} ${tested.fingerprint} ${tested.latencyMs}ms`, { saved: true, ...tested });
441
+ } catch (error) {
442
+ const next = loadHosts();
443
+ delete next.hosts[saved.name];
444
+ saveHosts(defaultConfigPath(), next);
445
+ return failure(error);
446
+ }
447
+ },
448
+ });
449
+
450
+ pi.registerCommand("ssh", {
451
+ description: "查看、测试或切换 SSH 主机",
452
+ async handler(args, ctx) {
453
+ const [sub, name] = args.trim().split(/\s+/, 2);
454
+ const file = loadHosts();
455
+ if (!sub || sub === "ls") {
456
+ ctx.ui.notify(describeHosts(file), "info");
457
+ return;
458
+ }
459
+ if (sub === "use") {
460
+ if (!file.hosts[name]) {
461
+ ctx.ui.notify(`没有名为 ${name} 的主机`, "error");
462
+ return;
463
+ }
464
+ saveHosts(defaultConfigPath(), { ...file, activeHost: name });
465
+ ctx.ui.notify(`活动主机已切换为 ${name}`, "info");
466
+ return;
467
+ }
468
+ if (sub === "test") {
469
+ try {
470
+ const result = await runtime.testHost({ host: name });
471
+ ctx.ui.notify(`${name || "活动主机"} ${result.auth} ${result.fingerprint} ${result.latencyMs}ms`, result.ok ? "info" : "error");
472
+ } catch (error) {
473
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
474
+ }
475
+ return;
476
+ }
477
+ if (sub === "rm") {
478
+ if (!file.hosts[name]) {
479
+ ctx.ui.notify(`没有名为 ${name} 的主机`, "error");
480
+ return;
481
+ }
482
+ const accepted = await ctx.ui.confirm("删除主机", name);
483
+ if (!accepted) return;
484
+ const next = { ...file, hosts: { ...file.hosts } };
485
+ delete next.hosts[name];
486
+ if (next.activeHost === name) next.activeHost = undefined;
487
+ saveHosts(defaultConfigPath(), next);
488
+ ctx.ui.notify(`已删除 ${name}`, "info");
489
+ return;
490
+ }
491
+ if (sub === "grant") {
492
+ const minutes = Number(args.trim().split(/\s+/)[2] ?? 10);
493
+ const accepted = await ctx.ui.confirm("写授权", `${name} 在 ${minutes} 分钟内不再逐条确认写操作`);
494
+ if (!accepted) return;
495
+ try {
496
+ runtime.grantWrite(name, Number.isFinite(minutes) ? minutes : 10);
497
+ ctx.ui.notify(`${name} 的写操作在 ${minutes} 分钟内不再逐条确认。破坏性操作仍要确认。`, "info");
498
+ } catch (error) {
499
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
500
+ }
501
+ return;
502
+ }
503
+ if (sub === "log") {
504
+ const rows = readAudit(defaultAuditPath()).slice(-20);
505
+ ctx.ui.notify(rows.map((row) => `${row.ts} ${row.tool} ${row.command}`).join("\n") || "没有审计", "info");
506
+ return;
507
+ }
508
+ if (sub === "add" || sub === "edit") {
509
+ const current = name ? file.hosts[name] : undefined;
510
+ if (sub === "edit" && !current) {
511
+ ctx.ui.notify(`没有名为 ${name} 的主机`, "error");
512
+ return;
513
+ }
514
+ const hostName = sub === "add" ? await ctx.ui.input("主机名", "") : name;
515
+ const address = await ctx.ui.input("地址", current?.host ?? "");
516
+ const user = await ctx.ui.input("用户", current?.user ?? "");
517
+ const keyPath = await ctx.ui.input("私钥路径,密码登录留空", current?.auth.privateKeyPath ?? "");
518
+ const prod = await ctx.ui.confirm("生产主机", "这台机器的标签要包含 prod 吗?生产主机的写操作一律确认。");
519
+ if (!hostName || !address || !user) return;
520
+ let secretRef = current?.auth.secretRef;
521
+ if (!keyPath) {
522
+ const password = await readSecret(ctx, "登录密码", "密码不进入对话记录");
523
+ if (!password && !secretRef) return;
524
+ if (password) {
525
+ putSecret(defaultSecretsPath(), hostName, password);
526
+ secretRef = `file:${defaultSecretsPath()}#${hostName}`;
527
+ }
528
+ }
529
+ const saved = saveHostCandidate(loadHosts(), {
530
+ name: hostName,
531
+ host: address,
532
+ user,
533
+ privateKeyPath: keyPath || undefined,
534
+ secretRef,
535
+ tags: prod ? ["prod"] : current?.tags?.filter((tag) => tag !== "prod"),
536
+ }, sub === "edit" ? "overwrite" : "rename");
537
+ if (saved.saved) saveHosts(defaultConfigPath(), saved.file);
538
+ if (!saved.saved) {
539
+ ctx.ui.notify("未保存", "warning");
540
+ return;
541
+ }
542
+ try {
543
+ const tested = await testWithTofu(saved.name, ctx.ui);
544
+ ctx.ui.notify(`已保存 ${saved.name},${tested.fingerprint}`, "info");
545
+ } catch (error) {
546
+ const next = loadHosts();
547
+ delete next.hosts[saved.name];
548
+ saveHosts(defaultConfigPath(), next);
549
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
550
+ }
551
+ return;
552
+ }
553
+ if (sub === "exec") {
554
+ const command = args.trim().slice("exec".length).trim();
555
+ if (!command) {
556
+ ctx.ui.notify("用法:/ssh exec <命令>", "error");
557
+ return;
558
+ }
559
+ try {
560
+ const result = await runtime.exec({ command, allowActive: true, ui: ctx.ui });
561
+ ctx.ui.notify(`退出码 ${result.exitCode}\n${result.text}`, result.exitCode === 0 ? "info" : "error");
562
+ } catch (error) {
563
+ ctx.ui.notify(error instanceof Error ? error.message : String(error), "error");
564
+ }
565
+ return;
566
+ }
567
+ ctx.ui.notify("用法:/ssh ls | add | edit <主机> | test <主机> | use <主机> | rm <主机> | exec <命令> | grant <主机> <分钟> | log", "info");
568
+ },
569
+ });
570
+ }
571
+
572
+ export { classify, decide } from "./src/core/policy.js";
573
+ export type { Danger, Verdict, Policy, SessionGrant, Decision } from "./src/core/policy.js";
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@nsyan/ssh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "AI 远程运维扩展 for pi coding agent:SSH/SFTP/FTP 主机管理、危险命令确认、审计与可回滚部署 | Remote ops for the pi agent: SSH, SFTP and FTP with confirmation, audit and rollback",
5
+ "keywords": [
6
+ "pi-extension",
7
+ "pi-package",
8
+ "pi",
9
+ "pi-coding-agent",
10
+ "ssh",
11
+ "sftp",
12
+ "ftp",
13
+ "scp",
14
+ "remote",
15
+ "devops",
16
+ "deploy",
17
+ "rollback"
18
+ ],
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/nsyan/pi-plugins.git"
22
+ },
23
+ "license": "MIT",
24
+ "engines": {
25
+ "node": ">=18"
26
+ },
27
+ "type": "module",
28
+ "main": "index.ts",
29
+ "pi": {
30
+ "extensions": [
31
+ "./index.ts"
32
+ ],
33
+ "skills": [
34
+ "./skills"
35
+ ]
36
+ },
37
+ "files": [
38
+ "index.ts",
39
+ "src/",
40
+ "skills/",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "scripts": {
45
+ "test": "tsx --test \"test/**/*.test.ts\"",
46
+ "typecheck": "tsc -p tsconfig.typecheck.json"
47
+ },
48
+ "peerDependencies": {
49
+ "@earendil-works/pi-coding-agent": "*",
50
+ "typebox": "*"
51
+ },
52
+ "devDependencies": {
53
+ "@earendil-works/pi-coding-agent": "^0.85.1",
54
+ "@types/node": "^22.20.2",
55
+ "@types/ssh2": "^1.15.5",
56
+ "tsx": "^4.23.13",
57
+ "typebox": "^1.3.27",
58
+ "typescript": "^7.0.2"
59
+ },
60
+ "dependencies": {
61
+ "basic-ftp": "^5.0.5",
62
+ "ssh2": "^1.17.0"
63
+ }
64
+ }
@@ -0,0 +1,8 @@
1
+ # 部署
2
+
3
+ 能走 ssh_deploy 的发布不要用 ssh_exec 拼 rm 或 docker rm。
4
+
5
+ - 先 dryRun 看剧本,再真正部署。
6
+ - 只使用主机配置里的 deploy 布局。不要在调用时临时传 root、restartCmd 或 healthCmd。
7
+ - 生产主机必须带 reason。
8
+ - 健康检查失败会自动切回上一版。