@evandu/super-pi 0.1.258 → 0.1.259

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.
Files changed (50) hide show
  1. package/README.md +40 -0
  2. package/agents/super-pi-managed-model/index.ts +9 -0
  3. package/bin/npm-prefix.js +1 -1
  4. package/bin/super-pi.js +4 -3
  5. package/desktop/icon.png +0 -0
  6. package/desktop/launch.cjs +14 -0
  7. package/desktop/main.cjs +96 -0
  8. package/desktop/preload.cjs +9 -0
  9. package/dist/client/.super-pi-client-sources.json +33 -28
  10. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  11. package/dist/client/assets/{GitDiffEditor-BOtWl74Z.js → GitDiffEditor-FQBfGxOY.js} +3 -3
  12. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  13. package/dist/client/assets/{index-JchFQmlF.css → index-UfzqdECL.css} +1 -1
  14. package/dist/client/index.html +2 -2
  15. package/dist/server/browser-access.d.ts +34 -0
  16. package/dist/server/browser-access.js +89 -0
  17. package/dist/server/command-handler.d.ts +1 -1
  18. package/dist/server/command-handler.js +3 -3
  19. package/dist/server/http-server.js +90 -36
  20. package/dist/server/index.js +9 -0
  21. package/dist/server/managed-http-tunnel.d.ts +6 -0
  22. package/dist/server/managed-http-tunnel.js +85 -0
  23. package/dist/server/managed-http.d.ts +4 -0
  24. package/dist/server/managed-http.js +85 -0
  25. package/dist/server/managed-model-adapter.d.ts +17 -0
  26. package/dist/server/managed-model-adapter.js +75 -0
  27. package/dist/server/managed-model-gateway.d.ts +49 -0
  28. package/dist/server/managed-model-gateway.js +73 -0
  29. package/dist/server/managed-servers.d.ts +55 -0
  30. package/dist/server/managed-servers.js +392 -0
  31. package/dist/server/managed-ssh.d.ts +26 -0
  32. package/dist/server/managed-ssh.js +73 -0
  33. package/dist/server/manager-vault.d.ts +11 -0
  34. package/dist/server/manager-vault.js +67 -0
  35. package/dist/server/provider-proxy.js +2 -0
  36. package/dist/server/remote-bootstrap.d.ts +17 -0
  37. package/dist/server/remote-bootstrap.js +119 -0
  38. package/dist/server/server-context.d.ts +2 -0
  39. package/dist/server/terminal.d.ts +2 -2
  40. package/dist/server/terminal.js +6 -6
  41. package/dist/server/update.d.ts +1 -0
  42. package/dist/server/update.js +13 -2
  43. package/dist/server/ws-server.d.ts +5 -0
  44. package/dist/server/ws-server.js +29 -4
  45. package/dist/shared/managed-servers.d.ts +36 -0
  46. package/dist/shared/managed-servers.js +1 -0
  47. package/package.json +19 -4
  48. package/scripts/pack-server.mjs +44 -0
  49. package/dist/client/assets/CodeMirrorEditor-CyVU-MC_.js +0 -2
  50. package/dist/client/assets/index-Ba79LA0t.js +0 -349
