pi-foreman 0.0.0-stage → 0.1.2
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 +21 -0
- package/README.md +179 -2
- package/package.json +58 -4
- package/src/bootstrap.mjs +107 -0
- package/src/cli.mjs +504 -0
- package/src/config.mjs +819 -0
- package/src/docs.mjs +148 -0
- package/src/envs.mjs +621 -0
- package/src/harness.mjs +96 -0
- package/src/hub.mjs +117 -0
- package/src/projection.mjs +455 -0
- package/src/providers.mjs +622 -0
- package/src/server.mjs +1350 -0
- package/src/skills.mjs +340 -0
- package/src/stores.mjs +117 -0
- package/src/tasks/ask-peer.mjs +201 -0
- package/src/tasks/peer-tools.mjs +254 -0
- package/src/tasks/workspace-extension.mjs +108 -0
- package/web/dist/assets/chat-vendor-CpKl2eGN.css +1 -0
- package/web/dist/assets/chat-vendor-PY5rkhAV.js +43 -0
- package/web/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/web/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/web/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/web/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/web/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/web/dist/assets/icons-BRdrcGH3.js +2 -0
- package/web/dist/assets/index-C32JOM8D.js +35 -0
- package/web/dist/assets/index-D_7gqB73.css +1 -0
- package/web/dist/assets/react-vendor-DEAzPTfA.js +10 -0
- package/web/dist/index.html +17 -0
package/src/envs.mjs
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 环境管理层(v2):四态统一执行面 + 全异步子进程 + 容器自动发现。
|
|
3
|
+
*
|
|
4
|
+
* 四种环境形态:
|
|
5
|
+
* 1. local-host 本机宿主机 → LocalExecutionEnv(pi-env localDaemon,不可用时回退 NodeExecutionEnv)
|
|
6
|
+
* 2. local-docker 本机容器 → Connection(["docker", "exec", ...]) + RemoteExecutionEnv(零 SSH)
|
|
7
|
+
* 3. ssh-host 远程宿主机 → sshConnection() + RemoteExecutionEnv
|
|
8
|
+
* 4. ssh-docker 远程容器 → Connection(["ssh", ..., "docker", "exec", ...]) + RemoteExecutionEnv
|
|
9
|
+
*
|
|
10
|
+
* 🔴 关键不变量:
|
|
11
|
+
* - HarnessOptions.env 被频繁调用(~1.8× 模型调用数),Connection 与 ExecutionEnv 必须缓存。
|
|
12
|
+
* - 绝不使用 spawnSync,全部异步 execFile + AbortSignal,避免卡死事件循环(I-21)。
|
|
13
|
+
* - 所有拼入远端 shell 的参数必须经过 shQuote() POSIX 单引号转义。
|
|
14
|
+
* - 共享 bind-mount 路径的环境通过 fsGroup 共享 env.id,确保 (env.id, path) 文件写锁生效(I-17)。
|
|
15
|
+
*/
|
|
16
|
+
import { execFile } from "node:child_process";
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { readFile } from "node:fs/promises";
|
|
19
|
+
import { basename, dirname, join } from "node:path";
|
|
20
|
+
import { promisify } from "node:util";
|
|
21
|
+
import {
|
|
22
|
+
Connection,
|
|
23
|
+
LocalExecutionEnv,
|
|
24
|
+
RemoteExecutionEnv,
|
|
25
|
+
acceptHostKey,
|
|
26
|
+
deployDaemon,
|
|
27
|
+
detectPlatform,
|
|
28
|
+
forgetHostKey,
|
|
29
|
+
localDaemon,
|
|
30
|
+
packagedDaemon,
|
|
31
|
+
scanHostKey,
|
|
32
|
+
sshConnection,
|
|
33
|
+
} from "@earendil-works/pi-env";
|
|
34
|
+
import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
|
|
35
|
+
import { BACKGROUND_CONTEXT as CONTEXT } from "@earendil-works/chord/context";
|
|
36
|
+
import { isHostTrusted, resolveEnvTarget, sshTargetFor } from "./config.mjs";
|
|
37
|
+
|
|
38
|
+
const execFileAsync = promisify(execFile);
|
|
39
|
+
|
|
40
|
+
/** pi-env 硬编码的 SSH 安全参数(docker-exec 与远端容器发现共用) */
|
|
41
|
+
const SSH_HARDENING = [
|
|
42
|
+
"-T",
|
|
43
|
+
"-a",
|
|
44
|
+
"-x",
|
|
45
|
+
"-o", "BatchMode=yes",
|
|
46
|
+
"-o", "ClearAllForwardings=yes",
|
|
47
|
+
"-o", "ForwardAgent=no",
|
|
48
|
+
"-o", "StrictHostKeyChecking=yes",
|
|
49
|
+
"-o", "GlobalKnownHostsFile=none",
|
|
50
|
+
"-o", "HashKnownHosts=no",
|
|
51
|
+
"-o", "ConnectTimeout=15",
|
|
52
|
+
"-o", "ServerAliveInterval=15",
|
|
53
|
+
"-o", "ServerAliveCountMax=3",
|
|
54
|
+
"-o", "RemoteCommand=none",
|
|
55
|
+
"-o", "PermitLocalCommand=no",
|
|
56
|
+
"-o", "SendEnv=-*",
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/** POSIX 单引号安全转义 */
|
|
60
|
+
export function shQuote(s) {
|
|
61
|
+
return `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** `docker ps --format '{{.Names}}\t{{.ID}}\t{{.Status}}'` → [{ name, id, status }] */
|
|
65
|
+
function parseDockerPs(out) {
|
|
66
|
+
return out.split("\n")
|
|
67
|
+
.map((l) => l.trim().split("\t"))
|
|
68
|
+
.filter((c) => c.length >= 2 && c[0])
|
|
69
|
+
.map((c) => ({ name: c[0], id: c[1], status: c[2] ?? "" }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export class EnvManager {
|
|
73
|
+
#cfg;
|
|
74
|
+
#dir;
|
|
75
|
+
/** @type {Map<string, {connection: Connection, mode: string}>} envName -> connection */
|
|
76
|
+
#connections = new Map();
|
|
77
|
+
/** @type {Connection | null} 本机共享 localDaemon 连接 */
|
|
78
|
+
#localConn = null;
|
|
79
|
+
/** @type {Map<string, object>} `${envName}\0${cwd}` -> ExecutionEnv */
|
|
80
|
+
#envs = new Map();
|
|
81
|
+
/** @type {Map<string, {PATH:string}|undefined>} 每环境一次的远端 PATH 探测结果 */
|
|
82
|
+
#shellEnv = new Map();
|
|
83
|
+
/** @type {Map<string, string[]>} 最近几条远端连接/启动日志,便于定位 255 等无详情退出 */
|
|
84
|
+
#lastLog = new Map();
|
|
85
|
+
/** @type {Map<string, Promise<void>>} 主机首次自动信任去重锁 */
|
|
86
|
+
#trusting = new Map();
|
|
87
|
+
#onLog;
|
|
88
|
+
|
|
89
|
+
constructor(cfg, dir, { onLog } = {}) {
|
|
90
|
+
this.#cfg = cfg;
|
|
91
|
+
this.#dir = dir;
|
|
92
|
+
this.#onLog = onLog ?? (() => {});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
names() {
|
|
96
|
+
return Object.keys(this.#cfg.environments ?? {});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
hostNames() {
|
|
100
|
+
return Object.keys(this.#cfg.hosts ?? {});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
isContainer(name) {
|
|
104
|
+
const e = this.#cfg.environments?.[name];
|
|
105
|
+
return Boolean(e && (e.runtime === "docker" || e.container));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 替换内存配置并精准逐出变更或已删除的 host / env 缓存 */
|
|
109
|
+
replaceConfig(nextHosts, nextEnvs) {
|
|
110
|
+
const prevHosts = this.#cfg.hosts ?? {};
|
|
111
|
+
const prevEnvs = this.#cfg.environments ?? {};
|
|
112
|
+
const changedHosts = new Set();
|
|
113
|
+
|
|
114
|
+
for (const hName of Object.keys(prevHosts)) {
|
|
115
|
+
if (!nextHosts[hName] || JSON.stringify(nextHosts[hName]) !== JSON.stringify(prevHosts[hName])) {
|
|
116
|
+
changedHosts.add(hName);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
for (const name of Object.keys(prevEnvs)) {
|
|
121
|
+
const prev = prevEnvs[name];
|
|
122
|
+
const next = nextEnvs[name];
|
|
123
|
+
if (!next || JSON.stringify(next) !== JSON.stringify(prev) || changedHosts.has(prev.host) || changedHosts.has(next.host)) {
|
|
124
|
+
this.#evict(name);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (const name of [...this.#connections.keys()]) {
|
|
128
|
+
if (!nextEnvs[name]) this.#evict(name);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
this.#cfg.hosts = nextHosts;
|
|
132
|
+
this.#cfg.environments = nextEnvs;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 兼容旧调用 */
|
|
136
|
+
replaceEnvironments(nextEnvs, nextHosts = this.#cfg.hosts) {
|
|
137
|
+
this.replaceConfig(nextHosts, nextEnvs);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ── 信任(Host Key Pinning,按 Host 粒度)──────────────────────────────────
|
|
141
|
+
async scanTrust(hostOrEnvName) {
|
|
142
|
+
const { target } = sshTargetFor(hostOrEnvName, this.#cfg, this.#dir);
|
|
143
|
+
return scanHostKey(target);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async acceptTrust(hostOrEnvName, lines) {
|
|
147
|
+
const { target, hostName } = sshTargetFor(hostOrEnvName, this.#cfg, this.#dir);
|
|
148
|
+
await acceptHostKey(target, lines);
|
|
149
|
+
this.#evictHost(hostName ?? hostOrEnvName);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async forgetTrust(hostOrEnvName) {
|
|
153
|
+
const { target, hostName } = sshTargetFor(hostOrEnvName, this.#cfg, this.#dir);
|
|
154
|
+
await forgetHostKey(target);
|
|
155
|
+
this.#evictHost(hostName ?? hostOrEnvName);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 列出主机上的 Docker 容器(名称 / ID / 状态),供"添加环境"时校验容器名 */
|
|
159
|
+
async listContainers(hostOrEnvName, { timeoutMs = 20_000 } = {}) {
|
|
160
|
+
const format = "{{.Names}}\t{{.ID}}\t{{.Status}}";
|
|
161
|
+
const out = hostOrEnvName === "local"
|
|
162
|
+
? await this.#execLocal("docker", ["ps", "--format", format], timeoutMs)
|
|
163
|
+
: await this.#sshExec(
|
|
164
|
+
sshTargetFor(hostOrEnvName, this.#cfg, this.#dir).target,
|
|
165
|
+
`docker ps --format '${format}'`,
|
|
166
|
+
timeoutMs,
|
|
167
|
+
);
|
|
168
|
+
return parseDockerPs(out);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// ── 连接管理 ────────────────────────────────────────────────────────────────
|
|
172
|
+
#getLocalConnection() {
|
|
173
|
+
if (this.#localConn) return this.#localConn;
|
|
174
|
+
const daemon = localDaemon();
|
|
175
|
+
this.#localConn = new Connection({ command: [daemon], onLog: (t) => this.#onLog("local", t) });
|
|
176
|
+
return this.#localConn;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** 取得(或建立)某环境的 Connection。local-host 走共享 localDaemon。 */
|
|
180
|
+
connection(name) {
|
|
181
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
182
|
+
if (resolved.mode === "local-host") {
|
|
183
|
+
return this.#getLocalConnection();
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const cached = this.#connections.get(name);
|
|
187
|
+
if (cached) return cached.connection;
|
|
188
|
+
|
|
189
|
+
const { env, target, mode } = resolved;
|
|
190
|
+
const daemonPath = env.daemonPath ?? "/opt/pi-foreman/pi-env";
|
|
191
|
+
const userArgs = env.containerUser ? ["-u", String(env.containerUser)] : [];
|
|
192
|
+
let connection;
|
|
193
|
+
|
|
194
|
+
const log = (t) => {
|
|
195
|
+
this.#appendLog(name, t);
|
|
196
|
+
this.#onLog(name, t);
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
if (mode === "local-docker") {
|
|
200
|
+
const cmd = ["docker", "exec", ...userArgs, "-i", env.container, daemonPath];
|
|
201
|
+
connection = new Connection({ command: cmd, onLog: log });
|
|
202
|
+
} else if (mode === "ssh-docker") {
|
|
203
|
+
const sshProgram = this.#cfg.ssh?.program ?? "ssh";
|
|
204
|
+
const args = [
|
|
205
|
+
sshProgram,
|
|
206
|
+
...this.#sshArgsForTarget(target),
|
|
207
|
+
target.host,
|
|
208
|
+
"docker",
|
|
209
|
+
"exec",
|
|
210
|
+
...userArgs,
|
|
211
|
+
"-i",
|
|
212
|
+
env.container,
|
|
213
|
+
daemonPath,
|
|
214
|
+
];
|
|
215
|
+
connection = new Connection({ command: args, onLog: log });
|
|
216
|
+
} else {
|
|
217
|
+
// ssh-host
|
|
218
|
+
connection = sshConnection({ ...target, onLog: log }).connection;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
this.#connections.set(name, { connection, mode });
|
|
222
|
+
return connection;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** 取得(或建立)某环境下某目录的 ExecutionEnv(同步版,不处理 binDir PATH 探测) */
|
|
226
|
+
env(name, cwd, { sharedFsId } = {}) {
|
|
227
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
228
|
+
const effectiveCwd = cwd || resolved.env.cwd || (resolved.mode === "local-host" ? process.cwd() : "/");
|
|
229
|
+
const key = `${name}\u0000${effectiveCwd}\u0000${sharedFsId ?? ""}`;
|
|
230
|
+
const cached = this.#envs.get(key);
|
|
231
|
+
if (cached) return cached;
|
|
232
|
+
|
|
233
|
+
const { env, hostName, mode, derived } = resolved;
|
|
234
|
+
const fsId = sharedFsId ?? (env.fsGroup
|
|
235
|
+
? `pi-fs:${env.fsGroup}`
|
|
236
|
+
: resolved.runtime === "host"
|
|
237
|
+
? `pi-fs:${hostName}`
|
|
238
|
+
: derived.envId);
|
|
239
|
+
|
|
240
|
+
const probedShellEnv = this.#shellEnv.get(name);
|
|
241
|
+
const mergedShellEnv = {
|
|
242
|
+
...(env.shellEnv ?? {}),
|
|
243
|
+
...(probedShellEnv ?? {}),
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
let execEnv;
|
|
247
|
+
if (mode === "local-host") {
|
|
248
|
+
const localShellEnv = {
|
|
249
|
+
...process.env,
|
|
250
|
+
...mergedShellEnv,
|
|
251
|
+
...(env.binDir && !probedShellEnv ? { PATH: `${env.binDir}:${process.env.PATH ?? ""}` } : {}),
|
|
252
|
+
};
|
|
253
|
+
try {
|
|
254
|
+
execEnv = new LocalExecutionEnv({
|
|
255
|
+
cwd: effectiveCwd,
|
|
256
|
+
connection: this.#getLocalConnection(),
|
|
257
|
+
shellEnv: localShellEnv,
|
|
258
|
+
});
|
|
259
|
+
} catch {
|
|
260
|
+
execEnv = new NodeExecutionEnv({
|
|
261
|
+
cwd: effectiveCwd,
|
|
262
|
+
shellEnv: localShellEnv,
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
// 对齐共享文件系统 id,使 local-host 与挂载同目录的 local-docker 共享写锁
|
|
266
|
+
try {
|
|
267
|
+
Object.defineProperty(execEnv, "id", { value: fsId, enumerable: true, configurable: true });
|
|
268
|
+
} catch { /* 若不可重定义则沿用默认值 */ }
|
|
269
|
+
} else {
|
|
270
|
+
execEnv = new RemoteExecutionEnv({
|
|
271
|
+
connection: this.connection(name),
|
|
272
|
+
id: fsId,
|
|
273
|
+
cwd: effectiveCwd,
|
|
274
|
+
...(Object.keys(mergedShellEnv).length ? { shellEnv: mergedShellEnv } : {}),
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
this.#envs.set(key, execEnv);
|
|
279
|
+
return execEnv;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 异步版:按需首次自动信任 SSH host key + 探测 binDir PATH */
|
|
283
|
+
async envAsync(name, cwd, opts) {
|
|
284
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
285
|
+
if (resolved.target) {
|
|
286
|
+
await this.#ensureTrusted(resolved.hostName, resolved.target);
|
|
287
|
+
}
|
|
288
|
+
if (resolved.env?.binDir && resolved.mode !== "local-host" && !this.#shellEnv.has(name)) {
|
|
289
|
+
await this.#prepareShellEnv(name, cwd || resolved.env.cwd || "/", resolved.env.binDir);
|
|
290
|
+
}
|
|
291
|
+
return this.env(name, cwd, opts);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async #prepareShellEnv(name, cwd, binDir) {
|
|
295
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
296
|
+
const probe = new RemoteExecutionEnv({
|
|
297
|
+
connection: this.connection(name),
|
|
298
|
+
id: resolved.derived.envId,
|
|
299
|
+
cwd,
|
|
300
|
+
});
|
|
301
|
+
let out = "";
|
|
302
|
+
const r = await probe.exec('printf %s "$PATH"', {
|
|
303
|
+
cwd,
|
|
304
|
+
onOutput: (t) => { out += t; },
|
|
305
|
+
timeout: 15,
|
|
306
|
+
}, CONTEXT);
|
|
307
|
+
const remotePath = out.trim();
|
|
308
|
+
if (!r.ok || !remotePath) {
|
|
309
|
+
this.#onLog(name, `无法取得远端 PATH(${r.ok ? "空" : r.error?.message}),跳过 binDir 注入`);
|
|
310
|
+
this.#shellEnv.set(name, undefined);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const already = remotePath.split(":").includes(binDir);
|
|
314
|
+
this.#shellEnv.set(name, { PATH: already ? remotePath : `${binDir}:${remotePath}` });
|
|
315
|
+
this.#onLog(name, `binDir 已注入 PATH: ${binDir}`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// ── 部署(全异步,不阻塞事件循环)──────────────────────────────────────────
|
|
319
|
+
async deploy(name) {
|
|
320
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
321
|
+
const { env, target, mode } = resolved;
|
|
322
|
+
|
|
323
|
+
if (mode === "local-host") {
|
|
324
|
+
const daemon = localDaemon();
|
|
325
|
+
const sha256 = createHash("sha256").update(await readFile(daemon)).digest("hex");
|
|
326
|
+
return { path: daemon, sha256, platform: { platform: process.platform, arch: process.arch }, mode };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (mode === "local-docker") {
|
|
330
|
+
const dest = env.daemonPath ?? "/opt/pi-foreman/pi-env";
|
|
331
|
+
const infoOut = await this.#execLocal(
|
|
332
|
+
"docker",
|
|
333
|
+
["exec", env.container, "sh", "-c", "uname -s && uname -m"],
|
|
334
|
+
30_000,
|
|
335
|
+
);
|
|
336
|
+
const [rawOs, rawArch] = infoOut.trim().split(/\s+/);
|
|
337
|
+
const platform = normalizePlatform(rawOs, rawArch);
|
|
338
|
+
const localBin = packagedDaemon({ platform: platform.platform, arch: platform.arch });
|
|
339
|
+
const sha256 = createHash("sha256").update(await readFile(localBin)).digest("hex");
|
|
340
|
+
const staged = `${dest}.${sha256.slice(0, 12)}.tmp`;
|
|
341
|
+
|
|
342
|
+
await this.#execLocal("docker", ["exec", env.container, "mkdir", "-p", dirOf(dest)], 30_000);
|
|
343
|
+
await this.#execLocal("docker", ["cp", localBin, `${env.container}:${staged}`], 120_000);
|
|
344
|
+
const cShaRaw = await this.#execLocal(
|
|
345
|
+
"docker",
|
|
346
|
+
["exec", env.container, "sh", "-c", `sha256sum ${shQuote(staged)} | cut -d' ' -f1`],
|
|
347
|
+
30_000,
|
|
348
|
+
);
|
|
349
|
+
const cSha = cShaRaw.trim();
|
|
350
|
+
if (cSha !== sha256) throw new Error(`容器内校验失败: ${cSha} != ${sha256}`);
|
|
351
|
+
await this.#execLocal(
|
|
352
|
+
"docker",
|
|
353
|
+
["exec", env.container, "sh", "-c", `chmod 755 ${shQuote(staged)} && mv -f ${shQuote(staged)} ${shQuote(dest)}`],
|
|
354
|
+
30_000,
|
|
355
|
+
);
|
|
356
|
+
return { path: dest, sha256, platform, mode };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ssh-host 或 ssh-docker
|
|
360
|
+
await this.#ensureTrusted(resolved.hostName, target);
|
|
361
|
+
const remote = await detectPlatform(target);
|
|
362
|
+
const localBin = packagedDaemon({ platform: remote.platform, arch: remote.arch });
|
|
363
|
+
const sha256 = createHash("sha256").update(await readFile(localBin)).digest("hex");
|
|
364
|
+
|
|
365
|
+
if (mode === "ssh-host") {
|
|
366
|
+
const path = await deployDaemon(target, remote, localBin);
|
|
367
|
+
return { path, sha256, platform: remote, mode };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// ssh-docker:异步 scp → 宿主机 sha256 → docker cp → 容器内 sha256 → 原子 mv
|
|
371
|
+
const dest = env.daemonPath ?? "/opt/pi-foreman/pi-env";
|
|
372
|
+
const staged = `${dest}.${sha256.slice(0, 12)}.tmp`;
|
|
373
|
+
const hostTmp = `/tmp/pi-env-${sha256.slice(0, 12)}-${process.pid}`;
|
|
374
|
+
const sh = (cmd, ms = 60_000) => this.#sshExec(target, cmd, ms);
|
|
375
|
+
|
|
376
|
+
await this.#scp(localBin, target, hostTmp);
|
|
377
|
+
try {
|
|
378
|
+
const hostSha = (await sh(`sha256sum ${shQuote(hostTmp)} | cut -d' ' -f1`)).trim();
|
|
379
|
+
if (hostSha !== sha256) throw new Error(`宿主机校验失败: ${hostSha} != ${sha256}`);
|
|
380
|
+
|
|
381
|
+
// 用宿主机 root/docker 默认权限 mkdir & chmod,避免 containerUser 无权限写 /opt
|
|
382
|
+
await sh(`docker exec ${shQuote(env.container)} mkdir -p ${shQuote(dirOf(dest))}`);
|
|
383
|
+
await sh(`docker cp ${shQuote(hostTmp)} ${shQuote(`${env.container}:${staged}`)}`, 120_000);
|
|
384
|
+
const cSha = (await sh(`docker exec ${shQuote(env.container)} sh -c ${shQuote(`sha256sum ${shQuote(staged)} | cut -d' ' -f1`)}`)).trim();
|
|
385
|
+
if (cSha !== sha256) throw new Error(`容器内校验失败: ${cSha} != ${sha256}`);
|
|
386
|
+
await sh(`docker exec ${shQuote(env.container)} sh -c ${shQuote(`chmod 755 ${shQuote(staged)} && mv -f ${shQuote(staged)} ${shQuote(dest)}`)}`);
|
|
387
|
+
} finally {
|
|
388
|
+
await sh(`rm -f ${shQuote(hostTmp)}`, 15_000).catch(() => {});
|
|
389
|
+
}
|
|
390
|
+
return { path: dest, sha256, platform: remote, mode };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// ── 健康探测 ────────────────────────────────────────────────────────────────
|
|
394
|
+
async probe(name, { timeoutMs = 5000, cwd } = {}) {
|
|
395
|
+
const t0 = Date.now();
|
|
396
|
+
let mode;
|
|
397
|
+
try {
|
|
398
|
+
const resolved = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
399
|
+
mode = resolved.mode;
|
|
400
|
+
const targetCwd = cwd ?? resolved.env.cwd ?? (mode === "local-host" ? process.cwd() : undefined);
|
|
401
|
+
|
|
402
|
+
if (mode === "local-host") {
|
|
403
|
+
let info = { os: process.platform, arch: process.arch, home: process.env.HOME, cwd: targetCwd, features: ["listFiles"] };
|
|
404
|
+
let connectMs = 0;
|
|
405
|
+
try {
|
|
406
|
+
info = await this.#getLocalConnection().info(AbortSignal.timeout(timeoutMs));
|
|
407
|
+
connectMs = Date.now() - t0;
|
|
408
|
+
} catch {
|
|
409
|
+
connectMs = Date.now() - t0;
|
|
410
|
+
}
|
|
411
|
+
const t1 = Date.now();
|
|
412
|
+
const r = await this.env(name, targetCwd).fileInfo(targetCwd, CONTEXT);
|
|
413
|
+
if (!r.ok) throw new Error(r.error?.message ?? "目录不可达");
|
|
414
|
+
const opMs = Date.now() - t1;
|
|
415
|
+
return { ok: true, info, connectMs, opMs, mode };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (mode === "ssh-host" || mode === "ssh-docker") {
|
|
419
|
+
await this.#ensureTrusted(resolved.hostName, resolved.target);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if (!this.#connections.has(name)) this.#lastLog.delete(name);
|
|
423
|
+
const info = await this.connection(name).info(AbortSignal.timeout(timeoutMs));
|
|
424
|
+
const connectMs = Date.now() - t0;
|
|
425
|
+
let opMs;
|
|
426
|
+
if (targetCwd) {
|
|
427
|
+
const t1 = Date.now();
|
|
428
|
+
const r = await this.env(name, targetCwd).fileInfo(targetCwd, { abortSignal: AbortSignal.timeout(timeoutMs) });
|
|
429
|
+
if (!r.ok) throw new Error(r.error?.message ?? r.error?.code ?? "工作目录探测失败");
|
|
430
|
+
opMs = Date.now() - t1;
|
|
431
|
+
}
|
|
432
|
+
return { ok: true, info, connectMs, opMs, mode };
|
|
433
|
+
} catch (error) {
|
|
434
|
+
const rawMsg = describeError(error);
|
|
435
|
+
if (mode === "ssh-host" || mode === "ssh-docker") {
|
|
436
|
+
try {
|
|
437
|
+
const { hostName, target } = resolveEnvTarget(name, this.#cfg, this.#dir);
|
|
438
|
+
const logs = this.#lastLog.get(name) ?? [];
|
|
439
|
+
if (/HostKeyChangedError|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(rawMsg)
|
|
440
|
+
|| logs.some((l) => /REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(l))) {
|
|
441
|
+
return {
|
|
442
|
+
ok: false,
|
|
443
|
+
error: `主机 ${target.host} 的 SSH 密钥已变更,请确认主机安全后点击“重置密钥”或运行 foreman trust ${hostName} --reset`,
|
|
444
|
+
ms: Date.now() - t0,
|
|
445
|
+
mode,
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
const trusted = isHostTrusted(target);
|
|
449
|
+
if (!trusted && /is not trusted yet|exited with code 255|Host key verification failed/i.test(rawMsg)) {
|
|
450
|
+
return {
|
|
451
|
+
ok: false,
|
|
452
|
+
error: `主机 ${target.host} 尚未信任 host key,请点击“信任密钥”或运行: foreman trust ${hostName}`,
|
|
453
|
+
ms: Date.now() - t0,
|
|
454
|
+
mode,
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
if (mode === "ssh-docker" && /exited with code 255/i.test(rawMsg)) {
|
|
458
|
+
const hint =
|
|
459
|
+
logs.find((l) => /REMOTE HOST IDENTIFICATION HAS CHANGED|Host key verification failed|Permission denied|No such container|docker: command not found|not running/i.test(l))
|
|
460
|
+
?? logs[logs.length - 1];
|
|
461
|
+
if (hint) {
|
|
462
|
+
return {
|
|
463
|
+
ok: false,
|
|
464
|
+
error: `ssh-docker 连接失败 (exit 255): ${hint}`,
|
|
465
|
+
ms: Date.now() - t0,
|
|
466
|
+
mode,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
} catch { /* 回退到原始错误 */ }
|
|
471
|
+
}
|
|
472
|
+
return { ok: false, error: rawMsg, ms: Date.now() - t0, mode };
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async closeAll() {
|
|
477
|
+
for (const name of [...this.#connections.keys()]) this.#evict(name);
|
|
478
|
+
if (this.#localConn) {
|
|
479
|
+
try { this.#localConn.close(); } catch { /* ignore */ }
|
|
480
|
+
this.#localConn = null;
|
|
481
|
+
}
|
|
482
|
+
this.#envs.clear();
|
|
483
|
+
this.#shellEnv.clear();
|
|
484
|
+
this.#lastLog.clear();
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// ── 内部工具 ────────────────────────────────────────────────────────────────
|
|
488
|
+
async #ensureTrusted(hostName, target) {
|
|
489
|
+
if (!target || this.#cfg.ssh?.autoTrust === false) return;
|
|
490
|
+
if (isHostTrusted(target)) return;
|
|
491
|
+
const inflight = this.#trusting.get(hostName);
|
|
492
|
+
if (inflight) return inflight;
|
|
493
|
+
const task = (async () => {
|
|
494
|
+
const scan = await scanHostKey(target);
|
|
495
|
+
await acceptHostKey(target, scan.lines);
|
|
496
|
+
this.#evictHost(hostName);
|
|
497
|
+
this.#onLog(hostName, `首次连接自动信任 SSH host key (${target.host})`);
|
|
498
|
+
})().finally(() => {
|
|
499
|
+
if (this.#trusting.get(hostName) === task) this.#trusting.delete(hostName);
|
|
500
|
+
});
|
|
501
|
+
this.#trusting.set(hostName, task);
|
|
502
|
+
return task;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
#appendLog(name, chunk) {
|
|
506
|
+
const lines = String(chunk ?? "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
507
|
+
if (lines.length === 0) return;
|
|
508
|
+
const prev = this.#lastLog.get(name) ?? [];
|
|
509
|
+
this.#lastLog.set(name, prev.concat(lines).slice(-10));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
#evictHost(hostName) {
|
|
513
|
+
for (const [envName, e] of Object.entries(this.#cfg.environments ?? {})) {
|
|
514
|
+
if (e?.host === hostName) this.#evict(envName);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
#evict(name) {
|
|
519
|
+
const cached = this.#connections.get(name);
|
|
520
|
+
if (cached) {
|
|
521
|
+
try { cached.connection.close(); } catch (e) { this.#onLog(name, `close 失败: ${e.message}`); }
|
|
522
|
+
this.#connections.delete(name);
|
|
523
|
+
}
|
|
524
|
+
const prefix = `${name}\u0000`;
|
|
525
|
+
for (const key of [...this.#envs.keys()]) if (key.startsWith(prefix)) this.#envs.delete(key);
|
|
526
|
+
this.#shellEnv.delete(name);
|
|
527
|
+
this.#lastLog.delete(name);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
#sshArgsForTarget(target) {
|
|
531
|
+
const args = [
|
|
532
|
+
...SSH_HARDENING,
|
|
533
|
+
"-o", `UserKnownHostsFile=${target.knownHostsFile}`,
|
|
534
|
+
"-o", `HostKeyAlias=${target.hostKeyAlias}`,
|
|
535
|
+
];
|
|
536
|
+
if (target.user) args.push("-l", target.user);
|
|
537
|
+
if (target.port) args.push("-p", String(target.port));
|
|
538
|
+
if (target.identityFile) args.push("-i", target.identityFile, "-o", "IdentitiesOnly=yes");
|
|
539
|
+
if (target.configFile) args.push("-F", target.configFile);
|
|
540
|
+
args.push("--");
|
|
541
|
+
return args;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
async #execLocal(bin, args, timeoutMs = 30_000) {
|
|
545
|
+
try {
|
|
546
|
+
const { stdout } = await execFileAsync(bin, args, {
|
|
547
|
+
encoding: "utf8",
|
|
548
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
549
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
550
|
+
});
|
|
551
|
+
return stdout;
|
|
552
|
+
} catch (e) {
|
|
553
|
+
const detail = e.stderr || e.stdout || e.message;
|
|
554
|
+
throw new Error(`${bin} ${args[0] ?? ""} 失败: ${String(detail).trim()}`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async #sshExec(target, command, timeoutMs = 120_000) {
|
|
559
|
+
const program = this.#cfg.ssh?.program ?? "ssh";
|
|
560
|
+
const args = [...this.#sshArgsForTarget(target), target.host, command];
|
|
561
|
+
try {
|
|
562
|
+
const { stdout } = await execFileAsync(program, args, {
|
|
563
|
+
encoding: "utf8",
|
|
564
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
565
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
566
|
+
});
|
|
567
|
+
return stdout;
|
|
568
|
+
} catch (e) {
|
|
569
|
+
const detail = e.stderr || e.stdout || e.message;
|
|
570
|
+
throw new Error(`ssh 执行失败: ${command}\n${String(detail).trim()}`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async #scp(localPath, target, remotePath, timeoutMs = 300_000) {
|
|
575
|
+
const sshProg = this.#cfg.ssh?.program;
|
|
576
|
+
let scpProgram = "scp";
|
|
577
|
+
if (sshProg) {
|
|
578
|
+
const base = basename(sshProg);
|
|
579
|
+
scpProgram = base === "ssh" ? join(dirname(sshProg), "scp") : sshProg.replace(/ssh$/, "scp");
|
|
580
|
+
if (scpProgram === sshProg) scpProgram = "scp";
|
|
581
|
+
}
|
|
582
|
+
const args = [
|
|
583
|
+
"-o", "BatchMode=yes",
|
|
584
|
+
"-o", "StrictHostKeyChecking=yes",
|
|
585
|
+
"-o", `UserKnownHostsFile=${target.knownHostsFile}`,
|
|
586
|
+
"-o", `HostKeyAlias=${target.hostKeyAlias}`,
|
|
587
|
+
];
|
|
588
|
+
if (target.port) args.push("-P", String(target.port));
|
|
589
|
+
if (target.identityFile) args.push("-i", target.identityFile, "-o", "IdentitiesOnly=yes");
|
|
590
|
+
if (target.configFile) args.push("-F", target.configFile);
|
|
591
|
+
const user = target.user ? `${target.user}@` : "";
|
|
592
|
+
args.push(localPath, `${user}${target.host}:${remotePath}`);
|
|
593
|
+
try {
|
|
594
|
+
await execFileAsync(scpProgram, args, {
|
|
595
|
+
encoding: "utf8",
|
|
596
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
597
|
+
});
|
|
598
|
+
} catch (e) {
|
|
599
|
+
const detail = e.stderr || e.stdout || e.message;
|
|
600
|
+
throw new Error(`scp 失败: ${String(detail).trim()}`);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function normalizePlatform(osRaw, archRaw) {
|
|
606
|
+
const os = String(osRaw ?? "").toLowerCase().includes("darwin") ? "darwin" : "linux";
|
|
607
|
+
const a = String(archRaw ?? "").toLowerCase();
|
|
608
|
+
const arch = (a === "aarch64" || a === "arm64") ? "arm64" : "x64";
|
|
609
|
+
return { platform: os, arch };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function dirOf(p) {
|
|
613
|
+
const i = p.lastIndexOf("/");
|
|
614
|
+
return i <= 0 ? "/" : p.slice(0, i);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
export function describeError(error) {
|
|
618
|
+
const name = error?.constructor?.name ?? "Error";
|
|
619
|
+
const code = error?.code ? ` [${error.code}]` : "";
|
|
620
|
+
return `${name}${code}: ${String(error?.message ?? error).split("\n")[0]}`;
|
|
621
|
+
}
|