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/config.mjs
ADDED
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配置与路径解析(v2:Host → Environment 两层模型 + 自动迁移 v1)。
|
|
3
|
+
*
|
|
4
|
+
* 原则:
|
|
5
|
+
* - 唯一和机器绑定的值是 homedir(),且可用 PI_FOREMAN_DATA_DIR 覆盖
|
|
6
|
+
* - 能派生的绝不写进配置文件:knownHostsFile / hostKeyAlias / envId / daemon 路径
|
|
7
|
+
* - 配置文件里不存任何凭据(凭据走 ~/.pi/agent/auth.json)
|
|
8
|
+
* - 所有本地路径必须是【绝对路径】:pi-env 不做 ~ 展开
|
|
9
|
+
*/
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { basename, dirname, join, isAbsolute, resolve } from "node:path";
|
|
12
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync } from "node:fs";
|
|
13
|
+
|
|
14
|
+
export const ENV_VAR_DATA_DIR = "PI_FOREMAN_DATA_DIR";
|
|
15
|
+
export const ENV_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
16
|
+
|
|
17
|
+
/** 应用数据目录。POSIX 下应设 0700。 */
|
|
18
|
+
export function dataDir() {
|
|
19
|
+
const override = process.env[ENV_VAR_DATA_DIR];
|
|
20
|
+
const dir = override ? resolve(override) : join(homedir(), ".pi", "pi-foreman");
|
|
21
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
22
|
+
return dir;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function paths(dir = dataDir()) {
|
|
26
|
+
return {
|
|
27
|
+
dataDir: dir,
|
|
28
|
+
config: join(dir, "config.json"),
|
|
29
|
+
sessionDb: join(dir, "session.sqlite"),
|
|
30
|
+
sshDir: join(dir, "ssh"),
|
|
31
|
+
knownHosts: join(dir, "ssh", "known_hosts"),
|
|
32
|
+
keysDir: join(dir, "ssh", "keys"),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 每个 Host 派生出的、不进配置文件的值(同宿主机的容器共享同一份信任锚) */
|
|
37
|
+
export function deriveHost(hostName, dir = dataDir()) {
|
|
38
|
+
if (!ENV_NAME_PATTERN.test(hostName)) {
|
|
39
|
+
throw new Error(`主机名 "${hostName}" 非法:必须匹配 ${ENV_NAME_PATTERN}`);
|
|
40
|
+
}
|
|
41
|
+
const p = paths(dir);
|
|
42
|
+
return {
|
|
43
|
+
name: hostName,
|
|
44
|
+
knownHostsFile: p.knownHosts,
|
|
45
|
+
hostKeyAlias: `pi-foreman-host-${hostName}`,
|
|
46
|
+
identityFile: join(p.keysDir, hostName),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 每个 Environment 派生出的值 */
|
|
51
|
+
export function deriveEnv(envName, envCfg, dir = dataDir()) {
|
|
52
|
+
if (!ENV_NAME_PATTERN.test(envName)) {
|
|
53
|
+
throw new Error(`环境名 "${envName}" 非法:必须匹配 ${ENV_NAME_PATTERN}`);
|
|
54
|
+
}
|
|
55
|
+
const hostName = envCfg?.host ?? envName;
|
|
56
|
+
return {
|
|
57
|
+
name: envName,
|
|
58
|
+
hostName,
|
|
59
|
+
envId: envCfg?.fsGroup ? `pi-fs:${envCfg.fsGroup}` : `pi-env:${envName}`,
|
|
60
|
+
...deriveHost(hostName, dir),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const DEFAULT_PEER = Object.freeze({
|
|
65
|
+
allowAgentTool: true,
|
|
66
|
+
maxDepth: 2,
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const DEFAULTS = Object.freeze({
|
|
70
|
+
version: 2,
|
|
71
|
+
ssh: { program: null, configFile: null, autoTrust: true },
|
|
72
|
+
proxy: { http: null, https: null, noProxy: null },
|
|
73
|
+
defaultModel: { provider: null, modelId: null },
|
|
74
|
+
providerExtensions: [],
|
|
75
|
+
peer: { ...DEFAULT_PEER },
|
|
76
|
+
harness: { settings: null },
|
|
77
|
+
hosts: { local: { type: "local" } },
|
|
78
|
+
environments: {},
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
/** 把 v1 扁平 config 自动转成 v2(合并重复 SSH host) */
|
|
82
|
+
export function migrateV1ToV2(raw) {
|
|
83
|
+
const hosts = { local: { type: "local" } };
|
|
84
|
+
const environments = {};
|
|
85
|
+
const sshHostMap = new Map();
|
|
86
|
+
|
|
87
|
+
for (const [name, e] of Object.entries(raw?.environments ?? {})) {
|
|
88
|
+
if (!e || typeof e !== "object") continue;
|
|
89
|
+
if (e.type === "local") {
|
|
90
|
+
environments[name] = {
|
|
91
|
+
host: "local",
|
|
92
|
+
runtime: e.container ? "docker" : "host",
|
|
93
|
+
...(e.container ? { container: e.container } : {}),
|
|
94
|
+
...(e.containerUser ? { containerUser: e.containerUser } : {}),
|
|
95
|
+
...(e.daemonPath ? { daemonPath: e.daemonPath } : {}),
|
|
96
|
+
...(e.cwd ? { cwd: e.cwd } : {}),
|
|
97
|
+
...(e.binDir ? { binDir: e.binDir } : {}),
|
|
98
|
+
...(e.shellEnv ? { shellEnv: e.shellEnv } : {}),
|
|
99
|
+
};
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ssh 类型:把相同 (host, user, port, identityFile) 的合并到同一个 Host
|
|
104
|
+
const sig = JSON.stringify([e.host, e.user ?? null, e.port ?? null, e.identityFile ?? null]);
|
|
105
|
+
let hostName = sshHostMap.get(sig);
|
|
106
|
+
if (!hostName) {
|
|
107
|
+
hostName = !e.container && ENV_NAME_PATTERN.test(name) ? name : makeUniqueHostName(e.host || name, hosts);
|
|
108
|
+
hosts[hostName] = {
|
|
109
|
+
type: "ssh",
|
|
110
|
+
host: e.host,
|
|
111
|
+
...(e.user ? { user: e.user } : {}),
|
|
112
|
+
...(e.port ? { port: e.port } : {}),
|
|
113
|
+
...(e.identityFile ? { identityFile: e.identityFile } : {}),
|
|
114
|
+
};
|
|
115
|
+
sshHostMap.set(sig, hostName);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
environments[name] = {
|
|
119
|
+
host: hostName,
|
|
120
|
+
runtime: e.container ? "docker" : "host",
|
|
121
|
+
...(e.container ? { container: e.container } : {}),
|
|
122
|
+
...(e.containerUser ? { containerUser: e.containerUser } : {}),
|
|
123
|
+
...(e.daemonPath ? { daemonPath: e.daemonPath } : {}),
|
|
124
|
+
...(e.cwd ? { cwd: e.cwd } : {}),
|
|
125
|
+
...(e.binDir ? { binDir: e.binDir } : {}),
|
|
126
|
+
...(e.shellEnv ? { shellEnv: e.shellEnv } : {}),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const defaultModel = {
|
|
131
|
+
provider: raw?.model?.provider ?? null,
|
|
132
|
+
modelId: raw?.model?.modelId ?? null,
|
|
133
|
+
};
|
|
134
|
+
const _legacyProviderModule = raw?.model?.providerModule
|
|
135
|
+
? { providerModule: raw.model.providerModule, providerExport: raw.model.providerExport ?? null }
|
|
136
|
+
: undefined;
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
...structuredClone(DEFAULTS),
|
|
140
|
+
ssh: { ...DEFAULTS.ssh, ...(raw.ssh ?? {}) },
|
|
141
|
+
proxy: { ...DEFAULTS.proxy, ...(raw.proxy ?? {}) },
|
|
142
|
+
defaultModel,
|
|
143
|
+
...(_legacyProviderModule ? { _legacyProviderModule } : {}),
|
|
144
|
+
harness: { settings: raw.harness?.settings ?? null },
|
|
145
|
+
hosts,
|
|
146
|
+
environments,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function makeUniqueHostName(base, hosts) {
|
|
151
|
+
const clean = String(base ?? "host")
|
|
152
|
+
.toLowerCase()
|
|
153
|
+
.replace(/[^a-z0-9_-]+/g, "-")
|
|
154
|
+
.replace(/^[^a-z0-9]+/, "")
|
|
155
|
+
.slice(0, 24) || "host";
|
|
156
|
+
if (!hosts[clean]) return clean;
|
|
157
|
+
for (let i = 2; i < 100; i++) {
|
|
158
|
+
const candidate = `${clean.slice(0, 28)}-${i}`;
|
|
159
|
+
if (!hosts[candidate]) return candidate;
|
|
160
|
+
}
|
|
161
|
+
return `host-${Date.now().toString(36)}`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 判断某个 target(hostKeyAlias + knownHostsFile)是否已被信任 */
|
|
165
|
+
export function isHostTrusted(target) {
|
|
166
|
+
if (!target?.knownHostsFile || !target?.hostKeyAlias) return false;
|
|
167
|
+
if (!existsSync(target.knownHostsFile)) return false;
|
|
168
|
+
try {
|
|
169
|
+
const content = readFileSync(target.knownHostsFile, "utf8");
|
|
170
|
+
const alias = target.hostKeyAlias;
|
|
171
|
+
return content.split("\n").some((line) => {
|
|
172
|
+
const first = line.trim().split(/\s+/)[0] ?? "";
|
|
173
|
+
return first === alias || first.split(",").includes(alias);
|
|
174
|
+
});
|
|
175
|
+
} catch {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 将 v1 按环境保存的 known_hosts 条目(pi-foreman-<env>)迁移并补充为 v2 按主机别名保存的条目(pi-foreman-host-<host>)。
|
|
182
|
+
* 只做增量克隆,不删除原有条目。
|
|
183
|
+
*/
|
|
184
|
+
export function migrateKnownHostsForV2(cfg, dir = dataDir()) {
|
|
185
|
+
const khFile = paths(dir).knownHosts;
|
|
186
|
+
if (!existsSync(khFile)) return false;
|
|
187
|
+
const sshHosts = Object.entries(cfg?.hosts ?? {}).filter(([, h]) => h?.type === "ssh");
|
|
188
|
+
if (sshHosts.length === 0) return false;
|
|
189
|
+
|
|
190
|
+
const rawLines = readFileSync(khFile, "utf8").split("\n").filter((l) => l.trim() !== "");
|
|
191
|
+
if (rawLines.length === 0) return false;
|
|
192
|
+
|
|
193
|
+
const lineSet = new Set(rawLines);
|
|
194
|
+
const appended = [];
|
|
195
|
+
|
|
196
|
+
const firstTokenHosts = (line) => (line.trim().split(/\s+/)[0] ?? "").split(",").filter(Boolean);
|
|
197
|
+
|
|
198
|
+
for (const [hostName] of sshHosts) {
|
|
199
|
+
const targetAlias = deriveHost(hostName, dir).hostKeyAlias;
|
|
200
|
+
const alreadyTrusted = rawLines.some((l) => firstTokenHosts(l).includes(targetAlias));
|
|
201
|
+
if (alreadyTrusted) continue;
|
|
202
|
+
|
|
203
|
+
const legacyAliases = new Set([`pi-foreman-${hostName}`]);
|
|
204
|
+
for (const [envName, e] of Object.entries(cfg?.environments ?? {})) {
|
|
205
|
+
if (e?.host === hostName) legacyAliases.add(`pi-foreman-${envName}`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
for (const line of rawLines) {
|
|
209
|
+
const trimmed = line.trim();
|
|
210
|
+
const m = trimmed.match(/^(\S+)(\s+.+)$/);
|
|
211
|
+
if (!m) continue;
|
|
212
|
+
const hostsField = m[1].split(",");
|
|
213
|
+
if (!hostsField.some((h) => legacyAliases.has(h))) continue;
|
|
214
|
+
const cloned = `${targetAlias}${m[2]}`;
|
|
215
|
+
if (!lineSet.has(cloned)) {
|
|
216
|
+
lineSet.add(cloned);
|
|
217
|
+
appended.push(cloned);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (appended.length === 0) return false;
|
|
223
|
+
const all = [...rawLines, ...appended];
|
|
224
|
+
const tmp = `${khFile}.${process.pid}.tmp`;
|
|
225
|
+
writeFileSync(tmp, `${all.join("\n")}\n`, { mode: 0o600 });
|
|
226
|
+
renameSync(tmp, khFile);
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function loadConfig(dir = dataDir()) {
|
|
231
|
+
const file = paths(dir).config;
|
|
232
|
+
if (!existsSync(file)) return structuredClone(DEFAULTS);
|
|
233
|
+
const raw = JSON.parse(readFileSync(file, "utf8"));
|
|
234
|
+
let cfg;
|
|
235
|
+
if ((raw.version ?? 1) < 2 && !raw.hosts) {
|
|
236
|
+
cfg = migrateV1ToV2(raw);
|
|
237
|
+
} else {
|
|
238
|
+
const hosts = { local: { type: "local" }, ...(raw.hosts ?? {}) };
|
|
239
|
+
cfg = {
|
|
240
|
+
...structuredClone(DEFAULTS),
|
|
241
|
+
...raw,
|
|
242
|
+
version: 2,
|
|
243
|
+
ssh: { ...DEFAULTS.ssh, ...(raw.ssh ?? {}) },
|
|
244
|
+
proxy: { ...DEFAULTS.proxy, ...(raw.proxy ?? {}) },
|
|
245
|
+
defaultModel: {
|
|
246
|
+
provider: raw.defaultModel?.provider ?? raw.model?.provider ?? null,
|
|
247
|
+
modelId: raw.defaultModel?.modelId ?? raw.model?.modelId ?? null,
|
|
248
|
+
},
|
|
249
|
+
providerExtensions: Array.isArray(raw.providerExtensions) ? raw.providerExtensions : [],
|
|
250
|
+
peer: { ...DEFAULT_PEER, ...(raw.peer ?? {}) },
|
|
251
|
+
harness: { settings: raw.harness?.settings ?? null },
|
|
252
|
+
hosts,
|
|
253
|
+
environments: { ...(raw.environments ?? {}) },
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
validateConfig(cfg);
|
|
257
|
+
try {
|
|
258
|
+
migrateKnownHostsForV2(cfg, dir);
|
|
259
|
+
} catch { /* 忽略权限不足等非致命迁移失败 */ }
|
|
260
|
+
return cfg;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function validateConfig(cfg) {
|
|
264
|
+
const errors = [];
|
|
265
|
+
const hosts = cfg.hosts ?? {};
|
|
266
|
+
for (const [hName, h] of Object.entries(hosts)) {
|
|
267
|
+
if (!ENV_NAME_PATTERN.test(hName)) errors.push(`主机名 "${hName}" 非法`);
|
|
268
|
+
if (!h || (h.type !== "local" && h.type !== "ssh")) {
|
|
269
|
+
errors.push(`host ${hName}: type 必须是 "local" 或 "ssh"`);
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (h.type === "ssh") {
|
|
273
|
+
if (!h.host || typeof h.host !== "string") errors.push(`host ${hName}: ssh 主机必须有 host`);
|
|
274
|
+
if (h.port !== undefined && (!Number.isInteger(h.port) || h.port < 1 || h.port > 65535)) {
|
|
275
|
+
errors.push(`host ${hName}: port 必须是 1-65535 的整数`);
|
|
276
|
+
}
|
|
277
|
+
if (h.identityFile && !isAbsolute(h.identityFile)) {
|
|
278
|
+
errors.push(`host ${hName}: identityFile 必须是绝对路径(pi-env 不展开 ~)`);
|
|
279
|
+
}
|
|
280
|
+
if (h.identityFile?.includes("%")) {
|
|
281
|
+
errors.push(`host ${hName}: identityFile 不能含 %(ssh 会展开 token)`);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
for (const [name, env] of Object.entries(cfg.environments ?? {})) {
|
|
287
|
+
if (!ENV_NAME_PATTERN.test(name)) errors.push(`环境名 "${name}" 非法`);
|
|
288
|
+
if (!env || typeof env !== "object") {
|
|
289
|
+
errors.push(`${name}: 环境配置必须是对象`);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
if (!env.host || typeof env.host !== "string" || !hosts[env.host]) {
|
|
293
|
+
errors.push(`${name}: host "${env.host ?? ""}" 不存在`);
|
|
294
|
+
}
|
|
295
|
+
const runtime = env.runtime ?? (env.container ? "docker" : "host");
|
|
296
|
+
if (runtime !== "host" && runtime !== "docker") {
|
|
297
|
+
errors.push(`${name}: runtime 必须是 "host" 或 "docker"`);
|
|
298
|
+
}
|
|
299
|
+
if (runtime === "docker" && (!env.container || typeof env.container !== "string")) {
|
|
300
|
+
errors.push(`${name}: docker 环境必须指定 container`);
|
|
301
|
+
}
|
|
302
|
+
if (env.container !== undefined && typeof env.container !== "string") {
|
|
303
|
+
errors.push(`${name}: container 必须是字符串`);
|
|
304
|
+
}
|
|
305
|
+
if (env.containerUser !== undefined && !/^\d+(:\d+)?$/.test(String(env.containerUser))) {
|
|
306
|
+
errors.push(`${name}: containerUser 必须是 "uid" 或 "uid:gid"(例如 "1130:1130")`);
|
|
307
|
+
}
|
|
308
|
+
if (env.binDir !== undefined && typeof env.binDir !== "string") errors.push(`${name}: binDir 必须是字符串`);
|
|
309
|
+
if (env.fsGroup !== undefined && typeof env.fsGroup !== "string") errors.push(`${name}: fsGroup 必须是字符串`);
|
|
310
|
+
if (env.description !== undefined && typeof env.description !== "string") errors.push(`${name}: description 必须是字符串`);
|
|
311
|
+
if (env.shellEnv !== undefined && (typeof env.shellEnv !== "object" || env.shellEnv === null)) {
|
|
312
|
+
errors.push(`${name}: shellEnv 必须是对象`);
|
|
313
|
+
}
|
|
314
|
+
if (env.workspaces !== undefined) {
|
|
315
|
+
if (!Array.isArray(env.workspaces)) {
|
|
316
|
+
errors.push(`${name}: workspaces 必须是数组`);
|
|
317
|
+
} else {
|
|
318
|
+
for (const ws of env.workspaces) {
|
|
319
|
+
if (!ws || typeof ws !== "object" || !ws.cwd || typeof ws.cwd !== "string") {
|
|
320
|
+
errors.push(`${name}: workspace 必须包含字符串类型的 cwd`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
for (const f of ["provider", "modelId"]) {
|
|
328
|
+
if (cfg.defaultModel?.[f] !== undefined && cfg.defaultModel[f] !== null && typeof cfg.defaultModel[f] !== "string") {
|
|
329
|
+
errors.push(`defaultModel.${f} 必须是字符串`);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (errors.length) throw new Error(`配置校验失败:\n - ${errors.join("\n - ")}`);
|
|
334
|
+
return cfg;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
export const HOST_WRITABLE_FIELDS = Object.freeze([
|
|
338
|
+
"type", "host", "user", "port", "identityFile",
|
|
339
|
+
]);
|
|
340
|
+
|
|
341
|
+
export const ENV_WRITABLE_FIELDS = Object.freeze([
|
|
342
|
+
"host", "runtime", "container", "containerUser", "daemonPath",
|
|
343
|
+
"cwd", "binDir", "shellEnv", "fsGroup", "description", "workspaces",
|
|
344
|
+
]);
|
|
345
|
+
|
|
346
|
+
export function normalizeWorkspaceCwd(cwd) {
|
|
347
|
+
const raw = String(cwd ?? "").trim();
|
|
348
|
+
if (!raw) return "";
|
|
349
|
+
if (raw === "/") return "/";
|
|
350
|
+
return raw.replace(/\/+$/, "") || "/";
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function uniqStrings(arr) {
|
|
354
|
+
if (!Array.isArray(arr)) return undefined;
|
|
355
|
+
const clean = [...new Set(arr.map((x) => String(x ?? "").trim()).filter(Boolean))];
|
|
356
|
+
return clean.length > 0 ? clean : undefined;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
export function normalizeWorkspaceInput(input) {
|
|
360
|
+
const cwd = normalizeWorkspaceCwd(input?.cwd);
|
|
361
|
+
if (!cwd) throw new Error("目录路径 cwd 必填");
|
|
362
|
+
const ws = { cwd };
|
|
363
|
+
if (typeof input?.name === "string" && input.name.trim()) ws.name = input.name.trim();
|
|
364
|
+
if (input?.model?.provider && input?.model?.modelId) {
|
|
365
|
+
ws.model = { provider: String(input.model.provider).trim(), modelId: String(input.model.modelId).trim() };
|
|
366
|
+
}
|
|
367
|
+
if (typeof input?.thinkingLevel === "string" && input.thinkingLevel.trim()) {
|
|
368
|
+
ws.thinkingLevel = input.thinkingLevel.trim();
|
|
369
|
+
}
|
|
370
|
+
const skills = uniqStrings(input?.skills);
|
|
371
|
+
if (skills) ws.skills = skills;
|
|
372
|
+
const disabledSkills = uniqStrings(input?.disabledSkills);
|
|
373
|
+
if (disabledSkills) ws.disabledSkills = disabledSkills;
|
|
374
|
+
if (typeof input?.instructions === "string" && input.instructions.trim()) {
|
|
375
|
+
ws.instructions = input.instructions.trim();
|
|
376
|
+
}
|
|
377
|
+
return ws;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function getEnvWorkspaces(cfg, envName) {
|
|
381
|
+
const env = cfg?.environments?.[envName];
|
|
382
|
+
if (!env) return [];
|
|
383
|
+
const configured = Array.isArray(env.workspaces)
|
|
384
|
+
? env.workspaces.filter((w) => w?.cwd).map((w) => normalizeWorkspaceInput(w))
|
|
385
|
+
: [];
|
|
386
|
+
if (configured.length > 0) return configured;
|
|
387
|
+
if (env.cwd) {
|
|
388
|
+
const c = normalizeWorkspaceCwd(env.cwd);
|
|
389
|
+
const seg = c === "/" ? "/" : (c.split("/").filter(Boolean).pop() ?? c);
|
|
390
|
+
return [{ cwd: c, name: seg, implicit: true }];
|
|
391
|
+
}
|
|
392
|
+
return [];
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export function resolveWorkspaceFor(cfg, envName, cwd) {
|
|
396
|
+
const env = cfg?.environments?.[envName];
|
|
397
|
+
if (!env || !Array.isArray(env.workspaces) || env.workspaces.length === 0) return null;
|
|
398
|
+
const target = normalizeWorkspaceCwd(cwd || env.cwd);
|
|
399
|
+
if (!target) return null;
|
|
400
|
+
const normalized = env.workspaces.filter((w) => w?.cwd).map((w) => normalizeWorkspaceInput(w));
|
|
401
|
+
const exact = normalized.find((w) => w.cwd === target);
|
|
402
|
+
if (exact) return exact;
|
|
403
|
+
let best = null;
|
|
404
|
+
for (const w of normalized) {
|
|
405
|
+
const prefix = w.cwd === "/" ? "/" : `${w.cwd}/`;
|
|
406
|
+
if (target.startsWith(prefix) && (!best || w.cwd.length > best.cwd.length)) {
|
|
407
|
+
best = w;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return best;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function expandTilde(p) {
|
|
414
|
+
const raw = String(p ?? "");
|
|
415
|
+
if (raw === "~") return homedir();
|
|
416
|
+
if (raw.startsWith("~/")) return join(homedir(), raw.slice(2));
|
|
417
|
+
return raw;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
export function normalizeHostInput(input) {
|
|
421
|
+
const h = {};
|
|
422
|
+
for (const key of HOST_WRITABLE_FIELDS) {
|
|
423
|
+
const value = input?.[key];
|
|
424
|
+
if (value === undefined || value === null || value === "") continue;
|
|
425
|
+
if (key === "port") {
|
|
426
|
+
const n = Number(value);
|
|
427
|
+
if (Number.isFinite(n)) h.port = n;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const trimmed = String(value).trim();
|
|
431
|
+
h[key] = key === "identityFile" ? expandTilde(trimmed) : trimmed;
|
|
432
|
+
}
|
|
433
|
+
if (!h.type) h.type = h.host ? "ssh" : "local";
|
|
434
|
+
return h;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function normalizeEnvInput(input) {
|
|
438
|
+
const env = {};
|
|
439
|
+
for (const key of ENV_WRITABLE_FIELDS) {
|
|
440
|
+
const value = input?.[key];
|
|
441
|
+
if (value === undefined || value === null || value === "") continue;
|
|
442
|
+
if (key === "shellEnv") {
|
|
443
|
+
if (typeof value !== "object" || Array.isArray(value)) throw new Error("shellEnv 必须是对象");
|
|
444
|
+
const clean = {};
|
|
445
|
+
for (const [k, v] of Object.entries(value)) {
|
|
446
|
+
if (v === null || v === undefined || v === "") continue;
|
|
447
|
+
clean[String(k)] = String(v);
|
|
448
|
+
}
|
|
449
|
+
if (Object.keys(clean).length) env.shellEnv = clean;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
if (key === "workspaces") {
|
|
453
|
+
if (!Array.isArray(value)) throw new Error("workspaces 必须是数组");
|
|
454
|
+
const clean = value.map((w) => normalizeWorkspaceInput(w));
|
|
455
|
+
if (clean.length) env.workspaces = clean;
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
env[key] = String(value).trim();
|
|
459
|
+
}
|
|
460
|
+
if (!env.runtime) env.runtime = env.container ? "docker" : "host";
|
|
461
|
+
return env;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
export function upsertWorkspace(cfg, envName, wsInput, dir = dataDir()) {
|
|
465
|
+
const existingEnv = cfg?.environments?.[envName];
|
|
466
|
+
if (!existingEnv) throw new Error(`未知环境: ${envName}`);
|
|
467
|
+
const ws = normalizeWorkspaceInput(wsInput);
|
|
468
|
+
const current = Array.isArray(existingEnv.workspaces)
|
|
469
|
+
? existingEnv.workspaces.filter((w) => w?.cwd).map((w) => normalizeWorkspaceInput(w))
|
|
470
|
+
: [];
|
|
471
|
+
// 若从隐式 env.cwd 首次新增另一个目录,把原默认 cwd 一并显式化避免丢失入口
|
|
472
|
+
if (current.length === 0 && existingEnv.cwd) {
|
|
473
|
+
const defCwd = normalizeWorkspaceCwd(existingEnv.cwd);
|
|
474
|
+
if (defCwd && defCwd !== ws.cwd) {
|
|
475
|
+
const seg = defCwd === "/" ? "/" : (defCwd.split("/").filter(Boolean).pop() ?? defCwd);
|
|
476
|
+
current.push({ cwd: defCwd, name: seg });
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const idx = current.findIndex((w) => w.cwd === ws.cwd);
|
|
480
|
+
const nextList = [...current];
|
|
481
|
+
if (idx >= 0) nextList[idx] = ws;
|
|
482
|
+
else nextList.push(ws);
|
|
483
|
+
const nextEnv = { ...existingEnv, workspaces: nextList };
|
|
484
|
+
const nextEnvs = { ...cfg.environments, [envName]: nextEnv };
|
|
485
|
+
const file = saveConfig({ ...cfg, environments: nextEnvs }, dir);
|
|
486
|
+
return { file, workspace: ws, environments: nextEnvs };
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
export function removeWorkspace(cfg, envName, cwd, dir = dataDir()) {
|
|
490
|
+
const existingEnv = cfg?.environments?.[envName];
|
|
491
|
+
if (!existingEnv) throw new Error(`未知环境: ${envName}`);
|
|
492
|
+
const target = normalizeWorkspaceCwd(cwd);
|
|
493
|
+
const current = Array.isArray(existingEnv.workspaces)
|
|
494
|
+
? existingEnv.workspaces.filter((w) => w?.cwd).map((w) => normalizeWorkspaceInput(w))
|
|
495
|
+
: [];
|
|
496
|
+
const nextList = current.filter((w) => w.cwd !== target);
|
|
497
|
+
const nextEnv = { ...existingEnv };
|
|
498
|
+
if (nextList.length > 0) nextEnv.workspaces = nextList;
|
|
499
|
+
else delete nextEnv.workspaces;
|
|
500
|
+
const nextEnvs = { ...cfg.environments, [envName]: nextEnv };
|
|
501
|
+
const file = saveConfig({ ...cfg, environments: nextEnvs }, dir);
|
|
502
|
+
return { file, environments: nextEnvs };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export function setHost(cfg, name, hostInput, dir = dataDir()) {
|
|
506
|
+
const h = normalizeHostInput(hostInput);
|
|
507
|
+
const nextHosts = { ...cfg.hosts, [name]: h };
|
|
508
|
+
const file = saveConfig({ ...cfg, hosts: nextHosts }, dir);
|
|
509
|
+
return { file, host: h, hosts: nextHosts };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
export function removeHost(cfg, name, dir = dataDir()) {
|
|
513
|
+
if (name === "local") throw new Error("内置 local 主机不能删除");
|
|
514
|
+
if (!cfg.hosts?.[name]) throw new Error(`未知主机: ${name}`);
|
|
515
|
+
const dependents = Object.entries(cfg.environments ?? {})
|
|
516
|
+
.filter(([, e]) => e.host === name)
|
|
517
|
+
.map(([envName]) => envName);
|
|
518
|
+
if (dependents.length > 0) {
|
|
519
|
+
throw new Error(`主机 ${name} 下还有环境(${dependents.join(", ")}),请先删除这些环境`);
|
|
520
|
+
}
|
|
521
|
+
const nextHosts = { ...cfg.hosts };
|
|
522
|
+
delete nextHosts[name];
|
|
523
|
+
const file = saveConfig({ ...cfg, hosts: nextHosts }, dir);
|
|
524
|
+
return { file, hosts: nextHosts };
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* 写入一个环境定义(新增或覆盖)。支持 v2(host + runtime)和向导/旧调用的扁平输入(自动确保对应 host 存在)。
|
|
529
|
+
* 🔴 先落盘再改内存。
|
|
530
|
+
*/
|
|
531
|
+
export function setEnvironment(cfg, name, envInput, dir = dataDir()) {
|
|
532
|
+
let nextHosts = { ...(cfg.hosts ?? { local: { type: "local" } }) };
|
|
533
|
+
let candidateInput = { ...(envInput ?? {}) };
|
|
534
|
+
if (!candidateInput.host && typeof candidateInput.hostName === "string" && nextHosts[candidateInput.hostName]) {
|
|
535
|
+
candidateInput.host = candidateInput.hostName;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// 如果传入的是扁平形状(type="ssh"|"local" + host 是远程地址/未传 host 引用名),自动绑定/创建对应 host
|
|
539
|
+
const isAlreadyHostRef = typeof candidateInput.host === "string" && Boolean(nextHosts[candidateInput.host]);
|
|
540
|
+
if (!isAlreadyHostRef) {
|
|
541
|
+
if (candidateInput.type === "local") {
|
|
542
|
+
candidateInput.host = "local";
|
|
543
|
+
} else if (candidateInput.type === "ssh" || (candidateInput.host && !nextHosts[candidateInput.host])) {
|
|
544
|
+
const remoteAddr = String(candidateInput.host ?? "").trim();
|
|
545
|
+
if (!remoteAddr) throw new Error(`${name}: ssh 环境必须有 host`);
|
|
546
|
+
// 复用已存在的同参数 SSH host,或创建新 host
|
|
547
|
+
const existing = Object.entries(nextHosts).find(([, h]) =>
|
|
548
|
+
h.type === "ssh" &&
|
|
549
|
+
h.host === remoteAddr &&
|
|
550
|
+
(h.user ?? undefined) === (candidateInput.user || undefined) &&
|
|
551
|
+
(h.port ?? undefined) === (candidateInput.port ? Number(candidateInput.port) : undefined) &&
|
|
552
|
+
(h.identityFile ?? undefined) === (candidateInput.identityFile || undefined),
|
|
553
|
+
);
|
|
554
|
+
if (existing) {
|
|
555
|
+
candidateInput.host = existing[0];
|
|
556
|
+
} else {
|
|
557
|
+
const hostName = candidateInput.hostName && ENV_NAME_PATTERN.test(candidateInput.hostName)
|
|
558
|
+
? candidateInput.hostName
|
|
559
|
+
: (!candidateInput.container && ENV_NAME_PATTERN.test(name) && !nextHosts[name]
|
|
560
|
+
? name
|
|
561
|
+
: makeUniqueHostName(remoteAddr, nextHosts));
|
|
562
|
+
nextHosts[hostName] = normalizeHostInput({
|
|
563
|
+
type: "ssh",
|
|
564
|
+
host: remoteAddr,
|
|
565
|
+
user: candidateInput.user,
|
|
566
|
+
port: candidateInput.port,
|
|
567
|
+
identityFile: candidateInput.identityFile,
|
|
568
|
+
});
|
|
569
|
+
candidateInput.host = hostName;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const env = normalizeEnvInput(candidateInput);
|
|
575
|
+
if (env.workspaces === undefined && Array.isArray(cfg.environments?.[name]?.workspaces)) {
|
|
576
|
+
env.workspaces = cfg.environments[name].workspaces;
|
|
577
|
+
}
|
|
578
|
+
const nextEnvs = { ...cfg.environments, [name]: env };
|
|
579
|
+
const file = saveConfig({ ...cfg, hosts: nextHosts, environments: nextEnvs }, dir);
|
|
580
|
+
return { file, env, hosts: nextHosts, environments: nextEnvs };
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
export function removeEnvironment(cfg, name, dir = dataDir()) {
|
|
584
|
+
if (!cfg.environments[name]) throw new Error(`未知环境: ${name}`);
|
|
585
|
+
const nextEnvs = { ...cfg.environments };
|
|
586
|
+
delete nextEnvs[name];
|
|
587
|
+
const file = saveConfig({ ...cfg, environments: nextEnvs }, dir);
|
|
588
|
+
return { file, environments: nextEnvs };
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
export function setDefaultModel(cfg, model, dir = dataDir()) {
|
|
592
|
+
const nextModel = {
|
|
593
|
+
provider: model?.provider ?? null,
|
|
594
|
+
modelId: model?.modelId ?? null,
|
|
595
|
+
};
|
|
596
|
+
const file = saveConfig({ ...cfg, defaultModel: nextModel }, dir);
|
|
597
|
+
return { file, defaultModel: nextModel };
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/** 原子写:临时文件 + rename,避免半截配置 */
|
|
601
|
+
export function saveConfig(cfg, dir = dataDir()) {
|
|
602
|
+
const normalized = { ...cfg, version: 2 };
|
|
603
|
+
validateConfig(normalized);
|
|
604
|
+
const file = paths(dir).config;
|
|
605
|
+
mkdirSync(dirnamePath(file), { recursive: true, mode: 0o700 });
|
|
606
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
607
|
+
writeFileSync(tmp, `${JSON.stringify(normalized, null, 2)}\n`, { mode: 0o600 });
|
|
608
|
+
renameSync(tmp, file);
|
|
609
|
+
return file;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function dirnamePath(p) {
|
|
613
|
+
const i = p.lastIndexOf("/");
|
|
614
|
+
return i <= 0 ? "." : p.slice(0, i);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** 解析某环境所属的 Host 配置与派生信息 */
|
|
618
|
+
export function resolveEnvTarget(envName, cfg, dir = dataDir()) {
|
|
619
|
+
const env = cfg.environments?.[envName];
|
|
620
|
+
if (!env) throw new Error(`未知环境: ${envName}`);
|
|
621
|
+
const hostName = env.host;
|
|
622
|
+
const hostCfg = cfg.hosts?.[hostName];
|
|
623
|
+
if (!hostCfg) throw new Error(`环境 ${envName} 引用的主机 "${hostName}" 不存在`);
|
|
624
|
+
const runtime = env.runtime ?? (env.container ? "docker" : "host");
|
|
625
|
+
const mode = `${hostCfg.type}-${runtime}`; // "local-host" | "local-docker" | "ssh-host" | "ssh-docker"
|
|
626
|
+
const derived = deriveEnv(envName, env, dir);
|
|
627
|
+
const target = hostCfg.type === "ssh" ? buildSshTarget(hostName, hostCfg, cfg, dir) : null;
|
|
628
|
+
return { envName, env, hostName, hostCfg, runtime, mode, derived, target };
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** 根据 Host 名构建 pi-env SshConnectOptions */
|
|
632
|
+
export function sshTargetForHost(hostName, cfg, dir = dataDir()) {
|
|
633
|
+
const hostCfg = cfg.hosts?.[hostName];
|
|
634
|
+
if (!hostCfg) throw new Error(`未知主机: ${hostName}`);
|
|
635
|
+
if (hostCfg.type !== "ssh") throw new Error(`主机 ${hostName} 不是 ssh 类型`);
|
|
636
|
+
const derived = deriveHost(hostName, dir);
|
|
637
|
+
return { hostName, target: buildSshTarget(hostName, hostCfg, cfg, dir), derived, host: hostCfg };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** 兼容封装:允许传 envName 或 hostName */
|
|
641
|
+
export function sshTargetFor(name, cfg, dir = dataDir()) {
|
|
642
|
+
if (cfg.hosts?.[name]) return sshTargetForHost(name, cfg, dir);
|
|
643
|
+
const resolved = resolveEnvTarget(name, cfg, dir);
|
|
644
|
+
if (!resolved.target) throw new Error(`环境 ${name} 不是 ssh 类型`);
|
|
645
|
+
return { target: resolved.target, derived: resolved.derived, env: resolved.env, hostName: resolved.hostName };
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
function buildSshTarget(hostName, hostCfg, cfg, dir) {
|
|
649
|
+
const d = deriveHost(hostName, dir);
|
|
650
|
+
const target = {
|
|
651
|
+
host: hostCfg.host,
|
|
652
|
+
knownHostsFile: d.knownHostsFile,
|
|
653
|
+
hostKeyAlias: d.hostKeyAlias,
|
|
654
|
+
};
|
|
655
|
+
if (hostCfg.user) target.user = hostCfg.user;
|
|
656
|
+
if (hostCfg.port) target.port = hostCfg.port;
|
|
657
|
+
if (hostCfg.identityFile) target.identityFile = hostCfg.identityFile;
|
|
658
|
+
else if (existsSync(d.identityFile)) target.identityFile = d.identityFile;
|
|
659
|
+
if (cfg.ssh?.program) target.ssh = cfg.ssh.program;
|
|
660
|
+
if (cfg.ssh?.configFile) target.configFile = cfg.ssh.configFile;
|
|
661
|
+
return target;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
function stripSshComment(line) {
|
|
665
|
+
let inQuotes = false;
|
|
666
|
+
for (let i = 0; i < line.length; i++) {
|
|
667
|
+
const ch = line[i];
|
|
668
|
+
if (ch === "\"") inQuotes = !inQuotes;
|
|
669
|
+
else if (ch === "#" && !inQuotes) return line.slice(0, i);
|
|
670
|
+
}
|
|
671
|
+
return line;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
function splitSshTokens(raw) {
|
|
675
|
+
const tokens = [];
|
|
676
|
+
let cur = "";
|
|
677
|
+
let inQuotes = false;
|
|
678
|
+
let hasToken = false;
|
|
679
|
+
for (let i = 0; i < raw.length; i++) {
|
|
680
|
+
const ch = raw[i];
|
|
681
|
+
if (ch === "\"") {
|
|
682
|
+
inQuotes = !inQuotes;
|
|
683
|
+
hasToken = true;
|
|
684
|
+
continue;
|
|
685
|
+
}
|
|
686
|
+
if (!inQuotes && /\s/.test(ch)) {
|
|
687
|
+
if (hasToken || cur.length > 0) {
|
|
688
|
+
tokens.push(cur);
|
|
689
|
+
cur = "";
|
|
690
|
+
hasToken = false;
|
|
691
|
+
}
|
|
692
|
+
continue;
|
|
693
|
+
}
|
|
694
|
+
cur += ch;
|
|
695
|
+
hasToken = true;
|
|
696
|
+
}
|
|
697
|
+
if (hasToken || cur.length > 0) tokens.push(cur);
|
|
698
|
+
return tokens;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
function unquoteSshValue(raw) {
|
|
702
|
+
const t = raw.trim();
|
|
703
|
+
if (t.length >= 2 && t.startsWith("\"") && t.endsWith("\"")) {
|
|
704
|
+
return t.slice(1, -1);
|
|
705
|
+
}
|
|
706
|
+
return t;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function expandIncludePattern(pattern, parentConfigDir) {
|
|
710
|
+
const expanded = expandTilde(unquoteSshValue(pattern));
|
|
711
|
+
if (!expanded) return [];
|
|
712
|
+
const defaultSshDir = join(homedir(), ".ssh");
|
|
713
|
+
let resolvedPattern = expanded;
|
|
714
|
+
if (!isAbsolute(expanded)) {
|
|
715
|
+
const relToParent = resolve(parentConfigDir, expanded);
|
|
716
|
+
const relDir = dirname(relToParent);
|
|
717
|
+
resolvedPattern = existsSync(relDir) ? relToParent : resolve(defaultSshDir, expanded);
|
|
718
|
+
}
|
|
719
|
+
const dirPart = dirname(resolvedPattern);
|
|
720
|
+
const basePat = basename(resolvedPattern);
|
|
721
|
+
if (!/[*?]/.test(basePat)) {
|
|
722
|
+
return existsSync(resolvedPattern) ? [resolvedPattern] : [];
|
|
723
|
+
}
|
|
724
|
+
if (!existsSync(dirPart)) return [];
|
|
725
|
+
const regexStr = `^${basePat
|
|
726
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
727
|
+
.replace(/\*/g, ".*")
|
|
728
|
+
.replace(/\?/g, ".")}$`;
|
|
729
|
+
const re = new RegExp(regexStr);
|
|
730
|
+
try {
|
|
731
|
+
return readdirSync(dirPart)
|
|
732
|
+
.filter((name) => {
|
|
733
|
+
if (!basePat.startsWith(".") && name.startsWith(".")) return false;
|
|
734
|
+
return re.test(name);
|
|
735
|
+
})
|
|
736
|
+
.sort()
|
|
737
|
+
.map((name) => join(dirPart, name));
|
|
738
|
+
} catch {
|
|
739
|
+
return [];
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function parseSshConfigFile(filePath, byAlias, seen, depth = 0) {
|
|
744
|
+
if (depth > 3) return;
|
|
745
|
+
const abs = resolve(filePath);
|
|
746
|
+
if (seen.has(abs) || !existsSync(abs)) return;
|
|
747
|
+
seen.add(abs);
|
|
748
|
+
|
|
749
|
+
let content = "";
|
|
750
|
+
try {
|
|
751
|
+
content = readFileSync(abs, "utf8");
|
|
752
|
+
} catch {
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
let currentAliases = [];
|
|
757
|
+
for (const rawLine of content.split(/\r?\n/)) {
|
|
758
|
+
const clean = stripSshComment(rawLine).trim();
|
|
759
|
+
if (!clean) continue;
|
|
760
|
+
const match = clean.match(/^([^\s=]+)(?:\s*=\s*|\s+)(.*)$/);
|
|
761
|
+
if (!match) continue;
|
|
762
|
+
const keyword = match[1].toLowerCase();
|
|
763
|
+
const rest = match[2].trim();
|
|
764
|
+
|
|
765
|
+
if (keyword === "include") {
|
|
766
|
+
for (const pat of splitSshTokens(rest)) {
|
|
767
|
+
for (const incFile of expandIncludePattern(pat, dirname(abs))) {
|
|
768
|
+
parseSshConfigFile(incFile, byAlias, seen, depth + 1);
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
continue;
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
if (keyword === "match") {
|
|
775
|
+
currentAliases = [];
|
|
776
|
+
continue;
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
if (keyword === "host") {
|
|
780
|
+
currentAliases = [];
|
|
781
|
+
for (const token of splitSshTokens(rest)) {
|
|
782
|
+
if (!token || token.startsWith("!") || /[*?]/.test(token)) continue;
|
|
783
|
+
let entry = byAlias.get(token);
|
|
784
|
+
if (!entry) {
|
|
785
|
+
entry = { alias: token };
|
|
786
|
+
byAlias.set(token, entry);
|
|
787
|
+
}
|
|
788
|
+
currentAliases.push(entry);
|
|
789
|
+
}
|
|
790
|
+
continue;
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
if (currentAliases.length === 0) continue;
|
|
794
|
+
const val = unquoteSshValue(rest);
|
|
795
|
+
if (!val) continue;
|
|
796
|
+
|
|
797
|
+
for (const entry of currentAliases) {
|
|
798
|
+
if (keyword === "hostname" && entry.hostName === undefined) entry.hostName = val;
|
|
799
|
+
else if (keyword === "user" && entry.user === undefined) entry.user = val;
|
|
800
|
+
else if (keyword === "port" && entry.port === undefined) {
|
|
801
|
+
const p = Number(val);
|
|
802
|
+
if (Number.isInteger(p) && p >= 1 && p <= 65535) entry.port = p;
|
|
803
|
+
} else if (keyword === "proxyjump" && entry.proxyJump === undefined) entry.proxyJump = val;
|
|
804
|
+
else if (keyword === "identityfile" && entry.identityFile === undefined) entry.identityFile = val;
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* 读取本机 ~/.ssh/config(或 cfg.ssh.configFile)中可用的具名 SSH Host 列表(忽略通配符与排除模式)。
|
|
811
|
+
*/
|
|
812
|
+
export function listSshConfigHosts(cfg) {
|
|
813
|
+
const file = cfg?.ssh?.configFile
|
|
814
|
+
? expandTilde(cfg.ssh.configFile)
|
|
815
|
+
: join(homedir(), ".ssh", "config");
|
|
816
|
+
const byAlias = new Map();
|
|
817
|
+
parseSshConfigFile(file, byAlias, new Set(), 0);
|
|
818
|
+
return Array.from(byAlias.values());
|
|
819
|
+
}
|