@evandu/super-pi 0.1.270 → 0.1.271

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.
@@ -8,7 +8,7 @@
8
8
  <link rel="alternate icon" href="/favicon.ico" />
9
9
  <link rel="apple-touch-icon" href="/favicon.svg" />
10
10
  <title>Super Pi</title>
11
- <script type="module" crossorigin src="/assets/index-BaYymkGX.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-CoLvWsuI.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-DV3qc1Hh.css">
14
14
  </head>
@@ -4,6 +4,6 @@ import type { ServiceProbe } from "../shared/managed-servers.js";
4
4
  export declare function serviceOrigin(value: string): string;
5
5
  export declare function defaultServiceOrigin(host: string, port: number): string;
6
6
  export declare function probeServiceEndpoint(origin: string, key?: string): Promise<ServiceProbe>;
7
- export declare function directJson(origin: string, path: string, key: string): Promise<Record<string, unknown>>;
7
+ export declare function directJson(origin: string, path: string, key: string, method?: string): Promise<Record<string, unknown>>;
8
8
  export declare function proxyThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath: string): void;
9
9
  export declare function proxyWebSocketThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): void;
@@ -36,8 +36,8 @@ export async function probeServiceEndpoint(origin, key = "") {
36
36
  return result({ reachable: false, service: false, authorized: false, message: "未能连接此服务端口。请检查 IP、端口、服务监听地址、防火墙或 TLS 配置;本次未尝试 SSH。" });
37
37
  }
38
38
  }
39
- export async function directJson(origin, path, key) {
40
- const response = await fetch(new URL(path, origin), { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(5000), redirect: "error" });
39
+ export async function directJson(origin, path, key, method = "GET") {
40
+ const response = await fetch(new URL(path, origin), { method, headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(5000), redirect: "error" });
41
41
  if (!response.ok || !response.headers.get("content-type")?.includes("application/json"))
42
42
  throw new Error(`Super Pi 服务直连检测失败(HTTP ${response.status})`);
43
43
  const value = await response.json();
@@ -43,7 +43,7 @@ export async function tunnelJson(client, port, path, key, method = "GET") {
43
43
  });
44
44
  const timeout = setTimeout(() => request.destroy(new Error("远端服务响应超时")), 12_000);
45
45
  request.once("close", () => clearTimeout(timeout));
46
- request.once("error", () => { agent.destroy(); reject(new Error("SSH 已连接,但远端 Super Pi 服务不可达")); });
46
+ request.once("error", () => { agent.destroy(); reject(new Error("SSH 隧道无法访问远端 Super Pi 端口")); });
47
47
  request.end();
48
48
  });
49
49
  }
