@evandu/super-pi 0.1.260 → 0.1.262

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 (33) hide show
  1. package/desktop/brand.svg +6 -0
  2. package/desktop/icon.png +0 -0
  3. package/desktop/main.cjs +16 -4
  4. package/desktop/preload.cjs +19 -0
  5. package/desktop/tray-icon.png +0 -0
  6. package/desktop/tray-icon@2x.png +0 -0
  7. package/desktop/tray.svg +1 -0
  8. package/dist/client/.super-pi-client-sources.json +19 -14
  9. package/dist/client/assets/{CodeMirrorEditor-mi9rGUce.js → CodeMirrorEditor-DRcRXwhV.js} +1 -1
  10. package/dist/client/assets/{GitDiffEditor-FQBfGxOY.js → GitDiffEditor-Cm0JVvdZ.js} +1 -1
  11. package/dist/client/assets/index-BZd7RTFi.js +350 -0
  12. package/dist/client/assets/index-DHTKUM97.css +1 -0
  13. package/dist/client/favicon.ico +0 -0
  14. package/dist/client/favicon.png +0 -0
  15. package/dist/client/favicon.svg +5 -9
  16. package/dist/client/index.html +2 -2
  17. package/dist/server/application/group-chat-service.d.ts +3 -0
  18. package/dist/server/application/group-chat-service.js +24 -6
  19. package/dist/server/existing-service.d.ts +12 -0
  20. package/dist/server/existing-service.js +18 -0
  21. package/dist/server/managed-http-tunnel.d.ts +2 -2
  22. package/dist/server/managed-http-tunnel.js +7 -5
  23. package/dist/server/managed-http.js +6 -2
  24. package/dist/server/managed-servers.d.ts +46 -3
  25. package/dist/server/managed-servers.js +194 -19
  26. package/dist/server/managed-ssh.d.ts +14 -1
  27. package/dist/server/managed-ssh.js +55 -5
  28. package/dist/shared/group-chat.d.ts +3 -0
  29. package/dist/shared/group-chat.js +7 -0
  30. package/dist/shared/managed-servers.d.ts +23 -2
  31. package/package.json +5 -1
  32. package/dist/client/assets/index-Cn7hdrDw.js +0 -350
  33. package/dist/client/assets/index-UfzqdECL.css +0 -1
@@ -9,6 +9,7 @@ import { ManagedModelGateway } from "./managed-model-gateway.js";
9
9
  import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
10
10
  import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
11
11
  import { installRemote, startRemote } from "./remote-bootstrap.js";
12
+ import { discoverExistingInstallation } from "./existing-service.js";
12
13
  export class ManagedServers {
13
14
  directory;
14
15
  packageRoot;
@@ -17,6 +18,9 @@ export class ManagedServers {
17
18
  clients = new Map();
18
19
  secrets = new Map();
19
20
  connecting = new Set();
21
+ pendingConnections = new Map();
22
+ verifications = new Map();
23
+ authBlocked = new Set();
20
24
  jobs = new Map();
21
25
  recoveries = new Map();
22
26
  vault;
@@ -75,7 +79,41 @@ export class ManagedServers {
75
79
  this.timer.unref();
76
80
  void this.maintain();
77
81
  }
78
- list() { return [...this.records.values()].map(entry => structuredClone(entry.profile)); }
82
+ list() { return [...this.records.values()].map(entry => structuredClone({ ...entry.profile, verification: this.verifications.get(entry.profile.id)?.challenge })); }
83
+ async cancelConnection(id, reason = "SSH 连接已取消") {
84
+ const pending = this.pendingConnections.get(id);
85
+ this.verifications.get(id)?.reject(new Error(reason));
86
+ this.verifications.delete(id);
87
+ if (pending) {
88
+ pending.controller.abort(new Error(reason));
89
+ await pending.promise.catch(() => { });
90
+ }
91
+ }
92
+ startConnection(id) {
93
+ this.authBlocked.delete(id);
94
+ void this.connect(id).catch(() => { });
95
+ }
96
+ answerVerification(id, verificationId, answers) {
97
+ const pending = this.verifications.get(id);
98
+ if (!pending || pending.challenge.id !== verificationId)
99
+ throw new Error("这轮 SSH 验证已经结束,请使用当前服务器的最新提示");
100
+ if (Date.parse(pending.challenge.expiresAt) <= Date.now())
101
+ throw new Error("这轮 SSH 验证已超时,请重新连接");
102
+ if (!Array.isArray(answers) || answers.length !== pending.challenge.prompts.length || answers.some(answer => typeof answer !== "string" || answer.length > 8192))
103
+ throw new Error("请完成当前验证轮次的全部提示");
104
+ this.verifications.delete(id);
105
+ const profile = this.entry(id).profile;
106
+ profile.ssh = "connecting";
107
+ if (!this.jobs.has(id))
108
+ profile.phase = "connecting";
109
+ pending.resolve(answers);
110
+ }
111
+ async cancelVerification(id, verificationId) {
112
+ if (this.verifications.get(id)?.challenge.id !== verificationId)
113
+ throw new Error("这轮 SSH 验证已经结束,请使用最新提示");
114
+ this.authBlocked.add(id);
115
+ await this.cancelConnection(id, "SSH 交互验证已取消,可重新检测/连接");
116
+ }
79
117
  persist() {
80
118
  const data = JSON.stringify({ servers: [...this.records.values()] }, null, 2);
81
119
  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); });
