@evandu/super-pi 0.1.270 → 0.1.272

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-BsfNx6DV.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>
@@ -6,7 +6,7 @@ import { readAgents } from "../agents.js";
6
6
  import { verifyCapability } from "../capability.js";
7
7
  import { capText, validateWorkflowPlan, workflowSummary } from "../workflow.js";
8
8
  import { ensureNameIndex, recordWorkspacePath } from "../file-name-index.js";
9
- import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
9
+ import { formatTurnFailure, isLengthExceededError, recordedTurnFailure } from "../turn-failure.js";
10
10
  import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
11
11
  import { describeThrownWithStack } from "../failure-text.js";
12
12
  import { toWorkspaceRelative } from "../files.js";
@@ -2134,7 +2134,7 @@ export class RunService {
2134
2134
  // A turn that broke is the failure the reader will complain about, and the banner only carries
2135
2135
  // the sentence. The stack goes to the server log, where it can still be found.
2136
2136
  console.error("Super Pi turn failed:", describeThrownWithStack(error));
2137
- throw error;
2137
+ throw recordedTurnFailure(error);
2138
2138
  }
2139
2139
  finally {
2140
2140
  this.releaseRunSlot(conversation.id, controller);
@@ -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
  }
@@ -19,13 +19,21 @@ export async function managedProviderDefinitions(config) {
19
19
  const latest = await readManagedModelConfig() ?? config;
20
20
  const { signal, ...rest } = options ?? {};
21
21
  const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) => ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets"].includes(key) && typeof value !== "function"));
22
- const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json" }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions }) });
22
+ const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json" }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions }) }).catch(cause => {
23
+ if (signal?.aborted)
24
+ throw cause;
25
+ throw new Error("本地模型通道未连接。请在管理电脑的服务器连接中检查模型通道,必要时完成 SSH 验证后重试。", { cause });
26
+ });
23
27
  if (!response.ok || !response.body)
24
28
  throw new Error(`本地模型通道不可用(${response.status}),请检查管理电脑和 SSH 连接`);
25
29
  const reader = response.body.getReader(), decoder = new TextDecoder();
26
30
  let pending = "", settled = false;