@@ -14,6 +14,7 @@ export declare class ManagedServers {
14
14
  private readonly verifications;
15
15
  private readonly authBlocked;
16
16
  private readonly jobs;
17
+ private readonly tunneledRequests;
17
18
  private readonly recoveries;
18
19
  private readonly vault;
19
20
  private readonly gateway;
@@ -45,8 +46,11 @@ export declare class ManagedServers {
45
46
  deployedAt?: string;
46
47
  remoteRoot?: string;
47
48
  serviceUrl?: string;
49
+ allowServiceTunnel?: boolean;
48
50
  transport?: "direct" | "ssh";
49
51
  serviceError?: string;
52
+ sshError?: string;
53
+ modelError?: string;
50
54
  serviceHost?: import("../shared/managed-servers.js").ServiceListenHost;
51
55
  deployedServiceHost?: import("../shared/managed-servers.js").ServiceListenHost;
52
56
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
@@ -80,10 +84,13 @@ export declare class ManagedServers {
80
84
  connect(id: string): Promise<Client>;
81
85
  private openConnection;
82
86
  private reverseModelChannel;
83
- syncModels(id: string, force?: boolean): Promise<void>;
87
+ private restoreModelChannel;
88
+ private serviceJson;
89
+ syncModels(id: string, force?: boolean, reload?: boolean): Promise<void>;
84
90
  private health;
85
91
  private checkDirect;
86
92
  private detectExisting;
93
+ private discoverExisting;
87
94
  private startExisting;
88
95
  private ensureService;
89
96
  private progress;
@@ -112,6 +119,8 @@ export declare class ManagedServers {
112
119
  identity: string | undefined;
113
120
  revision: number;
114
121
  }[];
122
+ private trackServiceTunnel;
123
+ private closeServiceTunnel;
115
124
  proxy(id: string, path: string, request: IncomingMessage, response: ServerResponse): void;
116
125
  upgrade(id: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
117
126
  close(): Promise<void>;
@@ -25,6 +25,7 @@ export class ManagedServers {
25
25
  verifications = new Map();
26
26
  authBlocked = new Set();
27
27
  jobs = new Map();
28
+ tunneledRequests = new Map();
28
29
  recoveries = new Map();
29
30
  vault;
30
31
  gateway = new ManagedModelGateway();
@@ -49,7 +50,7 @@ export class ManagedServers {
49
50
  if (!/^[a-f0-9-]+$/.test(entry.profile?.id))
50
51
  continue;
51
52
  entry.profile.serviceUrl ??= defaultServiceOrigin(entry.profile.host, entry.profile.servicePort);
52
- entry.profile = { ...entry.profile, ssh: "offline", service: "unknown", modelChannel: "offline", phase: entry.profile.phase === "deploying" ? "failed" : "idle", error: entry.profile.phase === "deploying" ? "本地管理服务在部署期间重启,请检查后重试部署" : undefined };
53
+ entry.profile = { ...entry.profile, ssh: "offline", service: "unknown", modelChannel: "offline", transport: undefined, serviceError: undefined, sshError: undefined, modelError: undefined, phase: entry.profile.phase === "deploying" ? "failed" : "idle", error: entry.profile.phase === "deploying" ? "本地管理服务在部署期间重启,请检查后重试部署" : undefined };
53
54
  if (entry.profile.updateOperation && ["waiting", "installing", "restarting"].includes(entry.profile.updateOperation.phase)) {
54
55
  const operation = entry.profile.updateOperation;
55
56
  operation.failure = { step: operation.phase === "restarting" ? "restarting" : "installing", message: "本地管理服务在远端更新期间退出,请检测远端版本后重试。" };
@@ -174,9 +175,11 @@ export class ManagedServers {
174
175
  throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
175
176
  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 };
176
177
  profile.serviceUrl = input.serviceUrl?.trim() ? serviceOrigin(input.serviceUrl.trim()) : defaultServiceOrigin(profile.host, profile.servicePort);
177
- profile.serviceHost = input.serviceHost ?? previous?.profile.serviceHost ?? "127.0.0.1";
178
+ profile.serviceHost = input.serviceHost ?? previous?.profile.serviceHost ?? "0.0.0.0";
178
179
  profile.transport = undefined;
179
180
  profile.serviceError = undefined;
181
+ profile.sshError = undefined;
182
+ profile.modelError = undefined;
180
183
  this.clients.get(id)?.end();
181
184
  this.clients.delete(id);
182
185
  await this.vault.write(id, secret);
@@ -237,7 +240,7 @@ export class ManagedServers {
237
240
  profile.ssh = "connecting";
238
241
  if (profile.phase !== "deploying")
239
242
  profile.phase = "connecting";
240
- delete profile.error;
243
+ delete profile.sshError;
241
244
  let requestedVerification = false;
242
245
  try {
243
246
  const client = await connectSsh({ host: profile.host, port: profile.sshPort, username: profile.username, authentication: profile.authentication, identityFile: profile.identityFile, fingerprint: profile.fingerprint, ...secret.ssh }, {
@@ -258,20 +261,28 @@ export class ManagedServers {
258
261
  this.clients.set(id, client);
259
262
  profile.ssh = "online";
260
263
  client.once("close", () => { if (this.clients.get(id) !== client)
261
- return; this.clients.delete(id); profile.ssh = "offline"; if (profile.transport !== "direct")
262
- profile.service = "unknown"; profile.modelChannel = "offline"; if (profile.phase !== "deploying") {
263
- profile.phase = profile.service === "online" ? "ready" : "idle";
264
- profile.error = "SSH 连接中断,服务直连状态独立检测";
265
- } void this.checkDirect(id); void this.persist(); });
264
+ return; this.clients.delete(id); profile.ssh = "offline"; profile.sshError = "SSH 管理连接中断"; if (profile.transport !== "direct") {
265
+ profile.service = "unknown";
266
+ delete profile.transport;
267
+ } profile.modelChannel = "offline"; if (profile.phase !== "deploying")
268
+ profile.phase = profile.service === "online" ? "ready" : "idle"; void this.checkDirect(id); void this.persist(); });
266
269
  if (entry.installation) {
267
- await this.reverseModelChannel(entry, client);
268
- await this.syncModels(id);
269
- await this.ensureService(id);
270
+ try {
271
+ await this.ensureService(id);
272
+ }
273
+ catch (error) {
274
+ if (profile.service !== "online")
275
+ profile.serviceError = error instanceof Error ? error.message : "远端服务检测失败";
276
+ }
277
+ await this.restoreModelChannel(entry, client);
270
278
  }
271
279
  else {
272
- await this.detectExisting(id);
280
+ if (!(await this.checkDirect(id)))
281
+ await this.detectExisting(id);
273
282
  profile.phase = profile.existingService?.attached ? "ready" : "idle";
274
283
  }
284
+ if (profile.service === "online" && !this.jobs.has(id))
285
+ profile.phase = "ready";
275
286
  await this.persist();
276
287
  return client;
277
288
  }
@@ -284,10 +295,10 @@ export class ManagedServers {
284
295
  this.clients.delete(id);
285
296
  failed?.end();
286
297
  profile.ssh = cause instanceof HostTrustRequired ? "needsTrust" : "offline";
287
- profile.phase = cause instanceof HostTrustRequired ? "needsTrust" : "failed";
298
+ profile.phase = profile.service === "online" ? "ready" : cause instanceof HostTrustRequired ? "needsTrust" : "failed";
288
299
  if (cause instanceof HostTrustRequired)
289
300
  profile.observedFingerprint = cause.fingerprint;
290
- profile.error = cause instanceof Error ? cause.message : "SSH 连接失败";
301
+ profile.sshError = cause instanceof Error ? cause.message : "SSH 连接失败";
291
302
  await this.persist();
292
303
  throw cause;
293
304
  }
@@ -311,7 +322,28 @@ export class ManagedServers {
311
322
  });
312
323
  entry.profile.modelChannel = "online";
313
324
  }
314
- async syncModels(id, force = false) {
325
+ async restoreModelChannel(entry, client) {
326
+ try {
327
+ await this.reverseModelChannel(entry, client);
328
+ if (entry.profile.service === "online")
329
+ await this.syncModels(entry.profile.id);
330
+ }
331
+ catch (error) {
332
+ entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
333
+ }
334
+ }
335
+ serviceJson(entry, path, method = "GET") {
336
+ const profile = entry.profile, secret = this.secrets.get(profile.id);
337
+ if (!secret)
338
+ throw new Error("缺少服务访问配置");
339
+ if (profile.transport === "direct" && profile.serviceUrl)
340
+ return directJson(profile.serviceUrl, path, secret.browserKey, method);
341
+ const client = this.clients.get(profile.id);
342
+ if (!client || !profile.allowServiceTunnel || profile.transport !== "ssh")
343
+ throw new Error("没有可用的服务访问通道");
344
+ return tunnelJson(client, profile.servicePort, path, secret.browserKey, method);
345
+ }
346
+ async syncModels(id, force = false, reload = true) {
315
347
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
316
348
  if (!entry.installation || !entry.reversePort || !client || !secret)
317
349
  throw new Error("请先部署并连接此服务器");
@@ -324,15 +356,16 @@ export class ManagedServers {
324
356
  const defaultModel = this.defaultModel() ?? (models[0] ? { provider: models[0].provider, modelId: models[0].id } : undefined);
325
357
  if (defaultModel)
326
358
  await sshWrite(client, posix.join(entry.installation.root, "agent", "settings.json"), JSON.stringify({ defaultProvider: defaultModel.provider, defaultModel: defaultModel.modelId }));
359
+ if (reload)
360
+ await this.serviceJson(entry, "/api/managed-model/reload", "POST");
327
361
  entry.modelHash = hash;
328
- if (entry.profile.service === "online")
329
- await tunnelJson(client, entry.profile.servicePort, "/api/managed-model/reload", secret.browserKey, "POST");
362
+ delete entry.profile.modelError;
330
363
  }
331
364
  async health(id) {
332
365
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
333
366
  if (await this.checkDirect(id))
334
367
  return;
335
- if (!client || !secret)
368
+ if (!entry.profile.allowServiceTunnel || !client || !secret)
336
369
  return;
337
370
  if (entry.compatibility) {
338
371
  await this.detectExisting(id);
@@ -342,17 +375,22 @@ export class ManagedServers {
342
375
  const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
343
376
  if (info.id !== entry.profile.identity)
344
377
  throw new Error("端口上运行的不是此托管服务,请检查端口冲突");
378
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
379
+ return;
345
380
  entry.profile.service = "online";
346
381
  entry.profile.transport = "ssh";
382
+ delete entry.profile.serviceError;
347
383
  if (!this.jobs.has(id))
348
384
  entry.profile.phase = "ready";
349
- delete entry.profile.error;
350
385
  }
351
386
  catch (cause) {
387
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
388
+ return;
352
389
  entry.profile.service = "offline";
390
+ delete entry.profile.transport;
353
391
  if (!this.jobs.has(id))
354
392
  entry.profile.phase = "failed";
355
- entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
393
+ entry.profile.serviceError = cause instanceof Error ? cause.message : "远端服务不可达";
356
394
  }
357
395
  }
358
396
  async checkDirect(id) {
@@ -380,6 +418,10 @@ export class ManagedServers {
380
418
  if (newlyAttached)
381
419
  await this.persist();
382
420
  }
421
+ if (!profile.enabled || this.records.get(id) !== entry)
422
+ return false;
423
+ if (profile.transport === "ssh")
424
+ this.closeServiceTunnel(id);
383
425
  profile.transport = "direct";
384
426
  profile.service = "online";
385
427
  delete profile.serviceError;
@@ -388,11 +430,13 @@ export class ManagedServers {
388
430
  return true;
389
431
  }
390
432
  catch (error) {
391
- profile.serviceError = error instanceof Error ? error.message : "Super Pi 直连不可达";
392
- if (!this.clients.has(id)) {
393
- profile.service = "offline";
394
- profile.transport = undefined;
395
- }
433
+ if (!profile.enabled || this.records.get(id) !== entry)
434
+ return false;
435
+ if (profile.transport === "ssh" && profile.allowServiceTunnel && this.clients.has(id))
436
+ return false;
437
+ profile.serviceError = error instanceof Error && error.message !== "fetch failed" ? error.message : "直连服务端口不可达,请检查 IP、端口和服务监听地址。";
438
+ profile.service = "offline";
439
+ delete profile.transport;
396
440
  return false;
397
441
  }
398
442
  }
@@ -400,9 +444,17 @@ export class ManagedServers {
400
444
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
401
445
  if (!client || !secret)
402
446
  return;
447
+ const canUseTunnel = () => entry.profile.enabled && entry.profile.allowServiceTunnel && entry.profile.transport !== "direct" && this.clients.get(id) === client;
448
+ if (!entry.profile.allowServiceTunnel) {
449
+ await this.discoverExisting(entry, client, false);
450
+ await this.persist();
451
+ return;
452
+ }
403
453
  let found = false;
404
454
  try {
405
455
  const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.serviceAccessToken ?? "");
456
+ if (!canUseTunnel())
457
+ return;
406
458
  if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
407
459
  throw new Error("所选端口不是可识别的 Super Pi 服务");
408
460
  found = true;
@@ -410,6 +462,8 @@ export class ManagedServers {
410
462
  const access = await tunnelJson(client, entry.profile.servicePort, "/api/terminal-shell", secret.serviceAccessToken ?? "");
411
463
  if (!access || typeof access !== "object" || !("shell" in access))
412
464
  throw new Error("已有服务未提供兼容的管理接口");
465
+ if (!canUseTunnel())
466
+ return;
413
467
  entry.compatibility = true;
414
468
  entry.profile.identity ??= randomUUID();
415
469
  entry.profile.existingService.attached = true;
@@ -417,26 +471,30 @@ export class ManagedServers {
417
471
  entry.profile.transport = "ssh";
418
472
  entry.profile.modelChannel = "offline";
419
473
  entry.profile.phase = "ready";
420
- delete entry.profile.error;
474
+ delete entry.profile.serviceError;
421
475
  }
422
476
  catch (error) {
477
+ if (!canUseTunnel())
478
+ return;
423
479
  entry.profile.service = "offline";
480
+ delete entry.profile.transport;
424
481
  if (found) {
425
482
  entry.profile.existingService.requiresToken = /401|403/.test(error instanceof Error ? error.message : "");
426
- entry.profile.error = entry.profile.existingService.requiresToken ? "已有 Super Pi 服务要求访问密钥,请编辑连接填写原服务的访问密钥" : error instanceof Error ? error.message : "已有服务暂不可访问";
483
+ entry.profile.serviceError = entry.profile.existingService.requiresToken ? "已有 Super Pi 服务要求访问密钥,请编辑连接填写原服务的访问密钥" : error instanceof Error ? error.message : "已有服务暂不可访问";
427
484
  }
428
- else if (!entry.existingInstallation) {
429
- entry.existingInstallation = await discoverExistingInstallation(client);
430
- if (entry.existingInstallation)
431
- 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) };
432
- }
433
- else if (entry.profile.existingService) {
434
- entry.profile.existingService.running = false;
435
- entry.profile.existingService.attached = false;
485
+ else {
486
+ entry.profile.serviceError = error instanceof Error ? error.message : "SSH 隧道无法访问远端 Super Pi 端口";
487
+ await this.discoverExisting(entry, client, true);
436
488
  }
437
489
  }
438
490
  await this.persist();
439
491
  }
492
+ async discoverExisting(entry, client, allowStart) {
493
+ entry.existingInstallation ??= await discoverExistingInstallation(client);
494
+ const installation = entry.existingInstallation;
495
+ if (installation && entry.profile.transport !== "direct")
496
+ entry.profile.existingService = { running: false, attached: false, version: installation.version, dataDirectory: installation.dataDir, hasData: installation.hasData, canStart: allowStart && Boolean(installation.cli && installation.hasData) };
497
+ }
440
498
  startExisting(id) {
441
499
  const entry = this.entry(id);
442
500
  if (this.jobs.has(id))
@@ -452,7 +510,8 @@ export class ManagedServers {
452
510
  this.progress(entry, "启动已有 Super Pi,保留原数据和模型配置");
453
511
  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 });
454
512
  for (let attempt = 0; attempt < 20; attempt++) {
455
- await this.detectExisting(id);
513
+ if (!(await this.checkDirect(id)))
514
+ await this.detectExisting(id);
456
515
  if (entry.profile.existingService?.attached)
457
516
  return;
458
517
  await new Promise(resolve => setTimeout(resolve, 1000));
@@ -474,7 +533,7 @@ export class ManagedServers {
474
533
  async ensureService(id) {
475
534
  await this.health(id);
476
535
  const entry = this.entry(id), client = this.clients.get(id);
477
- if (!client || !entry.installation || entry.profile.service === "online" || entry.profile.error?.includes("不是此托管") || Date.now() - (this.recoveries.get(id) ?? 0) < 60_000)
536
+ if (!client || !entry.installation || entry.profile.service === "online" || entry.profile.serviceError?.includes("不是此托管") || Date.now() - (this.recoveries.get(id) ?? 0) < 60_000)
478
537
  return;
479
538
  this.recoveries.set(id, Date.now());
480
539
  const root = entry.installation.root, pid = posix.join(root, "service.pid");
@@ -507,6 +566,8 @@ export class ManagedServers {
507
566
  throw new Error("此服务器已有部署进行中");
508
567
  if (!entry.profile.fingerprint)
509
568
  throw new Error("请先测试 SSH 并确认主机指纹");
569
+ if (entry.profile.serviceHost === "127.0.0.1" && !entry.profile.allowServiceTunnel)
570
+ throw new Error("仅本机回环部署需要先启用 SSH 隧道访问,或选择可直连的监听方式。");
510
571
  if (updateVersion) {
511
572
  if (!entry.installation || entry.compatibility)
512
573
  throw new Error("此连接不是托管实例,应使用原服务的软件更新接口");
@@ -534,7 +595,7 @@ export class ManagedServers {
534
595
  this.progress(entry, updateVersion ? "下载并校验目标版本的纯服务安装包" : "生成与本地版本一致的纯服务安装包");
535
596
  const artifact = updateVersion ? await publishedServerUpdate(updateVersion, join(this.directory, "packages")) : await this.preparePackage();
536
597
  if (entry.profile.service === "online") {
537
- const state = await tunnelJson(client, entry.profile.servicePort, "/api/conversations", this.secrets.get(id).browserKey);
598
+ const state = await this.serviceJson(entry, "/api/conversations");
538
599
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
539
600
  throw new Error("远端仍有进行中的任务,请完成后再重新部署");
540
601
  }
@@ -547,7 +608,7 @@ export class ManagedServers {
547
608
  this.progress(entry, "建立模型通道并同步本地模型目录");
548
609
  await this.reverseModelChannel(entry, client);
549
610
  entry.modelHash = undefined;
550
- await this.syncModels(id);
611
+ await this.syncModels(id, false, false);
551
612
  this.progress(entry, "启动远端 Super Pi 服务");
552
613
  if (entry.profile.updateOperation && updateVersion) {
553
614
  entry.profile.updateOperation.phase = "restarting";
@@ -566,7 +627,7 @@ export class ManagedServers {
566
627
  if (entry.profile.serviceHost !== "127.0.0.1" && entry.profile.serviceHost !== undefined && !(await this.checkDirect(id)))
567
628
  throw new Error("远端服务已启动,但客户端直连地址仍不可达;请检查服务端口的网络策略。SSH 隧道可用不代表直连成功。");
568
629
  if (updateVersion) {
569
- const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.browserKey);
630
+ const health = await this.serviceJson(entry, "/api/health");
570
631
  if (health.runningVersion !== updateVersion)
571
632
  throw new Error("远端尚未运行目标版本,请查看远端 service.log");
572
633
  if (entry.profile.updateOperation) {
@@ -657,17 +718,42 @@ export class ManagedServers {
657
718
  entry.profile.phase = "idle";
658
719
  }
659
720
  }
721
+ else if (action === "enableServiceTunnel") {
722
+ entry.profile.allowServiceTunnel = true;
723
+ entry.profile.enabled = true;
724
+ if (!(await this.checkDirect(id))) {
725
+ if (this.clients.has(id))
726
+ await (entry.installation ? this.health(id) : this.detectExisting(id));
727
+ else
728
+ this.startConnection(id);
729
+ }
730
+ }
731
+ else if (action === "disableServiceTunnel") {
732
+ entry.profile.allowServiceTunnel = false;
733
+ this.closeServiceTunnel(id);
734
+ if (entry.profile.transport === "ssh") {
735
+ delete entry.profile.transport;
736
+ entry.profile.service = "unknown";
737
+ }
738
+ await this.checkDirect(id);
739
+ }
660
740
  else if (action === "connect" || action === "test") {
661
741
  entry.profile.enabled = true;
662
- if (!(await this.checkDirect(id)))
742
+ if (!(await this.checkDirect(id)) && entry.profile.allowServiceTunnel)
663
743
  this.startConnection(id);
664
744
  }
665
745
  else if (action === "connectSsh") {
666
746
  entry.profile.enabled = true;
667
747
  this.startConnection(id);
668
748
  }
669
- else if (action === "sync")
670
- await this.syncModels(id, true);
749
+ else if (action === "sync") {
750
+ try {
751
+ await this.syncModels(id, true);
752
+ }
753
+ catch (error) {
754
+ entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
755
+ }
756
+ }
671
757
  else if (action === "startExisting")
672
758
  return this.startExisting(id);
673
759
  else if (action === "deploy")
@@ -696,21 +782,24 @@ export class ManagedServers {
696
782
  const check = async (entry) => {
697
783
  if (!entry.profile.enabled || this.jobs.has(entry.profile.id))
698
784
  return;
785
+ const client = this.clients.get(entry.profile.id);
699
786
  if (await this.checkDirect(entry.profile.id)) {
700
- if (entry.installation && this.clients.has(entry.profile.id) && entry.profile.modelChannel === "online")
701
- await this.syncModels(entry.profile.id).catch(() => { });
787
+ if (entry.installation && client)
788
+ await this.restoreModelChannel(entry, client);
702
789
  return;
703
790
  }
704
791
  if (this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
705
792
  return;
706
793
  try {
707
- if (!this.clients.has(entry.profile.id))
708
- this.startConnection(entry.profile.id);
794
+ if (!client) {
795
+ if (entry.profile.allowServiceTunnel)
796
+ this.startConnection(entry.profile.id);
797
+ }
709
798
  else if (entry.installation) {
710
799
  await this.ensureService(entry.profile.id);
711
- await this.syncModels(entry.profile.id);
800
+ await this.restoreModelChannel(entry, client);
712
801
  }
713
- else if (entry.compatibility)
802
+ else if (entry.profile.allowServiceTunnel)
714
803
  await this.detectExisting(entry.profile.id);
715
804
  }
716
805
  catch { /* Each record carries its own actionable connection failure. */ }
@@ -724,11 +813,27 @@ export class ManagedServers {
724
813
  }
725
814
  }
726
815
  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 })); }
816
+ trackServiceTunnel(id, stream) {
817
+ const streams = this.tunneledRequests.get(id) ?? new Set();
818
+ this.tunneledRequests.set(id, streams);
819
+ streams.add(stream);
820
+ stream.once("close", () => {
821
+ streams.delete(stream);
822
+ if (!streams.size && this.tunneledRequests.get(id) === streams)
823
+ this.tunneledRequests.delete(id);
824
+ });
825
+ }
826
+ closeServiceTunnel(id) {
827
+ for (const stream of this.tunneledRequests.get(id) ?? [])
828
+ stream.destroy();
829
+ this.tunneledRequests.delete(id);
830
+ }
727
831
  proxy(id, path, request, response) {
728
832
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
729
833
  const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
730
- if (!entry.profile.enabled || (!client && !direct) || !secret) {
731
- response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "Super Pi 访问通道不可用,请检查服务直连地址或 SSH 隧道" }));
834
+ const tunnel = entry.profile.allowServiceTunnel && entry.profile.transport === "ssh" && client;
835
+ if (!entry.profile.enabled || (!tunnel && !direct) || !secret) {
836
+ response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "Super Pi 服务访问通道不可用,请检查直连地址。" }));
732
837
  return;
733
838
  }
734
839
  if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
@@ -738,21 +843,26 @@ export class ManagedServers {
738
843
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
739
844
  if (direct)
740
845
  proxyThroughDirect(direct, key, path, request, response, `/managed/${id}`);
741
- else
742
- proxyThroughSsh(client, entry.profile.servicePort, key, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
846
+ else if (tunnel) {
847
+ this.trackServiceTunnel(id, response);
848
+ proxyThroughSsh(tunnel, entry.profile.servicePort, key, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
849
+ }
743
850
  }
744
851
  async upgrade(id, path, request, socket, head) {
745
852
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
746
853
  const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
747
- if (!entry.profile.enabled || (!client && !direct) || !secret) {
854
+ const tunnel = entry.profile.allowServiceTunnel && entry.profile.transport === "ssh" && client;
855
+ if (!entry.profile.enabled || (!tunnel && !direct) || !secret) {
748
856
  socket.destroy();
749
857
  return;
750
858
  }
751
859
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
752
860
  if (direct)
753
861
  proxyWebSocketThroughDirect(direct, key, path, request, socket, head);
754
- else
755
- await proxyWebSocketThroughSsh(client, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
862
+ else if (tunnel) {
863
+ this.trackServiceTunnel(id, socket);
864
+ await proxyWebSocketThroughSsh(tunnel, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
865
+ }
756
866
  }
757
867
  async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
758
868
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
@@ -36,8 +36,11 @@ export interface ManagedServerProfile {
36
36
  deployedAt?: string;
37
37
  remoteRoot?: string;
38
38
  serviceUrl?: string;
39
+ allowServiceTunnel?: boolean;
39
40
  transport?: "direct" | "ssh";
40
41
  serviceError?: string;
42
+ sshError?: string;
43
+ modelError?: string;
41
44
  serviceHost?: ServiceListenHost;
42
45
  deployedServiceHost?: ServiceListenHost;
43
46
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "superPi": {
4
4
  "managedDirectListener": true
5
5
  },
6
- "version": "0.1.270",
6
+ "version": "0.1.271",
7
7
  "description": "Web control plane and companion for Pi",
8
8
  "license": "MIT",
9
9
  "type": "module",