@@ -93,10 +131,11 @@ export class ManagedServers {
93
131
  const id = input.id ?? randomUUID(), previous = input.id ? this.entry(input.id) : undefined;
94
132
  if (this.jobs.has(id))
95
133
  throw new Error("部署尚未完成,暂不能修改连接");
134
+ await this.cancelConnection(id, "SSH 连接配置已修改,请重新验证");
96
135
  if ([...this.records.values()].some(item => item.profile.id !== id && item.profile.name === input.name.trim()))
97
136
  throw new Error("服务器名称已存在");
98
137
  const old = this.secrets.get(id);
99
- 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") };
138
+ 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"), serviceAccessToken: input.serviceAccessToken || old?.serviceAccessToken };
100
139
  if (input.authentication === "password" && !secret.ssh.password)
101
140
  throw new Error("请输入 SSH 密码");
102
141
  if (input.authentication === "privateKey" && !input.identityFile && !secret.ssh.privateKey)
@@ -108,18 +147,18 @@ export class ManagedServers {
108
147
  delete secret.ssh.passphrase;
109
148
  }
110
149
  const changedHost = previous && (previous.profile.host !== input.host.trim() || previous.profile.sshPort !== input.sshPort || previous.profile.username !== input.username.trim());
111
- if (changedHost && previous.installation)
112
- throw new Error("已部署服务器不能直接改为另一台主机,请添加新的服务器以保护工作区归属");
150
+ if ((changedHost && (previous.installation || previous.compatibility)) || (previous?.compatibility && previous.profile.servicePort !== input.servicePort))
151
+ throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
113
152
  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 };
114
153
  this.clients.get(id)?.end();
115
154
  this.clients.delete(id);
116
155
  await this.vault.write(id, secret);
117
156
  this.secrets.set(id, secret);
118
- this.records.set(id, { ...previous, profile });
157
+ this.records.set(id, { ...(changedHost ? {} : previous), profile });
119
158
  await this.persist();
120
159
  return profile;
121
160
  }