@@ -0,0 +1,392 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { createServer } from "node:http";
3
+ import { connect as connectLocal } from "node:net";
4
+ import { mkdir, readFile, rename, writeFile, rm } from "node:fs/promises";
5
+ import { join, posix } from "node:path";
6
+ import { pathToFileURL } from "node:url";
7
+ import { ManagerVault } from "./manager-vault.js";
8
+ import { ManagedModelGateway } from "./managed-model-gateway.js";
9
+ import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
10
+ import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
11
+ import { installRemote, startRemote } from "./remote-bootstrap.js";
12
+ export class ManagedServers {
13
+ directory;
14
+ packageRoot;
15
+ defaultModel;
16
+ records = new Map();
17
+ clients = new Map();
18
+ secrets = new Map();
19
+ connecting = new Set();
20
+ jobs = new Map();
21
+ recoveries = new Map();
22
+ vault;
23
+ gateway = new ManagedModelGateway();
24
+ gatewayServer;
25
+ gatewayPort = 0;
26
+ timer;
27
+ stopped = false;
28
+ persistence = Promise.resolve();
29
+ artifact;
30
+ constructor(directory, packageRoot, defaultModel) {
31
+ this.directory = directory;
32
+ this.packageRoot = packageRoot;
33
+ this.defaultModel = defaultModel;
34
+ this.vault = new ManagerVault(join(directory, "credentials"));
35
+ }
36
+ async initialize() {
37
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
38
+ try {
39
+ const data = JSON.parse(await readFile(join(this.directory, "servers.json"), "utf8"));
40
+ for (const entry of data.servers ?? []) {
41
+ if (!/^[a-f0-9-]+$/.test(entry.profile?.id))
42
+ continue;
43
+ entry.profile = { ...entry.profile, ssh: "offline", service: "unknown", modelChannel: "offline", phase: entry.profile.phase === "deploying" ? "failed" : "idle", error: entry.profile.phase === "deploying" ? "本地管理服务在部署期间重启,请检查后重试部署" : undefined };
44
+ this.records.set(entry.profile.id, entry);
45
+ const secret = await this.vault.read(entry.profile.id);
46
+ if (secret)
47
+ this.secrets.set(entry.profile.id, secret);
48
+ }
49
+ }
50
+ catch (error) {
51
+ if (error.code !== "ENOENT")
52
+ throw new Error("本地服务器托管配置无法读取,请检查数据目录");
53
+ }
54
+ this.gatewayServer = createServer((request, response) => {
55
+ const value = request.headers.authorization?.replace(/^Bearer /, "") ?? "";
56
+ const valid = [...this.records.values()].some(entry => {
57
+ if (!entry.profile.enabled)
58
+ return false;
59
+ const token = this.secrets.get(entry.profile.id)?.modelToken;
60
+ return token && value.length === token.length && timingSafeEqual(Buffer.from(value), Buffer.from(token));
61
+ });
62
+ if (request.url !== "/model" || !valid) {
63
+ response.writeHead(403).end();
64
+ return;
65
+ }
66
+ void this.gateway.handle(request, response);
67
+ });
68
+ await new Promise((resolve, reject) => { this.gatewayServer.once("error", reject); this.gatewayServer.listen(0, "127.0.0.1", resolve); });
69
+ this.gatewayPort = this.gatewayServer.address().port;
70
+ this.timer = setInterval(() => { void this.maintain(); }, 10_000);
71
+ this.timer.unref();
72
+ void this.maintain();
73
+ }
74
+ list() { return [...this.records.values()].map(entry => structuredClone(entry.profile)); }
75
+ persist() {
76
+ const data = JSON.stringify({ servers: [...this.records.values()] }, null, 2);
77
+ this.persistence = this.persistence.catch(() => { }).then(async () => { const path = join(this.directory, "servers.json"), temp = `${path}.tmp`; await writeFile(temp, data, { mode: 0o600 }); await rename(temp, path); });
78
+ return this.persistence;
79
+ }
80
+ entry(id) { const entry = this.records.get(id); if (!entry)
81
+ throw new Error("找不到这个托管服务器"); return entry; }
82
+ async save(input) {
83
+ if (!input.name?.trim() || !input.host?.trim() || !input.username?.trim() || /[\s/\\\0]/.test(input.host) || /[\r\n\0]/.test(input.username))
84
+ throw new Error("请填写服务器名称、SSH 地址和用户名");
85
+ if (![input.sshPort, input.servicePort].every(port => Number.isInteger(port) && port > 0 && port < 65536))
86
+ throw new Error("SSH 和 Super Pi 端口必须在 1–65535 之间");
87
+ if (!["agent", "password", "privateKey"].includes(input.authentication))
88
+ throw new Error("请选择 SSH 认证方式");
89
+ const id = input.id ?? randomUUID(), previous = input.id ? this.entry(input.id) : undefined;
90
+ if (this.jobs.has(id))
91
+ throw new Error("部署尚未完成,暂不能修改连接");
92
+ if ([...this.records.values()].some(item => item.profile.id !== id && item.profile.name === input.name.trim()))
93
+ throw new Error("服务器名称已存在");
94
+ const old = this.secrets.get(id);
95
+ const secret = { ssh: { password: input.password || old?.ssh.password, privateKey: input.privateKey || old?.ssh.privateKey, passphrase: input.passphrase || old?.ssh.passphrase }, browserKey: old?.browserKey ?? randomBytes(32).toString("base64url"), modelToken: old?.modelToken ?? randomBytes(32).toString("base64url") };
96
+ if (input.authentication === "password" && !secret.ssh.password)
97
+ throw new Error("请输入 SSH 密码");
98
+ if (input.authentication === "privateKey" && !input.identityFile && !secret.ssh.privateKey)
99
+ throw new Error("请选择本地私钥文件,或粘贴私钥");
100
+ if (input.authentication !== "password")
101
+ delete secret.ssh.password;
102
+ if (input.authentication !== "privateKey") {
103
+ delete secret.ssh.privateKey;
104
+ delete secret.ssh.passphrase;
105
+ }
106
+ const changedHost = previous && (previous.profile.host !== input.host.trim() || previous.profile.sshPort !== input.sshPort || previous.profile.username !== input.username.trim());
107
+ if (changedHost && previous.installation)
108
+ throw new Error("已部署服务器不能直接改为另一台主机,请添加新的服务器以保护工作区归属");
109
+ const profile = { ...previous?.profile, id, name: input.name.trim(), host: input.host.trim(), sshPort: input.sshPort, username: input.username.trim(), servicePort: input.servicePort, authentication: input.authentication, identityFile: input.identityFile?.trim(), fingerprint: changedHost ? undefined : previous?.profile.fingerprint, observedFingerprint: undefined, enabled: true, ssh: "offline", service: "unknown", modelChannel: "offline", phase: "idle", error: undefined };
110
+ this.clients.get(id)?.end();
111
+ this.clients.delete(id);
112
+ await this.vault.write(id, secret);
113
+ this.secrets.set(id, secret);
114
+ this.records.set(id, { ...previous, profile });
115
+ await this.persist();
116
+ return profile;
117
+ }
118
+ async trust(id, fingerprint) {
119
+ const entry = this.entry(id);
120
+ if (!entry.profile.observedFingerprint || fingerprint !== entry.profile.observedFingerprint)
121
+ throw new Error("主机指纹已变化,请重新检测后确认");
122
+ entry.profile.fingerprint = fingerprint;
123
+ delete entry.profile.observedFingerprint;
124
+ entry.profile.phase = "idle";
125
+ await this.persist();
126
+ await this.connect(id);
127
+ return this.entry(id).profile;
128
+ }
129
+ async connect(id) {
130
+ const entry = this.entry(id), profile = entry.profile;
131
+ const existing = this.clients.get(id);
132
+ if (existing)
133
+ return existing;
134
+ if (!profile.enabled || this.stopped)
135
+ throw new Error("服务器连接已停用");
136
+ if (this.connecting.has(id))
137
+ throw new Error("正在连接此服务器");
138
+ const secret = this.secrets.get(id);
139
+ if (!secret)
140
+ throw new Error("缺少 SSH 认证配置");
141
+ this.connecting.add(id);
142
+ profile.ssh = "connecting";
143
+ if (profile.phase !== "deploying")
144
+ profile.phase = "connecting";
145
+ delete profile.error;
146
+ try {
147
+ const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh });
148
+ if (!profile.enabled || this.stopped) {
149
+ client.end();
150
+ throw new Error("连接已取消");
151
+ }
152
+ this.clients.set(id, client);
153
+ profile.ssh = "online";
154
+ client.once("close", () => { if (this.clients.get(id) !== client)
155
+ return; this.clients.delete(id); profile.ssh = "offline"; profile.service = "offline"; profile.modelChannel = "offline"; if (profile.phase !== "deploying") {
156
+ profile.phase = "idle";
157
+ profile.error = "SSH 连接中断,正在自动重连";
158
+ } void this.persist(); });
159
+ if (entry.installation) {
160
+ await this.reverseModelChannel(entry, client);
161
+ await this.syncModels(id);
162
+ await this.ensureService(id);
163
+ }
164
+ else
165
+ profile.phase = "idle";
166
+ await this.persist();
167
+ return client;
168
+ }
169
+ catch (cause) {
170
+ const failed = this.clients.get(id);
171
+ this.clients.delete(id);
172
+ failed?.end();
173
+ profile.ssh = cause instanceof HostTrustRequired ? "needsTrust" : "offline";
174
+ profile.phase = cause instanceof HostTrustRequired ? "needsTrust" : "failed";
175
+ if (cause instanceof HostTrustRequired)
176
+ profile.observedFingerprint = cause.fingerprint;
177
+ profile.error = cause instanceof Error ? cause.message : "SSH 连接失败";
178
+ await this.persist();
179
+ throw cause;
180
+ }
181
+ finally {
182
+ this.connecting.delete(id);
183
+ }
184
+ }
185
+ async reverseModelChannel(entry, client) {
186
+ if (entry.profile.modelChannel === "online")
187
+ return;
188
+ const port = await new Promise((resolve, reject) => client.forwardIn("127.0.0.1", entry.reversePort ?? 0, (error, port) => error ? reject(new Error("SSH 服务拒绝反向端口转发,请启用 AllowTcpForwarding")) : resolve(port)));
189
+ entry.reversePort = port;
190
+ client.on("tcp connection", (details, accept, reject) => {
191
+ if (details.destPort !== port || details.destIP !== "127.0.0.1") {
192
+ reject();
193
+ return;
194
+ }
195
+ const channel = accept();
196
+ const local = connectLocal(this.gatewayPort, "127.0.0.1", () => { channel.pipe(local); local.pipe(channel); });
197
+ channel.once("close", () => local.destroy());
198
+ local.once("close", () => channel.close());
199
+ channel.once("error", () => local.destroy());
200
+ local.once("error", () => channel.close());
201
+ });
202
+ entry.profile.modelChannel = "online";
203
+ }
204
+ async syncModels(id, force = false) {
205
+ const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
206
+ if (!entry.installation || !entry.reversePort || !client || !secret)
207
+ throw new Error("请先部署并连接此服务器");
208
+ const models = await this.gateway.catalog(force);
209
+ const content = JSON.stringify({ endpoint: `http://127.0.0.1:${entry.reversePort}/model`, token: secret.modelToken, models, defaultModel: this.defaultModel() });
210
+ const hash = createHash("sha256").update(content).digest("hex");
211
+ if (hash === entry.modelHash)
212
+ return;
213
+ await sshWrite(client, posix.join(entry.installation.root, "models.json"), content);
214
+ const defaultModel = this.defaultModel() ?? (models[0] ? { provider: models[0].provider, modelId: models[0].id } : undefined);
215
+ if (defaultModel)
216
+ await sshWrite(client, posix.join(entry.installation.root, "agent", "settings.json"), JSON.stringify({ defaultProvider: defaultModel.provider, defaultModel: defaultModel.modelId }));
217
+ entry.modelHash = hash;
218
+ if (entry.profile.service === "online")
219
+ await tunnelJson(client, entry.profile.servicePort, "/api/managed-model/reload", secret.browserKey, "POST");
220
+ }
221
+ async health(id) {
222
+ const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
223
+ if (!client || !secret)
224
+ return;
225
+ try {
226
+ const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
227
+ if (info.id !== entry.profile.identity)
228
+ throw new Error("端口上运行的不是此托管服务,请检查端口冲突");
229
+ entry.profile.service = "online";
230
+ if (!this.jobs.has(id))
231
+ entry.profile.phase = "ready";
232
+ delete entry.profile.error;
233
+ }
234
+ catch (cause) {
235
+ entry.profile.service = "offline";
236
+ if (!this.jobs.has(id))
237
+ entry.profile.phase = "failed";
238
+ entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
239
+ }
240
+ }
241
+ async ensureService(id) {
242
+ await this.health(id);
243
+ const entry = this.entry(id), client = this.clients.get(id);
244
+ if (!client || !entry.installation || entry.profile.service === "online" || entry.profile.error?.includes("不是此托管") || Date.now() - (this.recoveries.get(id) ?? 0) < 60_000)
245
+ return;
246
+ this.recoveries.set(id, Date.now());
247
+ const root = entry.installation.root, pid = posix.join(root, "service.pid");
248
+ const alive = await sshExec(client, `if [ -f ${sh(pid)} ]; then p=$(cat ${sh(pid)}); case "$p" in *[!0-9]*|"") ;; *) ps -p "$p" -o args= 2>/dev/null | grep -F ${sh(`${root}/runtime-`)} || true ;; esac; fi`);
249
+ if (alive.trim())
250
+ return;
251
+ this.progress(entry, "远端服务已停止,正在恢复");
252
+ await startRemote(client, entry.installation, entry.profile.servicePort);
253
+ for (let attempt = 0; attempt < 15; attempt++) {
254
+ await this.health(id);
255
+ if (this.entry(id).profile.service === "online")
256
+ break;
257
+ await new Promise(resolve => setTimeout(resolve, 1000));
258
+ }
259
+ }
260
+ progress(entry, step, output) {
261
+ entry.profile.step = step;
262
+ if (output) {
263
+ const clean = output.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/(https?:\/\/)[^/@\s]+:[^/@\s]+@/g, "$1[redacted]@").replace(/Bearer\s+\S+/gi, "Bearer [redacted]");
264
+ entry.profile.log = [...entry.profile.log ?? [], ...clean.split(/\r?\n/).filter(Boolean)].slice(-80).map(line => line.slice(0, 1000));
265
+ }
266
+ void this.persist();
267
+ }
268
+ deploy(id) {
269
+ const entry = this.entry(id);
270
+ if (this.jobs.has(id))
271
+ throw new Error("此服务器已有部署进行中");
272
+ if (!entry.profile.fingerprint)
273
+ throw new Error("请先测试 SSH 并确认主机指纹");
274
+ entry.profile.phase = "deploying";
275
+ entry.profile.log = [];
276
+ delete entry.profile.error;
277
+ const job = (async () => {
278
+ try {
279
+ const client = await this.connect(id);
280
+ entry.profile.phase = "deploying";
281
+ this.progress(entry, "生成与本地版本一致的纯服务安装包");
282
+ this.artifact ??= import(pathToFileURL(join(this.packageRoot, "scripts", "pack-server.mjs")).href).then(module => module.packServer(this.packageRoot, join(this.directory, "packages"))).catch(error => { this.artifact = undefined; throw error; });
283
+ const artifact = await this.artifact;
284
+ if (entry.profile.service === "online") {
285
+ const state = await tunnelJson(client, entry.profile.servicePort, "/api/conversations", this.secrets.get(id).browserKey);
286
+ if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
287
+ throw new Error("远端仍有进行中的任务,请完成后再重新部署");
288
+ }
289
+ const installation = await installRemote({ client, id, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
290
+ entry.installation = installation;
291
+ entry.profile.remoteRoot = installation.root;
292
+ entry.profile.identity ??= randomUUID();
293
+ const secret = this.secrets.get(id);
294
+ await sshWrite(client, posix.join(installation.root, "data", "browser-access.json"), JSON.stringify({ id: entry.profile.identity, key: secret.browserKey }));
295
+ this.progress(entry, "建立模型通道并同步本地模型目录");
296
+ await this.reverseModelChannel(entry, client);
297
+ entry.modelHash = undefined;
298
+ await this.syncModels(id);
299
+ this.progress(entry, "启动远端 Super Pi 服务");
300
+ await startRemote(client, installation, entry.profile.servicePort);
301
+ for (let attempt = 0; attempt < 30; attempt++) {
302
+ await this.health(id);
303
+ if (this.entry(id).profile.service === "online")
304
+ break;
305
+ await new Promise(resolve => setTimeout(resolve, 1000));
306
+ }
307
+ if (entry.profile.service !== "online")
308
+ throw new Error("远端服务未能启动,请查看部署记录及远端 service.log");
309
+ entry.profile.deployedAt = new Date().toISOString();
310
+ entry.profile.phase = "ready";
311
+ this.progress(entry, "已接入,本地配置的模型可直接用于远端会话");
312
+ }
313
+ catch (cause) {
314
+ entry.profile.phase = "failed";
315
+ entry.profile.error = cause instanceof Error ? cause.message : "部署失败";
316
+ }
317
+ finally {
318
+ this.jobs.delete(id);
319
+ await this.persist();
320
+ }
321
+ })();
322
+ this.jobs.set(id, job);
323
+ void this.persist();
324
+ return entry.profile;
325
+ }
326
+ async action(id, action) {
327
+ const entry = this.entry(id);
328
+ if (action === "disconnect") {
329
+ entry.profile.enabled = false;
330
+ this.clients.get(id)?.end();
331
+ this.clients.delete(id);
332
+ entry.profile.ssh = "offline";
333
+ entry.profile.service = "offline";
334
+ entry.profile.modelChannel = "offline";
335
+ entry.profile.phase = "idle";
336
+ delete entry.profile.error;
337
+ }
338
+ else if (action === "connect" || action === "test") {
339
+ entry.profile.enabled = true;
340
+ await this.connect(id);
341
+ }
342
+ else if (action === "sync")
343
+ await this.syncModels(id, true);
344
+ else if (action === "deploy")
345
+ return this.deploy(id);
346
+ else if (action === "remove") {
347
+ if (this.jobs.has(id))
348
+ throw new Error("部署期间不能移除服务器");
349
+ this.clients.get(id)?.end();
350
+ this.clients.delete(id);
351
+ this.records.delete(id);
352
+ this.secrets.delete(id);
353
+ await rm(join(this.directory, "credentials", `${id}.secret`), { force: true });
354
+ }
355
+ else
356
+ throw new Error("不支持的托管操作");
357
+ await this.persist();
358
+ return this.records.get(id)?.profile;
359
+ }
360
+ async maintain() {
361
+ if (this.stopped)
362
+ return;
363
+ for (const entry of this.records.values()) {
364
+ if (!entry.profile.enabled || this.jobs.has(entry.profile.id) || this.connecting.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
365
+ continue;
366
+ try {
367
+ if (!this.clients.has(entry.profile.id))
368
+ await this.connect(entry.profile.id);
369
+ else if (entry.installation) {
370
+ await this.ensureService(entry.profile.id);
371
+ await this.syncModels(entry.profile.id);
372
+ }
373
+ }
374
+ catch { /* Each record carries its own actionable connection failure. */ }
375
+ }
376
+ }
377
+ connectionProfiles() { return [...this.records.values()].filter(entry => entry.profile.identity).map(entry => ({ id: `ssh-${entry.profile.id}`, managedId: entry.profile.id, managed: true, name: entry.profile.name, url: `/managed/${entry.profile.id}`, enabled: entry.profile.enabled, identity: entry.profile.identity, revision: entry.profile.deployedAt ? Date.parse(entry.profile.deployedAt) : 0 })); }
378
+ proxy(id, path, request, response) {
379
+ const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
380
+ if (!entry.profile.enabled || !client || !secret) {
381
+ response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 连接不可用,请在服务器连接设置中查看状态" }));
382
+ return;
383
+ }
384
+ proxyThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, response, `/managed/${id}`);
385
+ }
386
+ async upgrade(id, path, request, socket, head) { const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id); if (!entry.profile.enabled || !client || !secret) {
387
+ socket.destroy();
388
+ return;
389
+ } await proxyWebSocketThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, socket, head); }
390
+ async close() { this.stopped = true; clearInterval(this.timer); for (const client of this.clients.values())
391
+ client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
392
+ }
@@ -0,0 +1,26 @@
1
+ import type { Client, ClientChannel, SFTPWrapper } from "ssh2";
2
+ export interface SshProfile {
3
+ host: string;
4
+ port: number;
5
+ username: string;
6
+ authentication: "agent" | "password" | "privateKey";
7
+ password?: string;
8
+ privateKey?: string;
9
+ identityFile?: string;
10
+ passphrase?: string;
11
+ fingerprint?: string;
12
+ }
13
+ export declare class HostTrustRequired extends Error {
14
+ readonly fingerprint: string;
15
+ readonly changed: boolean;
16
+ constructor(fingerprint: string, changed: boolean);
17
+ }
18
+ export declare const sh: (value: string) => string;
19
+ export declare function connectSsh(profile: SshProfile): Promise<Client>;
20
+ export declare function sshExec(client: Client, command: string, options?: {
21
+ timeout?: number;
22
+ onOutput?: (chunk: string) => void;
23
+ }): Promise<string>;
24
+ export declare const sshSftp: (client: Client) => Promise<SFTPWrapper>;
25
+ export declare function sshWrite(client: Client, path: string, data: string | Buffer, mode?: number): Promise<void>;
26
+ export declare const sshForward: (client: Client, port: number) => Promise<ClientChannel>;
@@ -0,0 +1,73 @@
1
+ import { createHash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ export class HostTrustRequired extends Error {
4
+ fingerprint;
5
+ changed;
6
+ constructor(fingerprint, changed) {
7
+ super(changed ? "SSH 主机指纹发生变化,已拒绝连接" : "请确认 SSH 主机指纹后继续");
8
+ this.fingerprint = fingerprint;
9
+ this.changed = changed;
10
+ }
11
+ }
12
+ export const sh = (value) => `'${value.replaceAll("'", "'\\''")}'`;
13
+ export async function connectSsh(profile) {
14
+ const { Client } = await import("ssh2");
15
+ const client = new Client();
16
+ let observed = "";
17
+ let trusted = false;
18
+ const settings = {
19
+ host: profile.host, port: profile.port, username: profile.username,
20
+ readyTimeout: 20_000, keepaliveInterval: 15_000, keepaliveCountMax: 3,
21
+ hostVerifier: (key) => {
22
+ observed = `SHA256:${createHash("sha256").update(key).digest("base64").replace(/=+$/, "")}`;
23
+ trusted = profile.fingerprint === observed;
24
+ return trusted;
25
+ },
26
+ };
27
+ if (profile.authentication === "password")
28
+ settings.password = profile.password;
29
+ else if (profile.authentication === "privateKey") {
30
+ settings.privateKey = profile.privateKey || (profile.identityFile ? await readFile(profile.identityFile) : undefined);
31
+ settings.passphrase = profile.passphrase;
32
+ }
33
+ else
34
+ settings.agent = process.env.SSH_AUTH_SOCK || (process.platform === "win32" ? "\\\\.\\pipe\\openssh-ssh-agent" : undefined);
35
+ return new Promise((resolve, reject) => {
36
+ client.once("ready", () => { client.removeListener("error", failed); client.on("error", () => { }); resolve(client); });
37
+ const failed = (error) => { client.end(); reject(observed && !trusted ? new HostTrustRequired(observed, Boolean(profile.fingerprint)) : new Error(error.level === "client-authentication" ? "SSH 认证失败,请检查用户名和认证信息" : "SSH 连接失败,请检查地址、端口、网络和认证信息")); };
38
+ client.once("error", failed);
39
+ client.connect(settings);
40
+ });
41
+ }
42
+ export function sshExec(client, command, options = {}) {
43
+ return new Promise((resolve, reject) => {
44
+ let channel, output = "", error = "";
45
+ const timer = setTimeout(() => { channel?.close(); reject(new Error("远端命令超时,请检查部署进度后重试")); }, options.timeout ?? 30_000);
46
+ client.exec(command, (failure, stream) => {
47
+ if (failure) {
48
+ clearTimeout(timer);
49
+ reject(new Error("无法启动远端命令"));
50
+ return;
51
+ }
52
+ channel = stream;
53
+ stream.on("data", (chunk) => { output = (output + chunk.toString()).slice(-256_000); options.onOutput?.(chunk.toString()); });
54
+ stream.stderr.on("data", (chunk) => { error = (error + chunk.toString()).slice(-32_000); options.onOutput?.(chunk.toString()); });
55
+ stream.once("close", (code) => { clearTimeout(timer); if (code === 0)
56
+ resolve(output);
57
+ else
58
+ reject(new Error(`远端命令失败(exit ${code ?? "unknown"})${error ? ",请查看部署日志" : ""}`)); });
59
+ stream.once("error", () => { clearTimeout(timer); reject(new Error("SSH 命令通道中断")); });
60
+ });
61
+ });
62
+ }
63
+ export const sshSftp = (client) => new Promise((resolve, reject) => client.sftp((error, sftp) => error ? reject(new Error("无法打开 SFTP 通道")) : resolve(sftp)));
64
+ export async function sshWrite(client, path, data, mode = 0o600) {
65
+ const sftp = await sshSftp(client);
66
+ try {
67
+ await new Promise((resolve, reject) => sftp.writeFile(path, data, { mode }, error => error ? reject(new Error("无法写入远端托管文件")) : resolve()));
68
+ }
69
+ finally {
70
+ sftp.end();
71
+ }
72
+ }
73
+ export const sshForward = (client, port) => new Promise((resolve, reject) => client.forwardOut("127.0.0.1", 0, "127.0.0.1", port, (error, channel) => error ? reject(new Error("远端 Super Pi 端口不可达,请检查服务是否已启动")) : resolve(channel)));
@@ -0,0 +1,11 @@
1
+ /** Authentication material is kept outside public connection records and encrypted at rest. */
2
+ export declare class ManagerVault {
3
+ private readonly directory;
4
+ private key?;
5
+ private keyLoading?;
6
+ constructor(directory: string);
7
+ private encryptionKey;
8
+ private loadEncryptionKey;
9
+ read<T>(id: string): Promise<T | undefined>;
10
+ write(id: string, value: unknown): Promise<void>;
11
+ }
@@ -0,0 +1,67 @@
1
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ /** Authentication material is kept outside public connection records and encrypted at rest. */
5
+ export class ManagerVault {
6
+ directory;
7
+ key;
8
+ keyLoading;
9
+ constructor(directory) {
10
+ this.directory = directory;
11
+ }
12
+ async encryptionKey() {
13
+ if (this.key)
14
+ return this.key;
15
+ this.keyLoading ??= this.loadEncryptionKey().catch(error => { this.keyLoading = undefined; throw error; });
16
+ return this.keyLoading;
17
+ }
18
+ async loadEncryptionKey() {
19
+ await mkdir(this.directory, { recursive: true, mode: 0o700 });
20
+ const path = join(this.directory, "manager.key");
21
+ try {
22
+ this.key = await readFile(path);
23
+ }
24
+ catch (error) {
25
+ if (error.code !== "ENOENT")
26
+ throw error;
27
+ const key = randomBytes(32);
28
+ try {
29
+ await writeFile(path, key, { mode: 0o600, flag: "wx" });
30
+ this.key = key;
31
+ }
32
+ catch (error) {
33
+ if (error.code !== "EEXIST")
34
+ throw error;
35
+ this.key = await readFile(path);
36
+ }
37
+ }
38
+ if (this.key.length !== 32)
39
+ throw new Error("本地认证存储损坏,请恢复管理服务的数据目录");
40
+ return this.key;
41
+ }
42
+ async read(id) {
43
+ if (!/^[a-zA-Z0-9-]+$/.test(id))
44
+ throw new Error("认证记录标识无效");
45
+ const key = await this.encryptionKey();
46
+ try {
47
+ const raw = JSON.parse(await readFile(join(this.directory, `${id}.secret`), "utf8"));
48
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(raw.iv, "base64"));
49
+ decipher.setAuthTag(Buffer.from(raw.tag, "base64"));
50
+ return JSON.parse(Buffer.concat([decipher.update(Buffer.from(raw.data, "base64")), decipher.final()]).toString("utf8"));
51
+ }
52
+ catch (error) {
53
+ if (error.code === "ENOENT")
54
+ return;
55
+ throw new Error("无法解密本地 SSH 认证资料");
56
+ }
57
+ }
58
+ async write(id, value) {
59
+ if (!/^[a-zA-Z0-9-]+$/.test(id))
60
+ throw new Error("认证记录标识无效");
61
+ const key = await this.encryptionKey(), iv = randomBytes(12), cipher = createCipheriv("aes-256-gcm", key, iv);
62
+ const encrypted = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);
63
+ const path = join(this.directory, `${id}.secret`), temp = `${path}.tmp`;
64
+ await writeFile(temp, JSON.stringify({ iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: encrypted.toString("base64") }), { mode: 0o600 });
65
+ await rename(temp, path);
66
+ }
67
+ }
@@ -1,3 +1,4 @@
1
+ import { installManagedModels } from "./managed-model-adapter.js";
1
2
  import { EnvHttpProxyAgent } from "undici";
2
3
  import { readFile } from "node:fs/promises";
3
4
  import { join } from "node:path";
@@ -138,6 +139,7 @@ export function proxyCredentialStore(store) {
138
139
  }
139
140
  /** Read provider routing independently of Pi's auth result: OAuth resolution omits credential.env. */
140
141
  export async function installProviderProxy(runtime, agentDir) {
142
+ await installManagedModels(runtime);
141
143
  const target = runtime;
142
144
  if (typeof target.getAuth !== "function")
143
145
  return;
@@ -0,0 +1,17 @@
1
+ import type { Client } from "ssh2";
2
+ export interface RemoteInstallation {
3
+ root: string;
4
+ packageRoot: string;
5
+ node: string;
6
+ piCommand: string;
7
+ }
8
+ export declare function uploadFile(client: Client, local: string, remote: string): Promise<void>;
9
+ export declare function installRemote(options: {
10
+ client: Client;
11
+ id: string;
12
+ archive: string;
13
+ archiveHash: string;
14
+ cacheDir: string;
15
+ progress(step: string, output?: string): void;
16
+ }): Promise<RemoteInstallation>;
17
+ export declare function startRemote(client: Client, installation: RemoteInstallation, port: number): Promise<void>;