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/cli.mjs
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* foreman CLI(v2)
|
|
4
|
+
*
|
|
5
|
+
* foreman doctor 全链路体检(Node/CA/版本锁步/已发现扩展/代理/各环境)
|
|
6
|
+
* foreman init 生成 v2 起始配置(含 local + 示例 host/container)
|
|
7
|
+
* foreman login [provider] 交互式登录任意 Pi / 内置 Provider(凭据共享 ~/.pi/agent/auth.json)
|
|
8
|
+
* foreman logout [provider] 登出指定 Provider
|
|
9
|
+
* foreman models 列出全部已登录 Provider 的可用模型
|
|
10
|
+
* foreman envs 列出并探测所有环境(支持 4 种环境)
|
|
11
|
+
* foreman trust <name> [--yes] [--reset] 扫描/接受/重置 host key
|
|
12
|
+
* foreman deploy <name> 部署 daemon 到环境(支持 local-docker / ssh-host / ssh-docker)
|
|
13
|
+
* foreman ask <from> <to> "<问题>" [--timeout 秒] [--new]
|
|
14
|
+
* foreman serve [--port 8788] [--host 127.0.0.1]
|
|
15
|
+
* foreman conversations 列出已登记会话
|
|
16
|
+
*/
|
|
17
|
+
import { createInterface } from "node:readline/promises";
|
|
18
|
+
import { bootstrap, installedPiVersion } from "./bootstrap.mjs";
|
|
19
|
+
import { BACKGROUND_CONTEXT as CONTEXT } from "@earendil-works/chord/context";
|
|
20
|
+
import { projectEnvStatus, projectExec, projectModel } from "./projection.mjs";
|
|
21
|
+
|
|
22
|
+
const argv = process.argv.slice(2);
|
|
23
|
+
const command = argv[0] ?? "doctor";
|
|
24
|
+
const rest = argv.slice(1);
|
|
25
|
+
const flag = (name) => rest.includes(`--${name}`);
|
|
26
|
+
|
|
27
|
+
const ok = (m) => console.log(` \x1b[32m✅\x1b[0m ${m}`);
|
|
28
|
+
const bad = (m) => console.log(` \x1b[31m❌\x1b[0m ${m}`);
|
|
29
|
+
const warn = (m) => console.log(` \x1b[33m⚠️ \x1b[0m ${m}`);
|
|
30
|
+
const info = (m) => console.log(` · ${m}`);
|
|
31
|
+
const head = (m) => console.log(`\n\x1b[1m${m}\x1b[0m`);
|
|
32
|
+
|
|
33
|
+
let failures = 0;
|
|
34
|
+
const check = (pass, okMsg, failMsg) => { pass ? ok(okMsg) : (bad(failMsg), failures++); };
|
|
35
|
+
|
|
36
|
+
const { dataDir, loadConfig, paths: dataPaths, saveConfig, sshTargetFor } = await import("./config.mjs");
|
|
37
|
+
|
|
38
|
+
let dir, cfg;
|
|
39
|
+
try {
|
|
40
|
+
dir = dataDir();
|
|
41
|
+
cfg = loadConfig(dir);
|
|
42
|
+
} catch (e) {
|
|
43
|
+
console.error(`\x1b[31m配置错误\x1b[0m: ${e.message}`);
|
|
44
|
+
process.exit(2);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const boot = await bootstrap(cfg.proxy);
|
|
48
|
+
|
|
49
|
+
if (command === "init") { await cmdInit(); process.exit(0); }
|
|
50
|
+
|
|
51
|
+
const { EnvManager, describeError } = await import("./envs.mjs");
|
|
52
|
+
const envs = new EnvManager(cfg, dir, { onLog: (n, t) => process.env.PI_FOREMAN_DEBUG && console.error(`[${n}] ${t}`) });
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
switch (command) {
|
|
56
|
+
case "doctor": await cmdDoctor(); break;
|
|
57
|
+
case "login": await cmdLogin(rest[0]); break;
|
|
58
|
+
case "logout": await cmdLogout(rest[0]); break;
|
|
59
|
+
case "models": await cmdModels(); break;
|
|
60
|
+
case "envs": await cmdEnvs(); break;
|
|
61
|
+
case "trust": await cmdTrust(rest[0]); break;
|
|
62
|
+
case "deploy": await cmdDeploy(rest[0]); break;
|
|
63
|
+
case "ask": await cmdAsk(rest); break;
|
|
64
|
+
case "serve": await cmdServe(rest); break;
|
|
65
|
+
case "conversations": await cmdConversations(); break;
|
|
66
|
+
default:
|
|
67
|
+
console.log(`未知命令: ${command}\n可用: doctor | init | login | logout | models | envs | trust <name> | deploy <name> | ask | serve | conversations`);
|
|
68
|
+
process.exit(2);
|
|
69
|
+
}
|
|
70
|
+
} finally {
|
|
71
|
+
if (command !== "serve") await envs.closeAll();
|
|
72
|
+
}
|
|
73
|
+
if (command !== "serve") process.exit(failures > 0 ? 1 : 0);
|
|
74
|
+
|
|
75
|
+
// ── 命令实现 ────────────────────────────────────────────────────────────────
|
|
76
|
+
|
|
77
|
+
async function cmdInit() {
|
|
78
|
+
const file = dataPaths(dir).config;
|
|
79
|
+
const template = {
|
|
80
|
+
version: 2,
|
|
81
|
+
ssh: { program: null, configFile: null },
|
|
82
|
+
proxy: { http: null, https: null, noProxy: "localhost,127.0.0.1,::1" },
|
|
83
|
+
defaultModel: { provider: null, modelId: null },
|
|
84
|
+
providerExtensions: [],
|
|
85
|
+
peer: { allowAgentTool: true, maxDepth: 2 },
|
|
86
|
+
hosts: {
|
|
87
|
+
local: { type: "local" },
|
|
88
|
+
},
|
|
89
|
+
environments: {
|
|
90
|
+
local: { host: "local", runtime: "host", cwd: process.cwd(), description: "本机宿主机" },
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
saveConfig(template, dir);
|
|
94
|
+
console.log(`已写入 v2 配置: ${file}`);
|
|
95
|
+
console.log(`\n下一步:`);
|
|
96
|
+
console.log(` 1. foreman login # 登录一个模型 Provider(自动识别已安装的第三方 provider 扩展)`);
|
|
97
|
+
console.log(` 2. foreman serve # 启动控制台,在页面左侧添加主机 / 发现容器`);
|
|
98
|
+
console.log(` 3. foreman doctor # 全链路体检`);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function cmdDoctor() {
|
|
102
|
+
const piVer = installedPiVersion();
|
|
103
|
+
console.log(`\x1b[1mforeman doctor\x1b[0m (pi ${piVer}, Node ${process.versions.node}, ${process.platform}/${process.arch})`);
|
|
104
|
+
console.log(`数据目录: ${dir}`);
|
|
105
|
+
|
|
106
|
+
head("1. 运行时");
|
|
107
|
+
check(boot.node.ok, `Node ${boot.node.current} 满足 ${boot.node.required}`, `Node ${boot.node.current} 不满足 ${boot.node.required}`);
|
|
108
|
+
if (Number(process.versions.node.split(".")[0]) < 24) warn("node:sqlite 在 Node 24.15 前仍是 experimental(会有警告,功能正常)");
|
|
109
|
+
|
|
110
|
+
head("2. TLS / CA bundle");
|
|
111
|
+
if (boot.ca.applied) warn(`已启用 CA 兜底: SSL_CERT_FILE=${boot.ca.bundle}`);
|
|
112
|
+
else if (boot.ca.reason === "already-set") info(`使用外部设置: SSL_CERT_FILE=${process.env.SSL_CERT_FILE ?? ""} NODE_EXTRA_CA_CERTS=${process.env.NODE_EXTRA_CA_CERTS ?? ""}`);
|
|
113
|
+
else ok("CA bundle 正常,无需兜底");
|
|
114
|
+
|
|
115
|
+
head("3. 版本锁步(无硬编码版本限制)");
|
|
116
|
+
if (boot.versions.ok) ok(`全部 @earendil-works/* 锁步一致 = ${boot.versions.version}`);
|
|
117
|
+
else { bad(`版本不一致: ${boot.versions.found.map((f) => `${f.pkg}@${f.version}`).join(", ")}`); failures++; }
|
|
118
|
+
const nested = await countNestedCopies();
|
|
119
|
+
check(nested === 0, "无嵌套的 chord/pi-durable 副本", `发现 ${nested} 个嵌套副本 → instanceof 会静默失效`);
|
|
120
|
+
|
|
121
|
+
head("4. Provider 与模型(自动发现 Pi 扩展)");
|
|
122
|
+
const { buildModels, listProvidersWithAuth, refreshAllModels } = await import("./providers.mjs");
|
|
123
|
+
const { models, discoveredExtensions, extensionProviders, errors } = await buildModels(cfg);
|
|
124
|
+
for (const ext of discoveredExtensions) ok(`发现扩展 ${ext.label}(注册 ${ext.registeredProviders} 个 provider)`);
|
|
125
|
+
for (const e of errors) warn(`扩展加载警告: ${e}`);
|
|
126
|
+
await refreshAllModels(models, { allowNetwork: true });
|
|
127
|
+
const providers = await listProvidersWithAuth(models, extensionProviders);
|
|
128
|
+
const loggedIn = providers.filter((p) => p.loggedIn);
|
|
129
|
+
if (loggedIn.length === 0) {
|
|
130
|
+
warn("还没有已登录的 Provider → 运行: foreman login");
|
|
131
|
+
} else {
|
|
132
|
+
for (const p of loggedIn) {
|
|
133
|
+
ok(`${p.name} (${p.id}) · 已登录 (${p.authSource ?? p.authType}) · ${p.modelCount} 个模型${p.baseUrl ? ` · ${p.baseUrl}` : ""}`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
head("5. 环境连通性");
|
|
138
|
+
const names = envs.names();
|
|
139
|
+
if (names.length === 0) warn("没有配置环境");
|
|
140
|
+
for (const name of names) {
|
|
141
|
+
const envCfg = cfg.environments[name];
|
|
142
|
+
const hostCfg = cfg.hosts[envCfg.host];
|
|
143
|
+
const label = envCfg.container ? `${hostCfg?.host ?? envCfg.host} ▸ ${envCfg.container}` : (hostCfg?.host ?? name);
|
|
144
|
+
console.log(`\n \x1b[1m${name}\x1b[0m (${label})`);
|
|
145
|
+
try {
|
|
146
|
+
if (hostCfg?.type === "ssh") {
|
|
147
|
+
const { target } = sshTargetFor(envCfg.host, cfg, dir);
|
|
148
|
+
const trusted = await isTrusted(target);
|
|
149
|
+
if (!trusted) { warn(`host key 未信任 → 运行: foreman trust ${envCfg.host}`); continue; }
|
|
150
|
+
ok("host key 已信任");
|
|
151
|
+
}
|
|
152
|
+
const cwd = envCfg.cwd ?? (hostCfg?.type === "local" ? process.cwd() : "/tmp");
|
|
153
|
+
const st = projectEnvStatus(name, await envs.probe(name, { timeoutMs: 20000, cwd }));
|
|
154
|
+
if (!st.ok) { bad(`连接失败: ${st.error}`); failures++; continue; }
|
|
155
|
+
ok(`已连通 (${st.mode}, 建连 ${st.connectMs}ms${st.opMs !== undefined ? `, 文件 RTT ${st.opMs}ms · ${st.latencyGrade}` : ""})`);
|
|
156
|
+
} catch (e) {
|
|
157
|
+
bad(describeError(e));
|
|
158
|
+
failures++;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
head("结果");
|
|
163
|
+
if (failures === 0) console.log(` \x1b[32m全部通过\x1b[0m`);
|
|
164
|
+
else console.log(` \x1b[31m${failures} 项失败\x1b[0m`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function cmdLogin(targetProvider) {
|
|
168
|
+
const { buildModels, listProvidersWithAuth, refreshAllModels } = await import("./providers.mjs");
|
|
169
|
+
const { models, extensionProviders, discoveredExtensions } = await buildModels(cfg);
|
|
170
|
+
if (discoveredExtensions.length) {
|
|
171
|
+
info(`已自动加载扩展: ${discoveredExtensions.map((d) => d.label).join(", ")}`);
|
|
172
|
+
}
|
|
173
|
+
const all = (await listProvidersWithAuth(models, extensionProviders)).filter((p) => p.canLogin);
|
|
174
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
175
|
+
|
|
176
|
+
try {
|
|
177
|
+
let chosenId = targetProvider;
|
|
178
|
+
if (!chosenId) {
|
|
179
|
+
console.log(`\n\x1b[1m可登录的 Provider:\x1b[0m`);
|
|
180
|
+
all.forEach((p, idx) => {
|
|
181
|
+
const mark = p.loggedIn ? "\x1b[32m(已登录)\x1b[0m" : "";
|
|
182
|
+
const ext = p.extension ? ` \x1b[36m[${p.extension}]\x1b[0m` : "";
|
|
183
|
+
console.log(` ${String(idx + 1).padStart(2)}. ${p.id.padEnd(20)} ${p.name}${ext} ${mark}`);
|
|
184
|
+
});
|
|
185
|
+
const ans = (await rl.question("\n输入序号或 provider id: ")).trim();
|
|
186
|
+
const num = Number(ans);
|
|
187
|
+
chosenId = Number.isInteger(num) && num >= 1 && num <= all.length ? all[num - 1].id : ans;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
const provider = models.getProvider(chosenId);
|
|
191
|
+
if (!provider) {
|
|
192
|
+
bad(`未知 provider: ${chosenId}`);
|
|
193
|
+
failures++;
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const authType = provider.auth?.oauth ? "oauth" : provider.auth?.apiKey?.login ? "api_key" : null;
|
|
197
|
+
if (!authType) {
|
|
198
|
+
bad(`${chosenId} 不支持交互式登录`);
|
|
199
|
+
failures++;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const ac = new AbortController();
|
|
204
|
+
await models.login(chosenId, authType, {
|
|
205
|
+
signal: ac.signal,
|
|
206
|
+
prompt: async (p) => {
|
|
207
|
+
if (p.type === "select" && Array.isArray(p.options)) {
|
|
208
|
+
console.log(`\n${p.message}`);
|
|
209
|
+
p.options.forEach((o, i) => console.log(` ${i + 1}. ${o.label}${o.description ? ` - ${o.description}` : ""}`));
|
|
210
|
+
const raw = (await rl.question("选择序号: ")).trim();
|
|
211
|
+
const idx = Number(raw) - 1;
|
|
212
|
+
return p.options[idx]?.id ?? raw;
|
|
213
|
+
}
|
|
214
|
+
const hint = p.placeholder ? ` (${p.placeholder})` : "";
|
|
215
|
+
return (await rl.question(`${p.message}${hint}: `)).trim();
|
|
216
|
+
},
|
|
217
|
+
notify: (ev) => {
|
|
218
|
+
if (ev.type === "auth_url") console.log(`\n请打开链接完成授权:\n ${ev.url}\n${ev.instructions ?? ""}`);
|
|
219
|
+
else if (ev.type === "device_code") console.log(`\n打开 ${ev.verificationUri} 并输入验证码: \x1b[1m${ev.userCode}\x1b[0m`);
|
|
220
|
+
else if (ev.type === "info" || ev.type === "progress") info(ev.message);
|
|
221
|
+
},
|
|
222
|
+
}, { agentName: "pi-foreman" });
|
|
223
|
+
|
|
224
|
+
await refreshAllModels(models, { allowNetwork: true, providers: [chosenId] });
|
|
225
|
+
const count = models.getModels(chosenId).length;
|
|
226
|
+
ok(`登录成功!凭据已写入 ~/.pi/agent/auth.json(${chosenId} 当前 ${count} 个模型可用)`);
|
|
227
|
+
} finally {
|
|
228
|
+
rl.close();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function cmdLogout(targetProvider) {
|
|
233
|
+
const { buildModels, listProvidersWithAuth } = await import("./providers.mjs");
|
|
234
|
+
const { models, extensionProviders } = await buildModels(cfg);
|
|
235
|
+
const logged = (await listProvidersWithAuth(models, extensionProviders)).filter((p) => p.loggedIn);
|
|
236
|
+
let id = targetProvider;
|
|
237
|
+
if (!id) {
|
|
238
|
+
if (logged.length === 0) { info("当前没有任何已登录的 Provider"); return; }
|
|
239
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
240
|
+
try {
|
|
241
|
+
logged.forEach((p, i) => console.log(` ${i + 1}. ${p.id} (${p.name})`));
|
|
242
|
+
const ans = (await rl.question("选择要登出的序号或 id: ")).trim();
|
|
243
|
+
const idx = Number(ans) - 1;
|
|
244
|
+
id = logged[idx]?.id ?? ans;
|
|
245
|
+
} finally { rl.close(); }
|
|
246
|
+
}
|
|
247
|
+
await models.logout(id);
|
|
248
|
+
ok(`已登出 ${id}`);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async function cmdModels() {
|
|
252
|
+
const { buildModels, listAvailableModels, listProvidersWithAuth, refreshAllModels } = await import("./providers.mjs");
|
|
253
|
+
const { models, extensionProviders } = await buildModels(cfg);
|
|
254
|
+
const r = await refreshAllModels(models, { allowNetwork: !flag("offline") });
|
|
255
|
+
if (r.errors.length) warn(`刷新有错误: ${r.errors.join("; ")}`);
|
|
256
|
+
|
|
257
|
+
const providers = await listProvidersWithAuth(models, extensionProviders);
|
|
258
|
+
const avail = await listAvailableModels(models);
|
|
259
|
+
if (!avail.length) {
|
|
260
|
+
console.log(" (当前没有可用模型 —— 运行 `foreman login` 登录一个 Provider)");
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
console.log(`\n\x1b[1m可用模型\x1b[0m 共 ${avail.length} 个(默认: ${cfg.defaultModel?.provider ?? "-"}/${cfg.defaultModel?.modelId ?? "-"})\n`);
|
|
265
|
+
const byProvider = new Map();
|
|
266
|
+
for (const { model, supportedThinkingLevels } of avail) {
|
|
267
|
+
const view = projectModel(model, supportedThinkingLevels);
|
|
268
|
+
const list = byProvider.get(view.provider) ?? [];
|
|
269
|
+
list.push(view);
|
|
270
|
+
byProvider.set(view.provider, list);
|
|
271
|
+
}
|
|
272
|
+
for (const [pid, list] of byProvider) {
|
|
273
|
+
const pMeta = providers.find((x) => x.id === pid);
|
|
274
|
+
console.log(` \x1b[1m${pid}\x1b[0m (${pMeta?.name ?? pid}${pMeta?.extension ? ` · 扩展: ${pMeta.extension}` : ""})`);
|
|
275
|
+
for (const m of list) {
|
|
276
|
+
const cur = m.provider === cfg.defaultModel?.provider && m.id === cfg.defaultModel?.modelId ? " \x1b[32m← 默认\x1b[0m" : "";
|
|
277
|
+
const flags = [m.vision ? "vision" : null, m.reasoning ? "reasoning" : null].filter(Boolean).join("+");
|
|
278
|
+
console.log(` ${m.id.padEnd(26)} ${(m.name ?? "").padEnd(22)} ctx=${String(m.contextWindow).padEnd(8)} ${flags}${cur}`);
|
|
279
|
+
}
|
|
280
|
+
console.log("");
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function cmdEnvs() {
|
|
285
|
+
const names = envs.names();
|
|
286
|
+
if (names.length === 0) { console.log("没有配置环境。运行 foreman init"); return; }
|
|
287
|
+
console.log(`\x1b[1m环境列表\x1b[0m\n`);
|
|
288
|
+
for (const name of names) {
|
|
289
|
+
const envCfg = cfg.environments[name];
|
|
290
|
+
const hostCfg = cfg.hosts[envCfg.host];
|
|
291
|
+
const st = projectEnvStatus(name, await envs.probe(name, { timeoutMs: 20000, cwd: envCfg.cwd }));
|
|
292
|
+
const mark = st.ok ? "\x1b[32m●\x1b[0m" : "\x1b[31m○\x1b[0m";
|
|
293
|
+
const target = envCfg.container ? `${hostCfg?.host ?? envCfg.host} ▸ ${envCfg.container}` : (hostCfg?.host ?? envCfg.host);
|
|
294
|
+
const detail = st.ok
|
|
295
|
+
? `${st.mode} ${st.os}/${st.arch} 连接 ${st.connectMs}ms${st.opMs !== undefined ? ` 文件 ${st.opMs}ms (${st.latencyGrade})` : ""}`
|
|
296
|
+
: st.error;
|
|
297
|
+
console.log(` ${mark} \x1b[1m${name.padEnd(20)}\x1b[0m ${target.padEnd(34)} ${detail}`);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
async function cmdTrust(name) {
|
|
302
|
+
if (!name) { console.error("用法: foreman trust <host|env> [--yes] [--reset]"); process.exit(2); }
|
|
303
|
+
const { target } = sshTargetFor(name, cfg, dir);
|
|
304
|
+
if (flag("reset")) {
|
|
305
|
+
await envs.forgetTrust(name);
|
|
306
|
+
info(`已移除 ${target.hostKeyAlias} 的旧 host key`);
|
|
307
|
+
}
|
|
308
|
+
console.log(`扫描 ${target.host} 的 host key ...\n`);
|
|
309
|
+
let scanned;
|
|
310
|
+
try {
|
|
311
|
+
scanned = await envs.scanTrust(name);
|
|
312
|
+
} catch (e) {
|
|
313
|
+
if (e?.constructor?.name === "HostKeyChangedError") {
|
|
314
|
+
console.error(`\x1b[31m⚠️ HOST KEY 已变更\x1b[0m —— 请确认后运行: foreman trust ${name} --reset --yes`);
|
|
315
|
+
process.exit(1);
|
|
316
|
+
}
|
|
317
|
+
throw e;
|
|
318
|
+
}
|
|
319
|
+
console.log(`指纹:`);
|
|
320
|
+
for (const f of scanned.fingerprints) console.log(` ${f}`);
|
|
321
|
+
console.log(`\n原始行:\n${scanned.lines.map((l) => ` ${l}`).join("\n")}`);
|
|
322
|
+
|
|
323
|
+
if (!flag("yes")) {
|
|
324
|
+
console.log(`\n核对无误后运行: foreman trust ${name} --yes`);
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
await envs.acceptTrust(name, scanned.lines);
|
|
328
|
+
ok(`已写入 ${dataPaths(dir).knownHosts}`);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
async function cmdDeploy(name) {
|
|
332
|
+
if (!name) { console.error("用法: foreman deploy <name>"); process.exit(2); }
|
|
333
|
+
const t0 = Date.now();
|
|
334
|
+
const r = await envs.deploy(name);
|
|
335
|
+
ok(`${r.mode} 部署完成 (${Date.now() - t0}ms)`);
|
|
336
|
+
info(`路径: ${r.path}`);
|
|
337
|
+
info(`平台: ${r.platform.platform}/${r.platform.arch}`);
|
|
338
|
+
info(`SHA256: ${r.sha256}`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async function cmdAsk(args) {
|
|
342
|
+
const positional = [];
|
|
343
|
+
let timeoutSec = 600;
|
|
344
|
+
let forceNew = false;
|
|
345
|
+
for (let i = 0; i < args.length; i++) {
|
|
346
|
+
const a = args[i];
|
|
347
|
+
if (a === "--timeout") { timeoutSec = Number(args[++i]); continue; }
|
|
348
|
+
if (a.startsWith("--timeout=")) { timeoutSec = Number(a.slice("--timeout=".length)); continue; }
|
|
349
|
+
if (a === "--new") { forceNew = true; continue; }
|
|
350
|
+
positional.push(a);
|
|
351
|
+
}
|
|
352
|
+
const [fromEnv, toEnv, question] = positional;
|
|
353
|
+
if (!fromEnv || !toEnv || !question) {
|
|
354
|
+
console.error('用法: foreman ask <fromEnv> <toEnv> "<问题>" [--timeout <秒>] [--new]');
|
|
355
|
+
process.exit(2);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const { openFleet, createEnvConversation } = await import("./harness.mjs");
|
|
359
|
+
const { buildModels, refreshAllModels, resolveDefaultModel } = await import("./providers.mjs");
|
|
360
|
+
const { askPeer } = await import("./tasks/ask-peer.mjs");
|
|
361
|
+
|
|
362
|
+
const { models } = await buildModels(cfg);
|
|
363
|
+
await refreshAllModels(models, { allowNetwork: true });
|
|
364
|
+
const { harness, index } = await openFleet({ cfg, dir, envs, models });
|
|
365
|
+
|
|
366
|
+
try {
|
|
367
|
+
const model = await resolveDefaultModel(models, cfg);
|
|
368
|
+
const convOf = async (name) => {
|
|
369
|
+
if (!forceNew) {
|
|
370
|
+
const existing = index.forEnv(name);
|
|
371
|
+
if (existing.length) {
|
|
372
|
+
const newest = existing.reduce((a, b) => ((b.createdAt ?? 0) > (a.createdAt ?? 0) ? b : a));
|
|
373
|
+
const c = await harness.conversation(newest.conversationId, CONTEXT);
|
|
374
|
+
if (c) return c;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return createEnvConversation(harness, index, { env: name, cwd: cfg.environments[name].cwd, model, title: `ask-${name}` });
|
|
378
|
+
};
|
|
379
|
+
const convFrom = await convOf(fromEnv);
|
|
380
|
+
const convTo = await convOf(toEnv);
|
|
381
|
+
console.log(`\x1b[1m${fromEnv}\x1b[0m(#${convFrom.id}) ──问──> \x1b[1m${toEnv}\x1b[0m(#${convTo.id})`);
|
|
382
|
+
|
|
383
|
+
const res = await askPeer({ harness, index, cfg, models, ctx: CONTEXT }, {
|
|
384
|
+
fromEnv, toEnv, fromConversationId: Number(convFrom.id), toConversationId: Number(convTo.id),
|
|
385
|
+
question, timeoutMs: timeoutSec * 1000,
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
if (!res.ok) { console.error(`\n\x1b[31m❌ ${res.error}\x1b[0m`); failures++; return; }
|
|
389
|
+
console.log(`\n\x1b[32m✅ ${toEnv} 的回答\x1b[0m (${res.elapsedMs}ms)`);
|
|
390
|
+
console.log(res.answer);
|
|
391
|
+
} finally {
|
|
392
|
+
await harness.close(CONTEXT);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
async function cmdServe(args) {
|
|
397
|
+
let port = 8788;
|
|
398
|
+
let host = "127.0.0.1";
|
|
399
|
+
for (let i = 0; i < args.length; i++) {
|
|
400
|
+
if (args[i] === "--port") port = Number(args[++i]);
|
|
401
|
+
else if (args[i] === "--host") host = args[++i];
|
|
402
|
+
else if (args[i].startsWith("--port=")) port = Number(args[i].slice(7));
|
|
403
|
+
else if (args[i].startsWith("--host=")) host = args[i].slice(7);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const { openFleet, createEnvConversation } = await import("./harness.mjs");
|
|
407
|
+
const { buildModels, refreshAllModels } = await import("./providers.mjs");
|
|
408
|
+
const { startServer } = await import("./server.mjs");
|
|
409
|
+
const { fileURLToPath } = await import("node:url");
|
|
410
|
+
const { existsSync } = await import("node:fs");
|
|
411
|
+
const { join, dirname } = await import("node:path");
|
|
412
|
+
|
|
413
|
+
const { models, discoveredExtensions, extensionProviders, errors } = await buildModels(cfg);
|
|
414
|
+
for (const e of errors) warn(e);
|
|
415
|
+
const refreshed = await refreshAllModels(models, { allowNetwork: true });
|
|
416
|
+
if (refreshed.errors.length) warn(`模型目录刷新有错误: ${refreshed.errors.join("; ")}`);
|
|
417
|
+
|
|
418
|
+
let svcRef = null;
|
|
419
|
+
const { harness, index } = await openFleet({
|
|
420
|
+
cfg, dir, envs, models,
|
|
421
|
+
});
|
|
422
|
+
const webRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "web", "dist");
|
|
423
|
+
|
|
424
|
+
const svc = await startServer({
|
|
425
|
+
cfg, dir, envs, harness, index, models, extensionProviders,
|
|
426
|
+
createConversationFn: (_deps, opts) => createEnvConversation(harness, index, opts),
|
|
427
|
+
webRoot: existsSync(webRoot) ? webRoot : undefined,
|
|
428
|
+
host, port,
|
|
429
|
+
});
|
|
430
|
+
svcRef = svc;
|
|
431
|
+
|
|
432
|
+
console.log(`\n\x1b[1mpi-foreman v2 服务已启动\x1b[0m`);
|
|
433
|
+
console.log(` ${svc.origin}`);
|
|
434
|
+
console.log(` 数据目录: ${dir}`);
|
|
435
|
+
console.log(` 发现扩展: ${discoveredExtensions.length ? discoveredExtensions.map((d) => d.label).join(", ") : "(无)"}`);
|
|
436
|
+
console.log(` 环境: ${Object.keys(cfg.environments ?? {}).join(", ") || "(无)"}`);
|
|
437
|
+
if (!svc.origin.startsWith("http://127.0.0.1") && !svc.origin.startsWith("http://localhost")) {
|
|
438
|
+
console.log(` \x1b[33m⚠️ 绑定在 ${host},请确认这是可信网络。\x1b[0m`);
|
|
439
|
+
}
|
|
440
|
+
console.log(` Ctrl-C 退出\n`);
|
|
441
|
+
|
|
442
|
+
let closing = false;
|
|
443
|
+
const shutdown = async (signal) => {
|
|
444
|
+
if (closing) return;
|
|
445
|
+
closing = true;
|
|
446
|
+
console.log(`\n收到 ${signal},正在关闭 …`);
|
|
447
|
+
try { await svc.close(); } catch (e) { console.error(` 关闭服务失败: ${e.message}`); }
|
|
448
|
+
try { await harness.close(CONTEXT); } catch (e) { console.error(` 关闭 Harness 失败: ${e.message}`); }
|
|
449
|
+
try { await envs.closeAll(); } catch (e) { console.error(` 关闭连接失败: ${e.message}`); }
|
|
450
|
+
console.log(" ✅ 已关闭");
|
|
451
|
+
process.exit(0);
|
|
452
|
+
};
|
|
453
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
454
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function cmdConversations() {
|
|
458
|
+
const { openFleet } = await import("./harness.mjs");
|
|
459
|
+
const { buildModels } = await import("./providers.mjs");
|
|
460
|
+
const { models } = await buildModels(cfg, { fauxOnly: true });
|
|
461
|
+
const { harness, index } = await openFleet({ cfg, dir, envs, models });
|
|
462
|
+
try {
|
|
463
|
+
const all = index.all().sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
|
|
464
|
+
if (!all.length) { console.log(" (还没有会话)"); return; }
|
|
465
|
+
console.log(`\n\x1b[1m会话\x1b[0m 共 ${all.length} 个\n`);
|
|
466
|
+
for (const c of all.slice(0, Number(process.env.FOREMAN_LIST_LIMIT ?? 30))) {
|
|
467
|
+
const when = c.createdAt ? new Date(c.createdAt).toISOString().slice(0, 16).replace("T", " ") : "-";
|
|
468
|
+
console.log(` #${String(c.conversationId).padEnd(5)} ${String(c.env).padEnd(12)} ${when} ${c.title ?? ""}`);
|
|
469
|
+
}
|
|
470
|
+
console.log("");
|
|
471
|
+
} finally {
|
|
472
|
+
await harness.close(CONTEXT);
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
async function isTrusted(target) {
|
|
477
|
+
const { existsSync, readFileSync } = await import("node:fs");
|
|
478
|
+
if (!existsSync(target.knownHostsFile)) return false;
|
|
479
|
+
const content = readFileSync(target.knownHostsFile, "utf8");
|
|
480
|
+
return content.split("\n").some((l) => l.startsWith(`${target.hostKeyAlias} `) || l.startsWith(`${target.hostKeyAlias},`));
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
async function countNestedCopies() {
|
|
484
|
+
const { readdirSync, existsSync } = await import("node:fs");
|
|
485
|
+
const { join } = await import("node:path");
|
|
486
|
+
let count = 0;
|
|
487
|
+
const walk = (base, depth) => {
|
|
488
|
+
if (depth > 4 || !existsSync(base)) return;
|
|
489
|
+
let entries;
|
|
490
|
+
try { entries = readdirSync(base, { withFileTypes: true }); } catch { return; }
|
|
491
|
+
for (const e of entries) {
|
|
492
|
+
if (!e.isDirectory()) continue;
|
|
493
|
+
const p = join(base, e.name);
|
|
494
|
+
if (e.name === "node_modules" && base !== join(process.cwd(), "node_modules")) {
|
|
495
|
+
for (const dup of ["chord", "pi-durable"]) {
|
|
496
|
+
if (existsSync(join(p, "@earendil-works", dup))) count++;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
if (e.name === "node_modules" || base.endsWith("node_modules")) walk(p, depth + 1);
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
walk(join(process.cwd(), "node_modules"), 0);
|
|
503
|
+
return count;
|
|
504
|
+
}
|