@evandu/super-pi 0.1.263 → 0.1.265

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 (76) hide show
  1. package/README.md +12 -0
  2. package/bin/completion.js +91 -0
  3. package/bin/super-pi.js +11 -1
  4. package/desktop/main.cjs +35 -3
  5. package/desktop/preload.cjs +1 -0
  6. package/desktop/update-lifecycle.cjs +8 -0
  7. package/dist/client/.super-pi-client-sources.json +12 -11
  8. package/dist/client/assets/{CodeMirrorEditor-EhfQhlNI.js → CodeMirrorEditor-B2cHfrUS.js} +2 -2
  9. package/dist/client/assets/GitDiffEditor-Bl7XQIDD.js +29 -0
  10. package/dist/client/assets/dist-3qQVP6l8.js +6 -0
  11. package/dist/client/assets/{dist-BXAOrsjq.js → dist-BlRuQIg1.js} +1 -1
  12. package/dist/client/assets/{dist-BRVQKlcp.js → dist-BvjUKkwy.js} +1 -1
  13. package/dist/client/assets/{dist-QzbOCAU6.js → dist-CQncCwUc.js} +1 -1
  14. package/dist/client/assets/dist-CZ4PyxQu.js +9 -0
  15. package/dist/client/assets/dist-CfTFp0AF.js +2 -0
  16. package/dist/client/assets/dist-CxmJXjJI.js +1 -0
  17. package/dist/client/assets/{dist-Dvb0SqcK.js → dist-D5u1uPmZ.js} +2 -2
  18. package/dist/client/assets/dist-D8HpMxmZ.js +1 -0
  19. package/dist/client/assets/{dist-AW5lyI3I.js → dist-DGBjhKI9.js} +1 -1
  20. package/dist/client/assets/dist-DRBIy9A1.js +1 -0
  21. package/dist/client/assets/dist-Dcww9FSw.js +1 -0
  22. package/dist/client/assets/{dist-moiMRpw_.js → dist-DjI7p99D.js} +1 -1
  23. package/dist/client/assets/dist-DlPa5gNa.js +7 -0
  24. package/dist/client/assets/dist-DxPJ1PN-.js +1 -0
  25. package/dist/client/assets/dist-HXD8sSA4.js +23 -0
  26. package/dist/client/assets/dist-LbeLCeoq.js +1 -0
  27. package/dist/client/assets/dist-ONdtnupI.js +1 -0
  28. package/dist/client/assets/dist-YqmXusLA.js +11 -0
  29. package/dist/client/assets/dist-ZAR1Tu2c.js +3 -0
  30. package/dist/client/assets/{dist-Cus6_oaF.js → dist-i79xiXVk.js} +2 -2
  31. package/dist/client/assets/index-Cl8iehsn.css +1 -0
  32. package/dist/client/assets/index-DW2nd-Cf.js +350 -0
  33. package/dist/client/index.html +2 -2
  34. package/dist/server/application/provider-service.d.ts +1 -0
  35. package/dist/server/application/provider-service.js +12 -2
  36. package/dist/server/http-server.js +105 -41
  37. package/dist/server/managed-http-direct.d.ts +9 -0
  38. package/dist/server/managed-http-direct.js +100 -0
  39. package/dist/server/managed-http.js +14 -0
  40. package/dist/server/managed-servers.d.ts +17 -1
  41. package/dist/server/managed-servers.js +196 -30
  42. package/dist/server/pi-session.js +1 -1
  43. package/dist/server/published-server-update.d.ts +6 -0
  44. package/dist/server/published-server-update.js +54 -0
  45. package/dist/server/read-receipts.d.ts +10 -0
  46. package/dist/server/read-receipts.js +55 -0
  47. package/dist/server/update-status.d.ts +3 -1
  48. package/dist/server/update-status.js +5 -3
  49. package/dist/shared/directory-completion.d.ts +5 -0
  50. package/dist/shared/directory-completion.js +10 -0
  51. package/dist/shared/managed-servers.d.ts +15 -0
  52. package/dist/shared/managed-servers.js +3 -1
  53. package/dist/shared/read-receipts.d.ts +7 -0
  54. package/dist/shared/read-receipts.js +3 -0
  55. package/dist/shared/update-status.d.ts +1 -1
  56. package/dist/shared/update-status.js +1 -1
  57. package/package.json +14 -1
  58. package/scripts/restart-process.mjs +11 -0
  59. package/scripts/restart-server.mjs +2 -2
  60. package/dist/client/assets/GitDiffEditor-Fd--uK9q.js +0 -29
  61. package/dist/client/assets/dist-B3-a6uF0.js +0 -7
  62. package/dist/client/assets/dist-BGxkyh6e.js +0 -1
  63. package/dist/client/assets/dist-BJxfd7yb.js +0 -11
  64. package/dist/client/assets/dist-BV64A9Ji.js +0 -1
  65. package/dist/client/assets/dist-CKF2Jksy.js +0 -1
  66. package/dist/client/assets/dist-CX_Hm4GS.js +0 -1
  67. package/dist/client/assets/dist-Cx00EZKR.js +0 -23
  68. package/dist/client/assets/dist-D71y2EI1.js +0 -1
  69. package/dist/client/assets/dist-Dc1MBGAG.js +0 -1
  70. package/dist/client/assets/dist-Dds-qLxY.js +0 -9
  71. package/dist/client/assets/dist-DeD9copn.js +0 -1
  72. package/dist/client/assets/dist-DuvGReu-.js +0 -6
  73. package/dist/client/assets/dist-J6XWqRpB.js +0 -3
  74. package/dist/client/assets/dist-scBkrwv-.js +0 -2
  75. package/dist/client/assets/index-Cs_T0IFR.js +0 -350
  76. package/dist/client/assets/index-D6ei0DbU.css +0 -1