122
- async trust(id, fingerprint) {
161
+ async trust(id, fingerprint, background = false) {
123
162
  const entry = this.entry(id);
124
163
  if (!entry.profile.observedFingerprint || fingerprint !== entry.profile.observedFingerprint)
125
164
  throw new Error("主机指纹已变化,请重新检测后确认");
@@ -127,10 +166,35 @@ export class ManagedServers {
127
166
  delete entry.profile.observedFingerprint;
128
167
  entry.profile.phase = "idle";
129
168
  await this.persist();
130
- await this.connect(id);
169
+ this.authBlocked.delete(id);
170
+ if (background)
171
+ this.startConnection(id);
172
+ else
173
+ await this.connect(id);
131
174
  return this.entry(id).profile;
132
175
  }
133
176
  async connect(id) {
177
+ const pending = this.pendingConnections.get(id);
178
+ if (pending)
179
+ return pending.promise;
180
+ const existing = this.clients.get(id);
181
+ if (existing)
182
+ return existing;
183
+ const controller = new AbortController();
184
+ const promise = this.openConnection(id, controller);
185
+ this.pendingConnections.set(id, { controller, promise });
186
+ try {
187
+ return await promise;
188
+ }
189
+ finally {
190
+ if (this.pendingConnections.get(id)?.promise === promise) {
191
+ this.pendingConnections.delete(id);
192
+ this.connecting.delete(id);
193
+ this.verifications.delete(id);
194
+ }
195
+ }
196
+ }
197
+ async openConnection(id, controller) {
134
198
  const entry = this.entry(id), profile = entry.profile;
135
199
  const existing = this.clients.get(id);
136
200
  if (existing)
@@ -147,8 +211,19 @@ export class ManagedServers {
147
211
  if (profile.phase !== "deploying")
148
212
  profile.phase = "connecting";
149
213
  delete profile.error;
214
+ let requestedVerification = false;
150
215
  try {
151
- const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh });
216
+ const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh }, {
217
+ signal: controller.signal,
218
+ onVerification: challenge => new Promise((resolve, reject) => {
219
+ requestedVerification = true;
220
+ this.verifications.get(id)?.reject(new Error("SSH 服务器已更换验证轮次"));
221
+ const value = { ...challenge, id: randomUUID(), expiresAt: new Date(Date.now() + 180_000).toISOString() };
222
+ this.verifications.set(id, { challenge: value, resolve, reject });
223
+ profile.ssh = "awaitingVerification";
224
+ profile.phase = "awaitingVerification";
225
+ }),
226
+ });
152
227
  if (!profile.enabled || this.stopped) {
153
228
  client.end();
154
229
  throw new Error("连接已取消");
@@ -165,12 +240,18 @@ export class ManagedServers {
165
240
  await this.syncModels(id);
166
241
  await this.ensureService(id);
167
242
  }
168
- else
169
- profile.phase = "idle";
243
+ else {
244
+ await this.detectExisting(id);
245
+ profile.phase = profile.existingService?.attached ? "ready" : "idle";
246
+ }
170
247
  await this.persist();
171
248
  return client;
172
249
  }
173
250
  catch (cause) {
251
+ if (requestedVerification || controller.signal.aborted)
252
+ this.authBlocked.add(id);
253
+ this.verifications.get(id)?.reject(cause instanceof Error ? cause : new Error("SSH 验证已结束"));
254
+ this.verifications.delete(id);
174
255
  const failed = this.clients.get(id);
175
256
  this.clients.delete(id);
176
257
  failed?.end();
@@ -182,9 +263,6 @@ export class ManagedServers {
182
263
  await this.persist();
183
264
  throw cause;
184
265
  }
185
- finally {
186
- this.connecting.delete(id);
187
- }
188
266
  }
189
267
  async reverseModelChannel(entry, client) {
190
268
  if (entry.profile.modelChannel === "online")
@@ -226,6 +304,10 @@ export class ManagedServers {
226
304
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
227
305
  if (!client || !secret)
228
306
  return;
307
+ if (entry.compatibility) {
308
+ await this.detectExisting(id);
309
+ return;
310
+ }
229
311
  try {
230
312
  const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
231
313
  if (info.id !== entry.profile.identity)
@@ -242,6 +324,80 @@ export class ManagedServers {
242
324
  entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
243
325
  }
244
326
  }
327
+ async detectExisting(id) {
328
+ const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
329
+ if (!client || !secret)
330
+ return;
331
+ let found = false;
332
+ try {
333
+ const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.serviceAccessToken ?? "");
334
+ if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
335
+ throw new Error("所选端口不是可识别的 Super Pi 服务");
336
+ found = true;
337
+ entry.profile.existingService = { running: true, attached: false, version: health.runningVersion, dataDirectory: entry.existingInstallation?.dataDir };
338
+ const access = await tunnelJson(client, entry.profile.servicePort, "/api/terminal-shell", secret.serviceAccessToken ?? "");
339
+ if (!access || typeof access !== "object" || !("shell" in access))
340
+ throw new Error("已有服务未提供兼容的管理接口");
341
+ entry.compatibility = true;
342
+ entry.profile.identity ??= randomUUID();
343
+ entry.profile.existingService.attached = true;
344
+ entry.profile.service = "online";
345
+ entry.profile.modelChannel = "offline";
346
+ entry.profile.phase = "ready";
347
+ delete entry.profile.error;
348
+ }
349
+ catch (error) {
350
+ entry.profile.service = "offline";
351
+ if (found) {
352
+ entry.profile.existingService.requiresToken = /401|403/.test(error instanceof Error ? error.message : "");
353
+ entry.profile.error = entry.profile.existingService.requiresToken ? "已有 Super Pi 服务要求访问密钥,请编辑连接填写原服务的访问密钥" : error instanceof Error ? error.message : "已有服务暂不可访问";
354
+ }
355
+ else if (!entry.existingInstallation) {
356
+ entry.existingInstallation = await discoverExistingInstallation(client);
357
+ if (entry.existingInstallation)
358
+ entry.profile.existingService = { running: false, attached: false, version: entry.existingInstallation.version, dataDirectory: entry.existingInstallation.dataDir, hasData: entry.existingInstallation.hasData, canStart: Boolean(entry.existingInstallation.cli && entry.existingInstallation.hasData) };
359
+ }
360
+ else if (entry.profile.existingService) {
361
+ entry.profile.existingService.running = false;
362
+ entry.profile.existingService.attached = false;
363
+ }
364
+ }
365
+ await this.persist();
366
+ }
367
+ startExisting(id) {
368
+ const entry = this.entry(id);
369
+ if (this.jobs.has(id))
370
+ throw new Error("此服务器已有操作进行中");
371
+ if (!entry.existingInstallation?.cli || !entry.existingInstallation.hasData)
372
+ throw new Error("尚未确认原安装及数据目录,不会猜测目录并启动空实例");
373
+ const job = (async () => {
374
+ try {
375
+ entry.profile.phase = "connecting";
376
+ const client = await this.connect(id), old = entry.existingInstallation;
377
+ if (entry.profile.existingService?.attached)
378
+ return;
379
+ this.progress(entry, "启动已有 Super Pi,保留原数据和模型配置");
380
+ await sshExec(client, `SUPER_PI_DATA_DIR=${sh(old.dataDir)} ${sh(old.node)} ${sh(old.cli)} start --no-browser --port ${entry.profile.servicePort}`, { timeout: 90_000 });
381
+ for (let attempt = 0; attempt < 20; attempt++) {
382
+ await this.detectExisting(id);
383
+ if (entry.profile.existingService?.attached)
384
+ return;
385
+ await new Promise(resolve => setTimeout(resolve, 1000));
386
+ }
387
+ throw new Error("原服务尚未启动,请查看原安装的服务日志;未修改其数据或安装包");
388
+ }
389
+ catch (error) {
390
+ entry.profile.phase = "failed";
391
+ entry.profile.error = error instanceof Error ? error.message : "原服务启动失败";
392
+ }
393
+ finally {
394
+ this.jobs.delete(id);
395
+ await this.persist();
396
+ }
397
+ })();
398
+ this.jobs.set(id, job);
399
+ return entry.profile;
400
+ }
245
401
  async ensureService(id) {
246
402
  await this.health(id);
247
403
  const entry = this.entry(id), client = this.clients.get(id);
@@ -282,6 +438,13 @@ export class ManagedServers {
282
438
  try {
283
439
  const client = await this.connect(id);
284
440
  entry.profile.phase = "deploying";
441
+ if (entry.profile.existingService?.running && entry.compatibility) {
442
+ entry.profile.phase = "ready";
443
+ this.progress(entry, "已接入已有服务,原端口、工作区、会话和模型配置保持可用");
444
+ return;
445
+ }
446
+ if (entry.existingInstallation)
447
+ throw new Error("检测到原有 Super Pi 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
285
448
  this.progress(entry, "生成与本地版本一致的纯服务安装包");
286
449
  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; });
287
450
  const artifact = await this.artifact;
@@ -331,6 +494,7 @@ export class ManagedServers {
331
494
  const entry = this.entry(id);
332
495
  if (action === "disconnect") {
333
496
  entry.profile.enabled = false;
497
+ await this.cancelConnection(id);
334
498
  this.clients.get(id)?.end();
335
499
  this.clients.delete(id);
336
500
  entry.profile.ssh = "offline";
@@ -341,19 +505,23 @@ export class ManagedServers {
341
505
  }
342
506
  else if (action === "connect" || action === "test") {
343
507
  entry.profile.enabled = true;
344
- await this.connect(id);
508
+ this.startConnection(id);
345
509
  }
346
510
  else if (action === "sync")
347
511
  await this.syncModels(id, true);
512
+ else if (action === "startExisting")
513
+ return this.startExisting(id);
348
514
  else if (action === "deploy")
349
515
  return this.deploy(id);
350
516
  else if (action === "remove") {
351
517
  if (this.jobs.has(id))
352
518
  throw new Error("部署期间不能移除服务器");
519
+ await this.cancelConnection(id);
353
520
  this.clients.get(id)?.end();
354
521
  this.clients.delete(id);
355
522
  this.records.delete(id);
356
523
  this.secrets.delete(id);
524
+ this.authBlocked.delete(id);
357
525
  await rm(join(this.directory, "credentials", `${id}.secret`), { force: true });
358
526
  }
359
527
  else
@@ -365,7 +533,7 @@ export class ManagedServers {
365
533
  if (this.stopped)
366
534
  return;
367
535
  for (const entry of this.records.values()) {
368
- if (!entry.profile.enabled || this.jobs.has(entry.profile.id) || this.connecting.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
536
+ if (!entry.profile.enabled || this.jobs.has(entry.profile.id) || this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
369
537
  continue;
370
538
  try {
371
539
  if (!this.clients.has(entry.profile.id))
@@ -374,23 +542,30 @@ export class ManagedServers {
374
542
  await this.ensureService(entry.profile.id);
375
543
  await this.syncModels(entry.profile.id);
376
544
  }
545
+ else if (entry.compatibility)
546
+ await this.detectExisting(entry.profile.id);
377
547
  }
378
548
  catch { /* Each record carries its own actionable connection failure. */ }
379
549
  }
380
550
  }
381
- 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 })); }
551
+ connectionProfiles() { return [...this.records.values()].filter(entry => entry.profile.identity).map(entry => ({ id: `ssh-${entry.profile.id}`, managedId: entry.profile.id, managed: true, legacy: Boolean(entry.compatibility), 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 })); }
382
552
  proxy(id, path, request, response) {
383
553
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
384
554
  if (!entry.profile.enabled || !client || !secret) {
385
555
  response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 连接不可用,请在服务器连接设置中查看状态" }));
386
556
  return;
387
557
  }
388
- proxyThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, response, `/managed/${id}`);
558
+ if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
559
+ response.writeHead(request.method === "GET" ? 200 : 405, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify(request.method === "GET" ? { id: entry.profile.identity, protocol: 1, enabled: true, legacy: true } : { error: "已有服务通过 SSH 连接授权,不在此处修改其原授权配置" }));
560
+ return;
561
+ }
562
+ proxyThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
389
563
  }
390
564
  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) {
391
565
  socket.destroy();
392
566
  return;
393
- } await proxyWebSocketThroughSsh(client, entry.profile.servicePort, secret.browserKey, path, request, socket, head); }
394
- async close() { this.stopped = true; clearInterval(this.timer); for (const client of this.clients.values())
567
+ } await proxyWebSocketThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, socket, head, Boolean(entry.compatibility)); }
568
+ async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
569
+ await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
395
570
  client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