27
31
  for (;;) {
28
- const { done, value } = await reader.read();
32
+ const { done, value } = await reader.read().catch(cause => {
33
+ if (signal?.aborted)
34
+ throw cause;
35
+ throw new Error("模型通道在回复完成前断开,请重连后重试", { cause });
36
+ });
29
37
  pending += decoder.decode(value, { stream: !done });
30
38
  let end;
31
39
  while ((end = pending.indexOf("\n")) >= 0) {
@@ -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,13 +46,17 @@ 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";
53
57
  service: "unknown" | "offline" | "online";
54
58
  modelChannel: "offline" | "online";
59
+ modelChannelPaused?: boolean;
55
60
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
56
61
  existingService?: {
57
62
  running: boolean;
@@ -80,10 +85,13 @@ export declare class ManagedServers {
80
85
  connect(id: string): Promise<Client>;
81
86
  private openConnection;
82
87
  private reverseModelChannel;
83
- syncModels(id: string, force?: boolean): Promise<void>;
88
+ private restoreModelChannel;
89
+ private serviceJson;
90
+ syncModels(id: string, force?: boolean, reload?: boolean): Promise<void>;
84
91
  private health;
85
92
  private checkDirect;
86
93
  private detectExisting;
94
+ private discoverExisting;
87
95
  private startExisting;
88
96
  private ensureService;
89
97
  private progress;
@@ -112,6 +120,8 @@ export declare class ManagedServers {
112
120
  identity: string | undefined;
113
121
  revision: number;
114
122
  }[];
123
+ private trackServiceTunnel;
124
+ private closeServiceTunnel;
115
125
  proxy(id: string, path: string, request: IncomingMessage, response: ServerResponse): void;
116
126
  upgrade(id: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
117
127
  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,25 +261,33 @@ 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
  }
278
289
  catch (cause) {
279
- if (requestedVerification || controller.signal.aborted)
290
+ if (requestedVerification || controller.signal.aborted || cause instanceof Error && cause.message.startsWith("SSH 认证失败"))
280
291
  this.authBlocked.add(id);
281
292
  this.verifications.get(id)?.reject(cause instanceof Error ? cause : new Error("SSH 验证已结束"));
282
293
  this.verifications.delete(id);
@@ -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,30 @@ 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
+ if (entry.profile.modelChannelPaused)
327
+ return;
328
+ try {
329
+ await this.reverseModelChannel(entry, client);
330
+ if (entry.profile.service === "online")
331
+ await this.syncModels(entry.profile.id);
332
+ }
333
+ catch (error) {
334
+ entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
335
+ }
336
+ }
337
+ serviceJson(entry, path, method = "GET") {
338
+ const profile = entry.profile, secret = this.secrets.get(profile.id);
339
+ if (!secret)
340
+ throw new Error("缺少服务访问配置");
341
+ if (profile.transport === "direct" && profile.serviceUrl)
342
+ return directJson(profile.serviceUrl, path, secret.browserKey, method);
343
+ const client = this.clients.get(profile.id);
344
+ if (!client || !profile.allowServiceTunnel || profile.transport !== "ssh")
345
+ throw new Error("没有可用的服务访问通道");
346
+ return tunnelJson(client, profile.servicePort, path, secret.browserKey, method);
347
+ }
348
+ async syncModels(id, force = false, reload = true) {
315
349
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
316
350
  if (!entry.installation || !entry.reversePort || !client || !secret)
317
351
  throw new Error("请先部署并连接此服务器");
@@ -324,15 +358,16 @@ export class ManagedServers {
324
358
  const defaultModel = this.defaultModel() ?? (models[0] ? { provider: models[0].provider, modelId: models[0].id } : undefined);
325
359
  if (defaultModel)
326
360
  await sshWrite(client, posix.join(entry.installation.root, "agent", "settings.json"), JSON.stringify({ defaultProvider: defaultModel.provider, defaultModel: defaultModel.modelId }));
361
+ if (reload)
362
+ await this.serviceJson(entry, "/api/managed-model/reload", "POST");
327
363
  entry.modelHash = hash;
328
- if (entry.profile.service === "online")
329
- await tunnelJson(client, entry.profile.servicePort, "/api/managed-model/reload", secret.browserKey, "POST");
364
+ delete entry.profile.modelError;
330
365
  }
331
366
  async health(id) {
332
367
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
333
368
  if (await this.checkDirect(id))
334
369
  return;
335
- if (!client || !secret)
370
+ if (!entry.profile.allowServiceTunnel || !client || !secret)
336
371
  return;
337
372
  if (entry.compatibility) {
338
373
  await this.detectExisting(id);
@@ -342,17 +377,22 @@ export class ManagedServers {
342
377
  const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
343
378
  if (info.id !== entry.profile.identity)
344
379
  throw new Error("端口上运行的不是此托管服务,请检查端口冲突");
380
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
381
+ return;
345
382
  entry.profile.service = "online";
346
383
  entry.profile.transport = "ssh";
384
+ delete entry.profile.serviceError;
347
385
  if (!this.jobs.has(id))
348
386
  entry.profile.phase = "ready";
349
- delete entry.profile.error;
350
387
  }
351
388
  catch (cause) {
389
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
390
+ return;
352
391
  entry.profile.service = "offline";
392
+ delete entry.profile.transport;
353
393
  if (!this.jobs.has(id))
354
394
  entry.profile.phase = "failed";
355
- entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
395
+ entry.profile.serviceError = cause instanceof Error ? cause.message : "远端服务不可达";
356
396
  }
357
397
  }
358
398
  async checkDirect(id) {
@@ -380,6 +420,10 @@ export class ManagedServers {
380
420
  if (newlyAttached)
381
421
  await this.persist();
382
422
  }
423
+ if (!profile.enabled || this.records.get(id) !== entry)
424
+ return false;
425
+ if (profile.transport === "ssh")
426
+ this.closeServiceTunnel(id);
383
427
  profile.transport = "direct";
384
428
  profile.service = "online";
385
429
  delete profile.serviceError;
@@ -388,11 +432,13 @@ export class ManagedServers {
388
432
  return true;
389
433
  }
390
434
  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
- }
435
+ if (!profile.enabled || this.records.get(id) !== entry)
436
+ return false;
437
+ if (profile.transport === "ssh" && profile.allowServiceTunnel && this.clients.has(id))
438
+ return false;
439
+ profile.serviceError = error instanceof Error && error.message !== "fetch failed" ? error.message : "直连服务端口不可达,请检查 IP、端口和服务监听地址。";
440
+ profile.service = "offline";
441
+ delete profile.transport;
396
442
  return false;
397
443
  }
398
444
  }
@@ -400,9 +446,17 @@ export class ManagedServers {
400
446
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
401
447
  if (!client || !secret)
402
448
  return;
449
+ const canUseTunnel = () => entry.profile.enabled && entry.profile.allowServiceTunnel && entry.profile.transport !== "direct" && this.clients.get(id) === client;
450
+ if (!entry.profile.allowServiceTunnel) {
451
+ await this.discoverExisting(entry, client, false);
452
+ await this.persist();
453
+ return;
454
+ }
403
455
  let found = false;
404
456
  try {
405
457
  const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.serviceAccessToken ?? "");
458
+ if (!canUseTunnel())
459
+ return;
406
460
  if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
407
461
  throw new Error("所选端口不是可识别的 Super Pi 服务");
408
462
  found = true;
@@ -410,6 +464,8 @@ export class ManagedServers {
410
464
  const access = await tunnelJson(client, entry.profile.servicePort, "/api/terminal-shell", secret.serviceAccessToken ?? "");
411
465
  if (!access || typeof access !== "object" || !("shell" in access))
412
466
  throw new Error("已有服务未提供兼容的管理接口");
467
+ if (!canUseTunnel())
468
+ return;
413
469
  entry.compatibility = true;
414
470
  entry.profile.identity ??= randomUUID();
415
471
  entry.profile.existingService.attached = true;
@@ -417,26 +473,30 @@ export class ManagedServers {
417
473
  entry.profile.transport = "ssh";
418
474
  entry.profile.modelChannel = "offline";
419
475
  entry.profile.phase = "ready";
420
- delete entry.profile.error;
476
+ delete entry.profile.serviceError;
421
477
  }
422
478
  catch (error) {
479
+ if (!canUseTunnel())
480
+ return;
423
481
  entry.profile.service = "offline";
482
+ delete entry.profile.transport;
424
483
  if (found) {
425
484
  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 : "已有服务暂不可访问";
427
- }
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) };
485
+ entry.profile.serviceError = entry.profile.existingService.requiresToken ? "已有 Super Pi 服务要求访问密钥,请编辑连接填写原服务的访问密钥" : error instanceof Error ? error.message : "已有服务暂不可访问";
432
486
  }
433
- else if (entry.profile.existingService) {
434
- entry.profile.existingService.running = false;
435
- entry.profile.existingService.attached = false;
487
+ else {
488
+ entry.profile.serviceError = error instanceof Error ? error.message : "SSH 隧道无法访问远端 Super Pi 端口";
489
+ await this.discoverExisting(entry, client, true);
436
490
  }
437
491
  }
438
492
  await this.persist();
439
493
  }
494
+ async discoverExisting(entry, client, allowStart) {
495
+ entry.existingInstallation ??= await discoverExistingInstallation(client);
496
+ const installation = entry.existingInstallation;
497
+ if (installation && entry.profile.transport !== "direct")
498
+ entry.profile.existingService = { running: false, attached: false, version: installation.version, dataDirectory: installation.dataDir, hasData: installation.hasData, canStart: allowStart && Boolean(installation.cli && installation.hasData) };
499
+ }
440
500
  startExisting(id) {
441
501
  const entry = this.entry(id);
442
502
  if (this.jobs.has(id))
@@ -452,7 +512,8 @@ export class ManagedServers {
452
512
  this.progress(entry, "启动已有 Super Pi,保留原数据和模型配置");
453
513
  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
514
  for (let attempt = 0; attempt < 20; attempt++) {
455
- await this.detectExisting(id);
515
+ if (!(await this.checkDirect(id)))
516
+ await this.detectExisting(id);
456
517
  if (entry.profile.existingService?.attached)
457
518
  return;
458
519
  await new Promise(resolve => setTimeout(resolve, 1000));
@@ -474,7 +535,7 @@ export class ManagedServers {
474
535
  async ensureService(id) {
475
536
  await this.health(id);
476
537
  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)
538
+ if (!client || !entry.installation || entry.profile.service === "online" || entry.profile.serviceError?.includes("不是此托管") || Date.now() - (this.recoveries.get(id) ?? 0) < 60_000)
478
539
  return;
479
540
  this.recoveries.set(id, Date.now());
480
541
  const root = entry.installation.root, pid = posix.join(root, "service.pid");
@@ -507,6 +568,8 @@ export class ManagedServers {
507
568
  throw new Error("此服务器已有部署进行中");
508
569
  if (!entry.profile.fingerprint)
509
570
  throw new Error("请先测试 SSH 并确认主机指纹");
571
+ if (entry.profile.serviceHost === "127.0.0.1" && !entry.profile.allowServiceTunnel)
572
+ throw new Error("仅本机回环部署需要先启用 SSH 隧道访问,或选择可直连的监听方式。");
510
573
  if (updateVersion) {
511
574
  if (!entry.installation || entry.compatibility)
512
575
  throw new Error("此连接不是托管实例,应使用原服务的软件更新接口");
@@ -534,7 +597,7 @@ export class ManagedServers {
534
597
  this.progress(entry, updateVersion ? "下载并校验目标版本的纯服务安装包" : "生成与本地版本一致的纯服务安装包");
535
598
  const artifact = updateVersion ? await publishedServerUpdate(updateVersion, join(this.directory, "packages")) : await this.preparePackage();
536
599
  if (entry.profile.service === "online") {
537
- const state = await tunnelJson(client, entry.profile.servicePort, "/api/conversations", this.secrets.get(id).browserKey);
600
+ const state = await this.serviceJson(entry, "/api/conversations");
538
601
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
539
602
  throw new Error("远端仍有进行中的任务,请完成后再重新部署");
540
603
  }
@@ -547,7 +610,7 @@ export class ManagedServers {
547
610
  this.progress(entry, "建立模型通道并同步本地模型目录");
548
611
  await this.reverseModelChannel(entry, client);
549
612
  entry.modelHash = undefined;
550
- await this.syncModels(id);
613
+ await this.syncModels(id, false, false);
551
614
  this.progress(entry, "启动远端 Super Pi 服务");
552
615
  if (entry.profile.updateOperation && updateVersion) {
553
616
  entry.profile.updateOperation.phase = "restarting";
@@ -566,7 +629,7 @@ export class ManagedServers {
566
629
  if (entry.profile.serviceHost !== "127.0.0.1" && entry.profile.serviceHost !== undefined && !(await this.checkDirect(id)))
567
630
  throw new Error("远端服务已启动,但客户端直连地址仍不可达;请检查服务端口的网络策略。SSH 隧道可用不代表直连成功。");
568
631
  if (updateVersion) {
569
- const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.browserKey);
632
+ const health = await this.serviceJson(entry, "/api/health");
570
633
  if (health.runningVersion !== updateVersion)
571
634
  throw new Error("远端尚未运行目标版本,请查看远端 service.log");
572
635
  if (entry.profile.updateOperation) {
@@ -646,6 +709,8 @@ export class ManagedServers {
646
709
  delete entry.profile.error;
647
710
  }
648
711
  else if (action === "disconnectSsh") {
712
+ if (entry.installation)
713
+ entry.profile.modelChannelPaused = true;
649
714
  this.authBlocked.add(id);
650
715
  await this.cancelConnection(id);
651
716
  this.clients.get(id)?.end();
@@ -657,17 +722,46 @@ export class ManagedServers {
657
722
  entry.profile.phase = "idle";
658
723
  }
659
724
  }
725
+ else if (action === "enableServiceTunnel") {
726
+ entry.profile.allowServiceTunnel = true;
727
+ entry.profile.enabled = true;
728
+ if (!(await this.checkDirect(id))) {
729
+ if (this.clients.has(id))
730
+ await (entry.installation ? this.health(id) : this.detectExisting(id));
731
+ else
732
+ this.startConnection(id);
733
+ }
734
+ }
735
+ else if (action === "disableServiceTunnel") {
736
+ entry.profile.allowServiceTunnel = false;
737
+ this.closeServiceTunnel(id);
738
+ if (entry.profile.transport === "ssh") {
739
+ delete entry.profile.transport;
740
+ entry.profile.service = "unknown";
741
+ }
742
+ await this.checkDirect(id);
743
+ }
660
744
  else if (action === "connect" || action === "test") {
661
745
  entry.profile.enabled = true;
662
- if (!(await this.checkDirect(id)))
746
+ if (!(await this.checkDirect(id)) && entry.profile.allowServiceTunnel)
663
747
  this.startConnection(id);
664
748
  }
665
749
  else if (action === "connectSsh") {
666
750
  entry.profile.enabled = true;
667
- this.startConnection(id);
751
+ delete entry.profile.modelChannelPaused;
752
+ if (entry.installation && this.clients.has(id))
753
+ await this.restoreModelChannel(entry, this.clients.get(id));
754
+ else
755
+ this.startConnection(id);
756
+ }
757
+ else if (action === "sync") {
758
+ try {
759
+ await this.syncModels(id, true);
760
+ }
761
+ catch (error) {
762
+ entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
763
+ }
668
764
  }
669
- else if (action === "sync")
670
- await this.syncModels(id, true);
671
765
  else if (action === "startExisting")
672
766
  return this.startExisting(id);
673
767
  else if (action === "deploy")
@@ -696,21 +790,28 @@ export class ManagedServers {
696
790
  const check = async (entry) => {
697
791
  if (!entry.profile.enabled || this.jobs.has(entry.profile.id))
698
792
  return;
793
+ const client = this.clients.get(entry.profile.id);
699
794
  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(() => { });
795
+ if (entry.installation && !entry.profile.modelChannelPaused) {
796
+ if (client)
797
+ await this.restoreModelChannel(entry, client);
798
+ else if (!this.connecting.has(entry.profile.id) && !this.authBlocked.has(entry.profile.id) && entry.profile.fingerprint && entry.profile.ssh !== "needsTrust")
799
+ this.startConnection(entry.profile.id);
800
+ }
702
801
  return;
703
802
  }
704
803
  if (this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
705
804
  return;
706
805
  try {
707
- if (!this.clients.has(entry.profile.id))
708
- this.startConnection(entry.profile.id);
806
+ if (!client) {
807
+ if (entry.profile.allowServiceTunnel)
808
+ this.startConnection(entry.profile.id);
809
+ }
709
810
  else if (entry.installation) {
710
811
  await this.ensureService(entry.profile.id);
711
- await this.syncModels(entry.profile.id);
812
+ await this.restoreModelChannel(entry, client);
712
813
  }
713
- else if (entry.compatibility)
814
+ else if (entry.profile.allowServiceTunnel)
714
815
  await this.detectExisting(entry.profile.id);
715
816
  }
716
817
  catch { /* Each record carries its own actionable connection failure. */ }
@@ -724,11 +825,27 @@ export class ManagedServers {
724
825
  }
725
826
  }
726
827
  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 })); }
828
+ trackServiceTunnel(id, stream) {
829
+ const streams = this.tunneledRequests.get(id) ?? new Set();
830
+ this.tunneledRequests.set(id, streams);
831
+ streams.add(stream);
832
+ stream.once("close", () => {
833
+ streams.delete(stream);
834
+ if (!streams.size && this.tunneledRequests.get(id) === streams)
835
+ this.tunneledRequests.delete(id);
836
+ });
837
+ }
838
+ closeServiceTunnel(id) {
839
+ for (const stream of this.tunneledRequests.get(id) ?? [])
840
+ stream.destroy();
841
+ this.tunneledRequests.delete(id);
842
+ }
727
843
  proxy(id, path, request, response) {
728
844
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
729
845
  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 隧道" }));
846
+ const tunnel = entry.profile.allowServiceTunnel && entry.profile.transport === "ssh" && client;
847
+ if (!entry.profile.enabled || (!tunnel && !direct) || !secret) {
848
+ response.writeHead(503, { "content-type": "application/json" }).end(JSON.stringify({ error: "Super Pi 服务访问通道不可用,请检查直连地址。" }));
732
849
  return;
733
850
  }
734
851
  if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
@@ -738,21 +855,26 @@ export class ManagedServers {
738
855
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
739
856
  if (direct)
740
857
  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));
858
+ else if (tunnel) {
859
+ this.trackServiceTunnel(id, response);
860
+ proxyThroughSsh(tunnel, entry.profile.servicePort, key, path, request, response, `/managed/${id}`, Boolean(entry.compatibility));
861
+ }
743
862
  }
744
863
  async upgrade(id, path, request, socket, head) {
745
864
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
746
865
  const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
747
- if (!entry.profile.enabled || (!client && !direct) || !secret) {
866
+ const tunnel = entry.profile.allowServiceTunnel && entry.profile.transport === "ssh" && client;
867
+ if (!entry.profile.enabled || (!tunnel && !direct) || !secret) {
748
868
  socket.destroy();
749
869
  return;
750
870
  }
751
871
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
752
872
  if (direct)
753
873
  proxyWebSocketThroughDirect(direct, key, path, request, socket, head);
754
- else
755
- await proxyWebSocketThroughSsh(client, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
874
+ else if (tunnel) {
875
+ this.trackServiceTunnel(id, socket);
876
+ await proxyWebSocketThroughSsh(tunnel, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
877
+ }
756
878
  }
757
879
  async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
758
880
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
@@ -1,3 +1,5 @@
1
+ export declare function recordedTurnFailure(error: unknown): Error;
2
+ export declare function isRecordedTurnFailure(error: unknown): boolean;
1
3
  /**
2
4
  * Translates a thrown error from the turn loop into a sentence a person reads.
3
5
  *