@@ -10,6 +10,8 @@ import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-
10
10
  import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
11
11
  import { installRemote, startRemote } from "./remote-bootstrap.js";
12
12
  import { discoverExistingInstallation } from "./existing-service.js";
13
+ import { publishedServerUpdate } from "./published-server-update.js";
14
+ import { directJson, serviceOrigin, defaultServiceOrigin, probeServiceEndpoint, proxyThroughDirect, proxyWebSocketThroughDirect } from "./managed-http-direct.js";
13
15
  export class ManagedServers {
14
16
  directory;
15
17
  packageRoot;
@@ -29,6 +31,7 @@ export class ManagedServers {
29
31
  gatewayPort = 0;
30
32
  timer;
31
33
  stopped = false;
34
+ maintaining = false;
32
35
  persistence = Promise.resolve();
33
36
  artifact;
34
37
  constructor(directory, packageRoot, defaultModel) {
@@ -44,7 +47,14 @@ export class ManagedServers {
44
47
  for (const entry of data.servers ?? []) {
45
48
  if (!/^[a-f0-9-]+$/.test(entry.profile?.id))
46
49
  continue;
50
+ entry.profile.serviceUrl ??= defaultServiceOrigin(entry.profile.host, entry.profile.servicePort);
47
51
  entry.profile = { ...entry.profile, ssh: "offline", service: "unknown", modelChannel: "offline", phase: entry.profile.phase === "deploying" ? "failed" : "idle", error: entry.profile.phase === "deploying" ? "本地管理服务在部署期间重启,请检查后重试部署" : undefined };
52
+ if (entry.profile.updateOperation && ["waiting", "installing", "restarting"].includes(entry.profile.updateOperation.phase)) {
53
+ const operation = entry.profile.updateOperation;
54
+ operation.failure = { step: operation.phase === "restarting" ? "restarting" : "installing", message: "本地管理服务在远端更新期间退出,请检测远端版本后重试。" };
55
+ operation.phase = "failed";
56
+ operation.changedAt = new Date().toISOString();
57
+ }
48
58
  this.records.set(entry.profile.id, entry);
49
59
  const secret = await this.vault.read(entry.profile.id);
50
60
  if (secret)
@@ -80,6 +90,16 @@ export class ManagedServers {
80
90
  void this.maintain();
81
91
  }
82
92
  list() { return [...this.records.values()].map(entry => structuredClone({ ...entry.profile, verification: this.verifications.get(entry.profile.id)?.challenge })); }
93
+ async probeService(input) {
94
+ const stored = input.id ? this.entry(input.id) : undefined;
95
+ const host = input.host ?? stored?.profile.host, port = input.servicePort ?? stored?.profile.servicePort;
96
+ if (typeof host !== "string" || !host || /[\s/\\\0]/.test(host) || !Number.isInteger(port) || port < 1 || port > 65535 || (input.serviceUrl !== undefined && typeof input.serviceUrl !== "string"))
97
+ throw new Error("请填写有效的服务器 IP 和 Super Pi 端口");
98
+ const address = input.serviceUrl?.trim() || (input.serviceUrl === undefined ? stored?.profile.serviceUrl : undefined) || defaultServiceOrigin(host, port);
99
+ const secret = input.id ? this.secrets.get(input.id) : undefined;
100
+ const key = input.serviceAccessToken || (stored?.installation ? secret?.browserKey : secret?.serviceAccessToken) || "";
101
+ return probeServiceEndpoint(address, key);
102
+ }
83
103
  async cancelConnection(id, reason = "SSH 连接已取消") {
84
104
  const pending = this.pendingConnections.get(id);
85
105
  this.verifications.get(id)?.reject(new Error(reason));
@@ -150,6 +170,9 @@ export class ManagedServers {
150
170
  if ((changedHost && (previous.installation || previous.compatibility)) || (previous?.compatibility && previous.profile.servicePort !== input.servicePort))
151
171
  throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
152
172
  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 };
173
+ profile.serviceUrl = input.serviceUrl?.trim() ? serviceOrigin(input.serviceUrl.trim()) : defaultServiceOrigin(profile.host, profile.servicePort);
174
+ profile.transport = undefined;
175
+ profile.serviceError = undefined;
153
176
  this.clients.get(id)?.end();
154
177
  this.clients.delete(id);
155
178
  await this.vault.write(id, secret);
@@ -231,10 +254,11 @@ export class ManagedServers {
231
254
  this.clients.set(id, client);
232
255
  profile.ssh = "online";
233
256
  client.once("close", () => { if (this.clients.get(id) !== client)
234
- return; this.clients.delete(id); profile.ssh = "offline"; profile.service = "offline"; profile.modelChannel = "offline"; if (profile.phase !== "deploying") {
235
- profile.phase = "idle";
236
- profile.error = "SSH 连接中断,正在自动重连";
237
- } void this.persist(); });
257
+ return; this.clients.delete(id); profile.ssh = "offline"; if (profile.transport !== "direct")
258
+ profile.service = "unknown"; profile.modelChannel = "offline"; if (profile.phase !== "deploying") {
259
+ profile.phase = profile.service === "online" ? "ready" : "idle";
260
+ profile.error = "SSH 连接中断,服务直连状态独立检测";
261
+ } void this.checkDirect(id); void this.persist(); });
238
262
  if (entry.installation) {
239
263
  await this.reverseModelChannel(entry, client);
240
264
  await this.syncModels(id);
@@ -302,6 +326,8 @@ export class ManagedServers {
302
326
  }
303
327
  async health(id) {
304
328
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
329
+ if (await this.checkDirect(id))
330
+ return;
305
331
  if (!client || !secret)
306
332
  return;
307
333
  if (entry.compatibility) {
@@ -313,6 +339,7 @@ export class ManagedServers {
313
339
  if (info.id !== entry.profile.identity)
314
340
  throw new Error("端口上运行的不是此托管服务,请检查端口冲突");
315
341
  entry.profile.service = "online";
342
+ entry.profile.transport = "ssh";
316
343
  if (!this.jobs.has(id))
317
344
  entry.profile.phase = "ready";
318
345
  delete entry.profile.error;
@@ -324,6 +351,47 @@ export class ManagedServers {
324
351
  entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
325
352
  }
326
353
  }
354
+ async checkDirect(id) {
355
+ const entry = this.entry(id), secret = this.secrets.get(id), profile = entry.profile;
356
+ if (!profile.enabled || !profile.serviceUrl || !secret)
357
+ return false;
358
+ try {
359
+ const key = entry.installation ? secret.browserKey : secret.serviceAccessToken ?? "";
360
+ const health = await directJson(profile.serviceUrl, "/api/health", key);
361
+ if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
362
+ throw new Error("直连地址不是 Super Pi 服务");
363
+ if (entry.installation) {
364
+ const identity = await directJson(profile.serviceUrl, "/api/browser-access", key);
365
+ if (identity.id !== profile.identity)
366
+ throw new Error("直连地址的服务器身份不匹配,请检查地址和端口");
367
+ }
368
+ else {
369
+ const access = await directJson(profile.serviceUrl, "/api/terminal-shell", key);
370
+ if (!access || typeof access !== "object" || !("shell" in access))
371
+ throw new Error("直连服务尚未通过访问授权");
372
+ const newlyAttached = !entry.compatibility || !profile.identity;
373
+ entry.compatibility = true;
374
+ profile.identity ??= randomUUID();
375
+ profile.existingService = { ...profile.existingService, running: true, attached: true, version: health.runningVersion };
376
+ if (newlyAttached)
377
+ await this.persist();
378
+ }
379
+ profile.transport = "direct";
380
+ profile.service = "online";
381
+ delete profile.serviceError;
382
+ if (!this.jobs.has(id) && !this.connecting.has(id))
383
+ profile.phase = "ready";
384
+ return true;
385
+ }
386
+ catch (error) {
387
+ profile.serviceError = error instanceof Error ? error.message : "Super Pi 直连不可达";
388
+ if (!this.clients.has(id)) {
389
+ profile.service = "offline";
390
+ profile.transport = undefined;
391
+ }
392
+ return false;
393
+ }
394
+ }
327
395
  async detectExisting(id) {
328
396
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
329
397
  if (!client || !secret)
@@ -342,6 +410,7 @@ export class ManagedServers {
342
410
  entry.profile.identity ??= randomUUID();
343
411
  entry.profile.existingService.attached = true;
344
412
  entry.profile.service = "online";
413
+ entry.profile.transport = "ssh";
345
414
  entry.profile.modelChannel = "offline";
346
415
  entry.profile.phase = "ready";
347
416
  delete entry.profile.error;
@@ -425,12 +494,22 @@ export class ManagedServers {
425
494
  }
426
495
  void this.persist();
427
496
  }
428
- deploy(id) {
497
+ deploy(id, updateVersion) {
429
498
  const entry = this.entry(id);
430
499
  if (this.jobs.has(id))
431
500
  throw new Error("此服务器已有部署进行中");
432
501
  if (!entry.profile.fingerprint)
433
502
  throw new Error("请先测试 SSH 并确认主机指纹");
503
+ if (updateVersion) {
504
+ if (!entry.installation || entry.compatibility)
505
+ throw new Error("此连接不是托管实例,应使用原服务的软件更新接口");
506
+ if (!entry.profile.enabled || !this.clients.has(id))
507
+ throw new Error("SSH 未连接,请连接后重试更新");
508
+ if (!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/i.test(updateVersion))
509
+ throw new Error("目标版本无效");
510
+ const at = new Date().toISOString();
511
+ entry.profile.updateOperation = { id: randomUUID(), action: "update", phase: "installing", fromVersion: "", targetVersion: updateVersion, startedAt: at, changedAt: at };
512
+ }
434
513
  entry.profile.phase = "deploying";
435
514
  entry.profile.log = [];
436
515
  delete entry.profile.error;
@@ -445,9 +524,10 @@ export class ManagedServers {
445
524
  }
446
525
  if (entry.existingInstallation)
447
526
  throw new Error("检测到原有 Super Pi 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
448
- this.progress(entry, "生成与本地版本一致的纯服务安装包");
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; });
450
- const artifact = await this.artifact;
527
+ this.progress(entry, updateVersion ? "下载并校验目标版本的纯服务安装包" : "生成与本地版本一致的纯服务安装包");
528
+ if (!updateVersion)
529
+ 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; });
530
+ const artifact = updateVersion ? await publishedServerUpdate(updateVersion, join(this.directory, "packages")) : await this.artifact;
451
531
  if (entry.profile.service === "online") {
452
532
  const state = await tunnelJson(client, entry.profile.servicePort, "/api/conversations", this.secrets.get(id).browserKey);
453
533
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
@@ -464,6 +544,10 @@ export class ManagedServers {
464
544
  entry.modelHash = undefined;
465
545
  await this.syncModels(id);
466
546
  this.progress(entry, "启动远端 Super Pi 服务");
547
+ if (entry.profile.updateOperation && updateVersion) {
548
+ entry.profile.updateOperation.phase = "restarting";
549
+ entry.profile.updateOperation.changedAt = new Date().toISOString();
550
+ }
467
551
  await startRemote(client, installation, entry.profile.servicePort);
468
552
  for (let attempt = 0; attempt < 30; attempt++) {
469
553
  await this.health(id);
@@ -473,6 +557,15 @@ export class ManagedServers {
473
557
  }
474
558
  if (entry.profile.service !== "online")
475
559
  throw new Error("远端服务未能启动,请查看部署记录及远端 service.log");
560
+ if (updateVersion) {
561
+ const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.browserKey);
562
+ if (health.runningVersion !== updateVersion)
563
+ throw new Error("远端尚未运行目标版本,请查看远端 service.log");
564
+ if (entry.profile.updateOperation) {
565
+ entry.profile.updateOperation.phase = "completed";
566
+ entry.profile.updateOperation.changedAt = new Date().toISOString();
567
+ }
568
+ }
476
569
  entry.profile.deployedAt = new Date().toISOString();
477
570
  entry.profile.phase = "ready";
478
571
  this.progress(entry, "已接入,本地配置的模型可直接用于远端会话");
@@ -480,6 +573,12 @@ export class ManagedServers {
480
573
  catch (cause) {
481
574
  entry.profile.phase = "failed";
482
575
  entry.profile.error = cause instanceof Error ? cause.message : "部署失败";
576
+ if (updateVersion && entry.profile.updateOperation) {
577
+ const operation = entry.profile.updateOperation;
578
+ operation.failure = { step: operation.phase === "restarting" ? "restarting" : "installing", message: entry.profile.error };
579
+ operation.phase = "failed";
580
+ operation.changedAt = new Date().toISOString();
581
+ }
483
582
  }
484
583
  finally {
485
584
  this.jobs.delete(id);
@@ -490,6 +589,26 @@ export class ManagedServers {
490
589
  void this.persist();
491
590
  return entry.profile;
492
591
  }
592
+ updateSelected(updates) {
593
+ if (updates.length > 64 || new Set(updates.map(item => item.id)).size !== updates.length)
594
+ throw new Error("更新目标无效或重复");
595
+ const started = [], errors = {};
596
+ for (const item of updates) {
597
+ try {
598
+ const entry = this.entry(item.id);
599
+ if (!entry.installation || entry.compatibility || !entry.profile.enabled || !this.clients.has(item.id) || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/i.test(item.version))
600
+ throw new Error(`无法更新 ${entry.profile.name}:请检查 SSH 连接和目标版本`);
601
+ if (!this.jobs.has(item.id))
602
+ this.deploy(item.id, item.version);
603
+ started.push(item.id);
604
+ }
605
+ catch (error) {
606
+ errors[item.id] = error instanceof Error ? error.message : "无法启动更新";
607
+ }
608
+ }
609
+ return { started, errors };
610
+ }
611
+ async waitForUpdates(ids) { await Promise.allSettled(ids.map(id => this.jobs.get(id))); }
493
612
  async action(id, action) {
494
613
  const entry = this.entry(id);
495
614
  if (action === "disconnect") {
@@ -503,7 +622,24 @@ export class ManagedServers {
503
622
  entry.profile.phase = "idle";
504
623
  delete entry.profile.error;
505
624
  }
625
+ else if (action === "disconnectSsh") {
626
+ this.authBlocked.add(id);
627
+ await this.cancelConnection(id);
628
+ this.clients.get(id)?.end();
629
+ this.clients.delete(id);
630
+ entry.profile.ssh = "offline";
631
+ entry.profile.modelChannel = "offline";
632
+ if (!(await this.checkDirect(id))) {
633
+ entry.profile.service = "unknown";
634
+ entry.profile.phase = "idle";
635
+ }
636
+ }
506
637
  else if (action === "connect" || action === "test") {
638
+ entry.profile.enabled = true;
639
+ if (!(await this.checkDirect(id)))
640
+ this.startConnection(id);
641
+ }
642
+ else if (action === "connectSsh") {
507
643
  entry.profile.enabled = true;
508
644
  this.startConnection(id);
509
645
  }
@@ -530,41 +666,71 @@ export class ManagedServers {
530
666
  return this.records.get(id)?.profile;
531
667
  }
532
668
  async maintain() {
533
- if (this.stopped)
669
+ if (this.stopped || this.maintaining)
534
670
  return;
535
- for (const entry of this.records.values()) {
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")
537
- continue;
538
- try {
539
- if (!this.clients.has(entry.profile.id))
540
- await this.connect(entry.profile.id);
541
- else if (entry.installation) {
542
- await this.ensureService(entry.profile.id);
543
- await this.syncModels(entry.profile.id);
671
+ this.maintaining = true;
672
+ try {
673
+ const check = async (entry) => {
674
+ if (!entry.profile.enabled || this.jobs.has(entry.profile.id))
675
+ return;
676
+ if (await this.checkDirect(entry.profile.id)) {
677
+ if (entry.installation && this.clients.has(entry.profile.id) && entry.profile.modelChannel === "online")
678
+ await this.syncModels(entry.profile.id).catch(() => { });
679
+ return;
544
680
  }
545
- else if (entry.compatibility)
546
- await this.detectExisting(entry.profile.id);
547
- }
548
- catch { /* Each record carries its own actionable connection failure. */ }
681
+ if (this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
682
+ return;
683
+ try {
684
+ if (!this.clients.has(entry.profile.id))
685
+ this.startConnection(entry.profile.id);
686
+ else if (entry.installation) {
687
+ await this.ensureService(entry.profile.id);
688
+ await this.syncModels(entry.profile.id);
689
+ }
690
+ else if (entry.compatibility)
691
+ await this.detectExisting(entry.profile.id);
692
+ }
693
+ catch { /* Each record carries its own actionable connection failure. */ }
694
+ };
695
+ const entries = [...this.records.values()];
696
+ for (let offset = 0; offset < entries.length; offset += 4)
697
+ await Promise.allSettled(entries.slice(offset, offset + 4).map(check));
698
+ }
699
+ finally {
700
+ this.maintaining = false;
549
701
  }
550
702
  }
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 })); }
703
+ connectionProfiles() { return [...this.records.values()].filter(entry => entry.profile.identity).map(entry => ({ id: `ssh-${entry.profile.id}`, managedId: entry.profile.id, managed: true, transport: entry.profile.transport, 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 })); }
552
704
  proxy(id, path, request, response) {
553
705
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
554
- if (!entry.profile.enabled || !client || !secret) {
555
- response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "SSH 连接不可用,请在服务器连接设置中查看状态" }));
706
+ const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
707
+ if (!entry.profile.enabled || (!client && !direct) || !secret) {
708
+ response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "Super Pi 访问通道不可用,请检查服务直连地址或 SSH 隧道" }));
556
709
  return;
557
710
  }
558
711
  if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
559
712
  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
713
  return;
561
714
  }
562
- proxyThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
715
+ const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
716
+ if (direct)
717
+ proxyThroughDirect(direct, key, path, request, response, `/managed/${id}`);
718
+ else
719
+ proxyThroughSsh(client, entry.profile.servicePort, key, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
720
+ }
721
+ async upgrade(id, path, request, socket, head) {
722
+ const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
723
+ const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
724
+ if (!entry.profile.enabled || (!client && !direct) || !secret) {
725
+ socket.destroy();
726
+ return;
727
+ }
728
+ const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
729
+ if (direct)
730
+ proxyWebSocketThroughDirect(direct, key, path, request, socket, head);
731
+ else
732
+ await proxyWebSocketThroughSsh(client, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
563
733
  }
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) {
565
- socket.destroy();
566
- return;
567
- } await proxyWebSocketThroughSsh(client, entry.profile.servicePort, entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey, path, request, socket, head, Boolean(entry.compatibility)); }
568
734
  async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
569
735
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
570
736
  client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
@@ -131,7 +131,7 @@ export async function createSdkCatalog(cwd) {
131
131
  if (!modelRuntime.login)
132
132
  throw new Error("当前 Pi SDK 不支持供应商登录。");
133
133
  await modelRuntime.login(providerId, "oauth", interaction, { agentName: "Super Pi" });
134
- await modelRuntime.refresh?.();
134
+ // Credential persistence is the login boundary; catalog refresh belongs to ProviderService.
135
135
  },
136
136
  logoutOAuth: async (providerId) => {
137
137
  if (!modelRuntime.logout)
@@ -0,0 +1,6 @@
1
+ export interface ServerUpdateArtifact {
2
+ path: string;
3
+ version: string;
4
+ shasum: string;
5
+ }
6
+ export declare function publishedServerUpdate(version: string, directory: string): Promise<ServerUpdateArtifact>;
@@ -0,0 +1,54 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ const pending = new Map();
5
+ export function publishedServerUpdate(version, directory) {
6
+ const key = JSON.stringify([version, directory]);
7
+ const existing = pending.get(key);
8
+ if (existing)
9
+ return existing;
10
+ const operation = downloadServerUpdate(version, directory).finally(() => pending.delete(key));
11
+ pending.set(key, operation);
12
+ return operation;
13
+ }
14
+ async function downloadServerUpdate(version, directory) {
15
+ if (!/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/i.test(version))
16
+ throw new Error("远端目标版本无效");
17
+ let failure;
18
+ for (let attempt = 0; attempt < 3; attempt++) {
19
+ try {
20
+ const response = await fetch(`https://registry.npmjs.org/@evandu%2Fsuper-pi-server/${encodeURIComponent(version)}`, { signal: AbortSignal.timeout(20_000) });
21
+ if (!response.ok)
22
+ throw new Error(`纯服务包版本尚不可用(HTTP ${response.status})`);
23
+ const metadata = await response.json();
24
+ const url = new URL(metadata.dist?.tarball ?? "");
25
+ const shasum = metadata.dist?.shasum ?? "";
26
+ if (metadata.version !== version || !/^[a-f0-9]{40}$/i.test(shasum) || url.protocol !== "https:" || url.hostname !== "registry.npmjs.org" || !url.pathname.startsWith("/@evandu/super-pi-server/-/"))
27
+ throw new Error("纯服务安装包元数据校验失败");
28
+ await mkdir(directory, { recursive: true });
29
+ const path = join(directory, `server-${shasum}.tgz`);
30
+ const valid = (bytes) => createHash("sha1").update(bytes).digest("hex") === shasum;
31
+ try {
32
+ if (valid(await readFile(path)))
33
+ return { path, version, shasum };
34
+ }
35
+ catch { /* A verified cached archive can be reused. */ }
36
+ const archive = await fetch(url, { signal: AbortSignal.timeout(180_000) });
37
+ if (!archive.ok)
38
+ throw new Error(`下载纯服务安装包失败(HTTP ${archive.status})`);
39
+ const bytes = Buffer.from(await archive.arrayBuffer());
40
+ if (!valid(bytes))
41
+ throw new Error("纯服务安装包校验和不一致");
42
+ const temporary = `${path}.${process.pid}.tmp`;
43
+ await writeFile(temporary, bytes, { mode: 0o600 });
44
+ await rename(temporary, path);
45
+ return { path, version, shasum };
46
+ }
47
+ catch (error) {
48
+ failure = error;
49
+ if (attempt < 2)
50
+ await new Promise(resolve => setTimeout(resolve, 750 * (attempt + 1)));
51
+ }
52
+ }
53
+ throw failure instanceof Error ? failure : new Error("无法获取纯服务安装包");
54
+ }
@@ -0,0 +1,10 @@
1
+ import { type ReadReceipt } from "../shared/read-receipts.js";
2
+ /** Owner-scoped progress, separate from browser layout preferences and conversation content. */
3
+ export declare class ReadReceipts {
4
+ private readonly path;
5
+ private records;
6
+ constructor(path: string, baseline: ReadReceipt[]);
7
+ list(): ReadReceipt[];
8
+ merge(values: unknown, latest: (value: ReadReceipt) => string | undefined): ReadReceipt[];
9
+ private persist;
10
+ }
@@ -0,0 +1,55 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { receiptKey } from "../shared/read-receipts.js";
4
+ /** Owner-scoped progress, separate from browser layout preferences and conversation content. */
5
+ export class ReadReceipts {
6
+ path;
7
+ records = new Map();
8
+ constructor(path, baseline) {
9
+ this.path = path;
10
+ if (existsSync(path)) {
11
+ // A damaged file is an error, never a reason to silently mark new results as read.
12
+ const saved = JSON.parse(readFileSync(path, "utf8"));
13
+ if (saved.version !== 1 || !Array.isArray(saved.receipts))
14
+ throw new Error("已读记录格式不正确");
15
+ for (const record of saved.receipts)
16
+ this.records.set(receiptKey(record), record);
17
+ }
18
+ else {
19
+ for (const record of baseline)
20
+ this.records.set(receiptKey(record), record);
21
+ this.persist(this.records);
22
+ }
23
+ }
24
+ list() { return [...this.records.values()].map(value => ({ ...value })); }
25
+ merge(values, latest) {
26
+ if (!Array.isArray(values) || values.length > 500)
27
+ throw new Error("每次最多同步 500 条已读记录");
28
+ const next = new Map(this.records);
29
+ for (const item of values) {
30
+ if (!item || typeof item.workspaceId !== "string" || !item.workspaceId ||
31
+ (typeof item.conversationId === "string") === (typeof item.roomId === "string") ||
32
+ !(item.conversationId ?? item.roomId) || typeof item.at !== "string" || !Number.isFinite(Date.parse(item.at)))
33
+ throw new Error("已读记录参数不正确");
34
+ const at = latest(item);
35
+ if (!at)
36
+ throw new Error("已读记录不属于指定工作区,或消息尚不存在");
37
+ const value = { workspaceId: item.workspaceId,
38
+ ...(item.conversationId ? { conversationId: item.conversationId } : { roomId: item.roomId }),
39
+ at: new Date(Math.min(Date.parse(item.at), Date.parse(at))).toISOString() };
40
+ const key = receiptKey(value);
41
+ if (value.at > (next.get(key)?.at ?? ""))
42
+ next.set(key, value);
43
+ }
44
+ // Commit to memory only after the complete batch has been validated and saved.
45
+ this.persist(next);
46
+ this.records = next;
47
+ return this.list();
48
+ }
49
+ persist(records) {
50
+ mkdirSync(dirname(this.path), { recursive: true });
51
+ const temporary = `${this.path}.tmp`;
52
+ writeFileSync(temporary, JSON.stringify({ version: 1, receipts: [...records.values()] }), { mode: 0o600 });
53
+ renameSync(temporary, this.path);
54
+ }
55
+ }
@@ -7,7 +7,9 @@ export declare class UpdateTracker {
7
7
  constructor(file: string, root: string);
8
8
  private save;
9
9
  snapshot(): UpdateStatus;
10
- begin(action: UpdateOperation["action"], targetVersion?: string): string;
10
+ begin(action: UpdateOperation["action"], targetVersion?: string, waiting?: boolean): string;
11
+ installing(id: string): void;
12
+ readyToRestart(id: string): void;
11
13
  private change;
12
14
  restarting(id: string, targetVersion: string): void;
13
15
  fail(id: string, step: "installing" | "restarting", message: string, code?: number): void;
@@ -12,7 +12,7 @@ export class UpdateTracker {
12
12
  this.root = root;
13
13
  try {
14
14
  const value = JSON.parse(readFileSync(file, "utf8"));
15
- if (value?.id && ["installing", "restarting", "completed", "failed"].includes(value.phase))
15
+ if (value?.id && ["waiting", "installing", "restarting", "completed", "failed"].includes(value.phase))
16
16
  this.operation = value;
17
17
  }
18
18
  catch { /* A new service has no update history. */ }
@@ -35,15 +35,17 @@ export class UpdateTracker {
35
35
  renameSync(temporary, this.file);
36
36
  }
37
37
  snapshot() { return { ...checkDiskVersion(this.root), operation: this.operation }; }
38
- begin(action, targetVersion) {
38
+ begin(action, targetVersion, waiting = false) {
39
39
  const { runningVersion } = checkDiskVersion(this.root);
40
40
  const startedAt = new Date().toISOString();
41
- const operation = { id: randomUUID(), action, phase: action === "update" ? "installing" : "restarting",
41
+ const operation = { id: randomUUID(), action, phase: waiting ? "waiting" : action === "update" ? "installing" : "restarting",
42
42
  fromVersion: runningVersion, targetVersion, startedAt, changedAt: startedAt };
43
43
  this.save(operation);
44
44
  this.operation = operation;
45
45
  return operation.id;
46
46
  }
47
+ installing(id) { this.change(id, { phase: "installing" }); }
48
+ readyToRestart(id) { this.change(id, { phase: "restarting" }); }
47
49
  change(id, change) {
48
50
  if (this.operation?.id !== id || !updateIsActive(this.operation))
49
51
  return;
@@ -0,0 +1,5 @@
1
+ /** Split only the unfinished last component; traversal stays on the selected server. */
2
+ export declare function directoryCompletion(input: string, current: string): {
3
+ path: string;
4
+ prefix: string;
5
+ };
@@ -0,0 +1,10 @@
1
+ /** Split only the unfinished last component; traversal stays on the selected server. */
2
+ export function directoryCompletion(input, current) {
3
+ const value = input.trim();
4
+ if (!value || value === current)
5
+ return { path: current, prefix: "" };
6
+ const separator = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
7
+ if (separator < 0)
8
+ return value === "~" ? { path: "~", prefix: "" } : { path: current, prefix: value };
9
+ return { path: value.slice(0, separator + 1), prefix: value.slice(separator + 1) };
10
+ }
@@ -8,6 +8,16 @@ export interface SshVerification {
8
8
  echo: boolean;
9
9
  }[];
10
10
  }
11
+ export type ServiceProbe = {
12
+ reachable: boolean;
13
+ service: boolean;
14
+ authorized: boolean;
15
+ address: string;
16
+ latencyMs: number;
17
+ status?: number;
18
+ message: string;
19
+ };
20
+ export declare function defaultServiceUrl(host: string, port: number): string;
11
21
  export interface ManagedServerProfile {
12
22
  id: string;
13
23
  name: string;
@@ -23,6 +33,9 @@ export interface ManagedServerProfile {
23
33
  identity?: string;
24
34
  deployedAt?: string;
25
35
  remoteRoot?: string;
36
+ serviceUrl?: string;
37
+ transport?: "direct" | "ssh";
38
+ serviceError?: string;
26
39
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
27
40
  service: "unknown" | "offline" | "online";
28
41
  modelChannel: "offline" | "online";
@@ -40,6 +53,7 @@ export interface ManagedServerProfile {
40
53
  step?: string;
41
54
  error?: string;
42
55
  log?: string[];
56
+ updateOperation?: import("./update-status.js").UpdateOperation;
43
57
  }
44
58
  export interface ManagedServerInput {
45
59
  id?: string;
@@ -54,4 +68,5 @@ export interface ManagedServerInput {
54
68
  privateKey?: string;
55
69
  passphrase?: string;
56
70
  serviceAccessToken?: string;
71
+ serviceUrl?: string;
57
72
  }
@@ -1 +1,3 @@
1
- export {};
1
+ export function defaultServiceUrl(host, port) {
2
+ return new URL(`http://${host.includes(":") && !host.startsWith("[") ? `[${host}]` : host}:${port}`).origin;
3
+ }
@@ -0,0 +1,7 @@
1
+ export type ReadReceipt = {
2
+ workspaceId: string;
3
+ conversationId?: string;
4
+ roomId?: string;
5
+ at: string;
6
+ };
7
+ export declare function receiptKey(value: ReadReceipt): string;
@@ -0,0 +1,3 @@
1
+ export function receiptKey(value) {
2
+ return JSON.stringify([value.workspaceId, value.conversationId ? "session" : "group", value.conversationId ?? value.roomId]);
3
+ }
@@ -3,7 +3,7 @@ export type UpdateVersions = {
3
3
  diskVersion: string;
4
4
  needsRestart: boolean;
5
5
  };
6
- export type UpdatePhase = "installing" | "restarting" | "completed" | "failed";
6
+ export type UpdatePhase = "waiting" | "installing" | "restarting" | "completed" | "failed";
7
7
  export type UpdateOperation = {
8
8
  id: string;
9
9
  action: "update" | "restart";
@@ -1 +1 @@
1
- export const updateIsActive = (operation) => operation?.phase === "installing" || operation?.phase === "restarting";
1
+ export const updateIsActive = (operation) => operation?.phase === "waiting" || operation?.phase === "installing" || operation?.phase === "restarting";