396
571
  }
@@ -16,7 +16,20 @@ export declare class HostTrustRequired extends Error {
16
16
  constructor(fingerprint: string, changed: boolean);
17
17
  }
18
18
  export declare const sh: (value: string) => string;
19
- export declare function connectSsh(profile: SshProfile): Promise<Client>;
19
+ export interface SshConnectOptions {
20
+ signal?: AbortSignal;
21
+ handshakeTimeoutMs?: number;
22
+ verificationTimeoutMs?: number;
23
+ onVerification?: (challenge: {
24
+ name: string;
25
+ instruction: string;
26
+ prompts: {
27
+ prompt: string;
28
+ echo: boolean;
29
+ }[];
30
+ }) => Promise<string[]>;
31
+ }
32
+ export declare function connectSsh(profile: SshProfile, options?: SshConnectOptions): Promise<Client>;
20
33
  export declare function sshExec(client: Client, command: string, options?: {
21
34
  timeout?: number;
22
35
  onOutput?: (chunk: string) => void;
@@ -10,14 +10,15 @@ export class HostTrustRequired extends Error {
10
10
  }
11
11
  }
12
12
  export const sh = (value) => `'${value.replaceAll("'", "'\\''")}'`;
13
- export async function connectSsh(profile) {
13
+ export async function connectSsh(profile, options = {}) {
14
+ options.signal?.throwIfAborted();
14
15
  const { Client } = await import("ssh2");
15
16
  const client = new Client();
16
17
  let observed = "";
17
18
  let trusted = false;
18
19
  const settings = {
19
20
  host: profile.host, port: profile.port, username: profile.username,
20
- readyTimeout: 20_000, keepaliveInterval: 15_000, keepaliveCountMax: 3,
21
+ readyTimeout: 0, tryKeyboard: true, keepaliveInterval: 15_000, keepaliveCountMax: 3,
21
22
  hostVerifier: (key) => {
22
23
  observed = `SHA256:${createHash("sha256").update(key).digest("base64").replace(/=+$/, "")}`;
23
24
  trusted = profile.fingerprint === observed;
@@ -33,10 +34,59 @@ export async function connectSsh(profile) {
33
34
  else
34
35
  settings.agent = process.env.SSH_AUTH_SOCK || (process.platform === "win32" ? "\\\\.\\pipe\\openssh-ssh-agent" : undefined);
35
36
  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 连接失败,请检查地址、端口、网络和认证信息")); };
37
+ let settled = false, round = 0, interactive = false;
38
+ let timer;
39
+ const cleanup = () => { clearTimeout(timer); options.signal?.removeEventListener("abort", cancelled); };
40
+ const stop = (reason) => { if (settled)
41
+ return; settled = true; cleanup(); client.destroy(); reject(reason); };
42
+ const arm = (waiting) => {
43
+ clearTimeout(timer);
44
+ timer = setTimeout(() => stop(new Error(waiting ? "SSH 交互验证超时,请重新连接" : "SSH 连接超时,请检查网络后重试")), waiting ? options.verificationTimeoutMs ?? 180_000 : options.handshakeTimeoutMs ?? 20_000);
45
+ };
46
+ const cancelled = () => stop(options.signal?.reason instanceof Error ? options.signal.reason : new Error("SSH 连接已取消"));
47
+ const failed = (error) => stop(observed && !trusted ? new HostTrustRequired(observed, Boolean(profile.fingerprint)) : new Error(error.level === "client-authentication" ? interactive ? "SSH 交互验证未通过,请重新连接后重试" : "SSH 认证失败,请检查用户名和认证信息" : "SSH 连接失败,请检查地址、端口、网络和认证信息"));
48
+ client.once("ready", () => { if (settled)
49
+ return; settled = true; cleanup(); client.removeListener("error", failed); client.on("error", () => { }); resolve(client); });
38
50
  client.once("error", failed);
39
- client.connect(settings);
51
+ client.once("close", () => { if (!settled)
52
+ stop(new Error("SSH 连接在验证完成前关闭,请重新连接")); });
53
+ client.on("keyboard-interactive", (name, instruction, _language, prompts, finish) => {
54
+ if (settled)
55
+ return;
56
+ interactive = true;
57
+ if (!options.onVerification) {
58
+ if (!prompts.length) {
59
+ finish([]);
60
+ return;
61
+ }
62
+ stop(new Error("SSH 服务器要求交互验证,请通过服务器连接设置完成验证"));
63
+ return;
64
+ }
65
+ const currentRound = ++round;
66
+ arm(true);
67
+ void Promise.resolve().then(() => options.onVerification({ name, instruction, prompts: prompts.map(item => ({ prompt: item.prompt, echo: item.echo === true })) })).then(answers => {
68
+ if (settled || currentRound !== round)
69
+ return;
70
+ if (answers.length !== prompts.length || answers.some(answer => typeof answer !== "string")) {
71
+ stop(new Error("SSH 交互验证响应格式无效"));
72
+ return;
73
+ }
74
+ arm(true);
75
+ finish(answers);
76
+ }, reason => stop(reason instanceof Error ? reason : new Error("SSH 交互验证已取消")));
77
+ });
78
+ options.signal?.addEventListener("abort", cancelled, { once: true });
79
+ if (options.signal?.aborted) {
80
+ cancelled();
81
+ return;
82
+ }
83
+ arm(false);
84
+ try {
85
+ client.connect(settings);
86
+ }
87
+ catch (error) {
88
+ stop(error instanceof Error ? error : new Error("无法启动 SSH 连接"));
89
+ }
40
90
  });
41
91
  }
42
92
  export function sshExec(client, command, options = {}) {
@@ -16,6 +16,7 @@ export type GroupMember = {
16
16
  description: string;
17
17
  agentId?: string;
18
18
  worktreePath?: string;
19
+ model?: GroupModel;
19
20
  };
20
21
  export type GroupCloneRequest = {
21
22
  id: string;
@@ -95,6 +96,8 @@ export type GroupReply = GroupPost & {
95
96
  };
96
97
  };
97
98
  export type GroupMessage = GroupUserPost | GroupReply;
99
+ export declare function groupMessageTime(post: GroupMessage): string;
100
+ export declare function groupTimeline(messages: readonly GroupMessage[]): GroupMessage[];
98
101
  export type GroupActivity = {
99
102
  status: "idle" | "running" | "awaiting_background" | "completed" | "failed";
100
103
  revision: number;
@@ -1,5 +1,12 @@
1
1
  import { deriveSessionState } from "./session-reporting.js";
2
2
  export const DEFAULT_GROUP_MEMBER_IDS = ["solution-designer", "code-designer", "code-auditor", "document-organizer"];
3
+ export function groupMessageTime(post) {
4
+ return post.role === "assistant" ? post.settledAt ?? post.createdAt : post.createdAt;
5
+ }
6
+ export function groupTimeline(messages) {
7
+ return messages.filter(post => post.role === "user" || !["queued", "running"].includes(post.status))
8
+ .slice().sort((a, b) => groupMessageTime(a).localeCompare(groupMessageTime(b)));
9
+ }
3
10
  export function groupDisplayState(activity, readAt) {
4
11
  return deriveSessionState({ status: activity.status, quietWhenRead: true,
5
12
  reportingState: activity.lastReplyAt && activity.lastReplyAt > (readAt ?? "") ? "unread" : null });
@@ -1,3 +1,13 @@
1
+ export interface SshVerification {
2
+ id: string;
3
+ name: string;
4
+ instruction: string;
5
+ expiresAt: string;
6
+ prompts: {
7
+ prompt: string;
8
+ echo: boolean;
9
+ }[];
10
+ }
1
11
  export interface ManagedServerProfile {
2
12
  id: string;
3
13
  name: string;
@@ -13,10 +23,20 @@ export interface ManagedServerProfile {
13
23
  identity?: string;
14
24
  deployedAt?: string;
15
25
  remoteRoot?: string;
16
- ssh: "offline" | "connecting" | "online" | "needsTrust";
26
+ ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
17
27
  service: "unknown" | "offline" | "online";
18
28
  modelChannel: "offline" | "online";
19
- phase: "idle" | "connecting" | "needsTrust" | "deploying" | "ready" | "failed";
29
+ phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
30
+ verification?: SshVerification;
31
+ existingService?: {
32
+ running: boolean;
33
+ attached: boolean;
34
+ version?: string;
35
+ dataDirectory?: string;
36
+ hasData?: boolean;
37
+ canStart?: boolean;
38
+ requiresToken?: boolean;
39
+ };
20
40
  step?: string;
21
41
  error?: string;
22
42
  log?: string[];
@@ -33,4 +53,5 @@ export interface ManagedServerInput {
33
53
  password?: string;
34
54
  privateKey?: string;
35
55
  passphrase?: string;
56
+ serviceAccessToken?: string;
36
57
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evandu/super-pi",
3
- "version": "0.1.260",
3
+ "version": "0.1.262",
4
4
  "description": "Web control plane and companion for Pi",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -48,6 +48,8 @@
48
48
  "pack:server": "npm run build && node scripts/pack-server.mjs"
49
49
  },
50
50
  "check:logic": [
51
+ "scripts/existing-service.test.mjs",
52
+ "scripts/ssh-keyboard-interactive.test.mjs",
51
53
  "scripts/title-cold-start.test.mjs",
52
54
  "scripts/desktop-runtime.test.mjs",
53
55
  "scripts/managed-ssh.test.mjs",
@@ -304,6 +306,7 @@
304
306
  "scripts/session-reminder-pmo-rights.test.mjs"
305
307
  ],
306
308
  "check:browser": [
309
+ "scripts/ssh-keyboard-browser.test.mjs",
307
310
  "scripts/desktop-browser.test.mjs",
308
311
  "scripts/managed-remote-install.test.mjs",
309
312
  "scripts/multi-server-browser.test.mjs",
@@ -345,6 +348,7 @@
345
348
  "scripts/right-sidebar-browser.test.mjs",
346
349
  "scripts/background-task-output-browser.test.mjs",
347
350
  "scripts/group-chat-browser.test.mjs",
351
+ "scripts/workbench-search-panel-browser.test.mjs",
348
352
  "scripts/rail-workspace-follows-session-browser.test.mjs",
349
353
  "scripts/git-tab-browser.test.mjs",
350
354
  "scripts/workspace-reopen-browser.test.mjs",