@evandu/super-pi 0.1.269 → 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.
@@ -9,6 +9,7 @@ import { ManagedModelGateway } from "./managed-model-gateway.js";
9
9
  import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
10
10
  import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
11
11
  import { installRemote, startRemote } from "./remote-bootstrap.js";
12
+ import { isServiceListenHost } from "../shared/managed-servers.js";
12
13
  import { discoverExistingInstallation } from "./existing-service.js";
13
14
  import { publishedServerUpdate } from "./published-server-update.js";
14
15
  import { directJson, serviceOrigin, defaultServiceOrigin, probeServiceEndpoint, proxyThroughDirect, proxyWebSocketThroughDirect } from "./managed-http-direct.js";
@@ -24,6 +25,7 @@ export class ManagedServers {
24
25
  verifications = new Map();
25
26
  authBlocked = new Set();
26
27
  jobs = new Map();
28
+ tunneledRequests = new Map();
27
29
  recoveries = new Map();
28
30
  vault;
29
31
  gateway = new ManagedModelGateway();
@@ -48,7 +50,7 @@ export class ManagedServers {
48
50
  if (!/^[a-f0-9-]+$/.test(entry.profile?.id))
49
51
  continue;
50
52
  entry.profile.serviceUrl ??= defaultServiceOrigin(entry.profile.host, entry.profile.servicePort);
51
- 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 };
52
54
  if (entry.profile.updateOperation && ["waiting", "installing", "restarting"].includes(entry.profile.updateOperation.phase)) {
53
55
  const operation = entry.profile.updateOperation;
54
56
  operation.failure = { step: operation.phase === "restarting" ? "restarting" : "installing", message: "本地管理服务在远端更新期间退出,请检测远端版本后重试。" };
@@ -146,6 +148,8 @@ export class ManagedServers {
146
148
  throw new Error("请填写服务器名称、SSH 地址和用户名");
147
149
  if (![input.sshPort, input.servicePort].every(port => Number.isInteger(port) && port > 0 && port < 65536))
148
150
  throw new Error("SSH 和 Super Pi 端口必须在 1–65535 之间");
151
+ if (input.serviceHost !== undefined && !isServiceListenHost(input.serviceHost))
152
+ throw new Error("请选择有效的服务监听方式");
149
153
  if (!["agent", "password", "privateKey"].includes(input.authentication))
150
154
  throw new Error("请选择 SSH 认证方式");
151
155
  const id = input.id ?? randomUUID(), previous = input.id ? this.entry(input.id) : undefined;
@@ -171,8 +175,11 @@ export class ManagedServers {
171
175
  throw new Error("已接入服务器不能改为另一台主机或服务,请添加新连接以保护工作区归属");
172
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 };
173
177
  profile.serviceUrl = input.serviceUrl?.trim() ? serviceOrigin(input.serviceUrl.trim()) : defaultServiceOrigin(profile.host, profile.servicePort);
178
+ profile.serviceHost = input.serviceHost ?? previous?.profile.serviceHost ?? "0.0.0.0";
174
179
  profile.transport = undefined;
175
180
  profile.serviceError = undefined;
181
+ profile.sshError = undefined;
182
+ profile.modelError = undefined;
176
183
  this.clients.get(id)?.end();
177
184
  this.clients.delete(id);
178
185
  await this.vault.write(id, secret);
@@ -233,7 +240,7 @@ export class ManagedServers {
233
240
  profile.ssh = "connecting";
234
241
  if (profile.phase !== "deploying")
235
242
  profile.phase = "connecting";
236
- delete profile.error;
243
+ delete profile.sshError;
237
244
  let requestedVerification = false;
238
245
  try {
239
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 }, {
@@ -254,20 +261,28 @@ export class ManagedServers {
254
261
  this.clients.set(id, client);
255
262
  profile.ssh = "online";
256
263
  client.once("close", () => { if (this.clients.get(id) !== client)
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(); });
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(); });
262
269
  if (entry.installation) {
263
- await this.reverseModelChannel(entry, client);
264
- await this.syncModels(id);
265
- 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);
266
278
  }
267
279
  else {
268
- await this.detectExisting(id);
280
+ if (!(await this.checkDirect(id)))
281
+ await this.detectExisting(id);
269
282
  profile.phase = profile.existingService?.attached ? "ready" : "idle";
270
283
  }
284
+ if (profile.service === "online" && !this.jobs.has(id))
285
+ profile.phase = "ready";
271
286
  await this.persist();
272
287
  return client;
273
288
  }
@@ -280,10 +295,10 @@ export class ManagedServers {
280
295
  this.clients.delete(id);
281
296
  failed?.end();
282
297
  profile.ssh = cause instanceof HostTrustRequired ? "needsTrust" : "offline";
283
- profile.phase = cause instanceof HostTrustRequired ? "needsTrust" : "failed";
298
+ profile.phase = profile.service === "online" ? "ready" : cause instanceof HostTrustRequired ? "needsTrust" : "failed";
284
299
  if (cause instanceof HostTrustRequired)
285
300
  profile.observedFingerprint = cause.fingerprint;
286
- profile.error = cause instanceof Error ? cause.message : "SSH 连接失败";
301
+ profile.sshError = cause instanceof Error ? cause.message : "SSH 连接失败";
287
302
  await this.persist();
288
303
  throw cause;
289
304
  }
@@ -307,7 +322,28 @@ export class ManagedServers {
307
322
  });
308
323
  entry.profile.modelChannel = "online";
309
324
  }
310
- 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) {
311
347
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
312
348
  if (!entry.installation || !entry.reversePort || !client || !secret)
313
349
  throw new Error("请先部署并连接此服务器");
@@ -320,15 +356,16 @@ export class ManagedServers {
320
356
  const defaultModel = this.defaultModel() ?? (models[0] ? { provider: models[0].provider, modelId: models[0].id } : undefined);
321
357
  if (defaultModel)
322
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");
323
361
  entry.modelHash = hash;
324
- if (entry.profile.service === "online")
325
- await tunnelJson(client, entry.profile.servicePort, "/api/managed-model/reload", secret.browserKey, "POST");
362
+ delete entry.profile.modelError;
326
363
  }
327
364
  async health(id) {
328
365
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
329
366
  if (await this.checkDirect(id))
330
367
  return;
331
- if (!client || !secret)
368
+ if (!entry.profile.allowServiceTunnel || !client || !secret)
332
369
  return;
333
370
  if (entry.compatibility) {
334
371
  await this.detectExisting(id);
@@ -338,17 +375,22 @@ export class ManagedServers {
338
375
  const info = await tunnelJson(client, entry.profile.servicePort, "/api/browser-access", secret.browserKey);
339
376
  if (info.id !== entry.profile.identity)
340
377
  throw new Error("端口上运行的不是此托管服务,请检查端口冲突");
378
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
379
+ return;
341
380
  entry.profile.service = "online";
342
381
  entry.profile.transport = "ssh";
382
+ delete entry.profile.serviceError;
343
383
  if (!this.jobs.has(id))
344
384
  entry.profile.phase = "ready";
345
- delete entry.profile.error;
346
385
  }
347
386
  catch (cause) {
387
+ if (!entry.profile.enabled || !entry.profile.allowServiceTunnel || entry.profile.transport === "direct" || this.clients.get(id) !== client)
388
+ return;
348
389
  entry.profile.service = "offline";
390
+ delete entry.profile.transport;
349
391
  if (!this.jobs.has(id))
350
392
  entry.profile.phase = "failed";
351
- entry.profile.error = cause instanceof Error ? cause.message : "远端服务不可达";
393
+ entry.profile.serviceError = cause instanceof Error ? cause.message : "远端服务不可达";
352
394
  }
353
395
  }
354
396
  async checkDirect(id) {
@@ -376,6 +418,10 @@ export class ManagedServers {
376
418
  if (newlyAttached)
377
419
  await this.persist();
378
420
  }
421
+ if (!profile.enabled || this.records.get(id) !== entry)
422
+ return false;
423
+ if (profile.transport === "ssh")
424
+ this.closeServiceTunnel(id);
379
425
  profile.transport = "direct";
380
426
  profile.service = "online";
381
427
  delete profile.serviceError;
@@ -384,11 +430,13 @@ export class ManagedServers {
384
430
  return true;
385
431
  }
386
432
  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
- }
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;
392
440
  return false;
393
441
  }
394
442
  }
@@ -396,9 +444,17 @@ export class ManagedServers {
396
444
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
397
445
  if (!client || !secret)
398
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
+ }
399
453
  let found = false;
400
454
  try {
401
455
  const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.serviceAccessToken ?? "");
456
+ if (!canUseTunnel())
457
+ return;
402
458
  if (health.service !== "super-pi" || typeof health.runningVersion !== "string")
403
459
  throw new Error("所选端口不是可识别的 Super Pi 服务");
404
460
  found = true;
@@ -406,6 +462,8 @@ export class ManagedServers {
406
462
  const access = await tunnelJson(client, entry.profile.servicePort, "/api/terminal-shell", secret.serviceAccessToken ?? "");
407
463
  if (!access || typeof access !== "object" || !("shell" in access))
408
464
  throw new Error("已有服务未提供兼容的管理接口");
465
+ if (!canUseTunnel())
466
+ return;
409
467
  entry.compatibility = true;
410
468
  entry.profile.identity ??= randomUUID();
411
469
  entry.profile.existingService.attached = true;
@@ -413,26 +471,30 @@ export class ManagedServers {
413
471
  entry.profile.transport = "ssh";
414
472
  entry.profile.modelChannel = "offline";
415
473
  entry.profile.phase = "ready";
416
- delete entry.profile.error;
474
+ delete entry.profile.serviceError;
417
475
  }
418
476
  catch (error) {
477
+ if (!canUseTunnel())
478
+ return;
419
479
  entry.profile.service = "offline";
480
+ delete entry.profile.transport;
420
481
  if (found) {
421
482
  entry.profile.existingService.requiresToken = /401|403/.test(error instanceof Error ? error.message : "");
422
- 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 : "已有服务暂不可访问";
423
484
  }
424
- else if (!entry.existingInstallation) {
425
- entry.existingInstallation = await discoverExistingInstallation(client);
426
- if (entry.existingInstallation)
427
- 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) };
428
- }
429
- else if (entry.profile.existingService) {
430
- entry.profile.existingService.running = false;
431
- 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);
432
488
  }
433
489
  }
434
490
  await this.persist();
435
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
+ }
436
498
  startExisting(id) {
437
499
  const entry = this.entry(id);
438
500
  if (this.jobs.has(id))
@@ -448,7 +510,8 @@ export class ManagedServers {
448
510
  this.progress(entry, "启动已有 Super Pi,保留原数据和模型配置");
449
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 });
450
512
  for (let attempt = 0; attempt < 20; attempt++) {
451
- await this.detectExisting(id);
513
+ if (!(await this.checkDirect(id)))
514
+ await this.detectExisting(id);
452
515
  if (entry.profile.existingService?.attached)
453
516
  return;
454
517
  await new Promise(resolve => setTimeout(resolve, 1000));
@@ -470,7 +533,7 @@ export class ManagedServers {
470
533
  async ensureService(id) {
471
534
  await this.health(id);
472
535
  const entry = this.entry(id), client = this.clients.get(id);
473
- 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)
474
537
  return;
475
538
  this.recoveries.set(id, Date.now());
476
539
  const root = entry.installation.root, pid = posix.join(root, "service.pid");
@@ -478,7 +541,7 @@ export class ManagedServers {
478
541
  if (alive.trim())
479
542
  return;
480
543
  this.progress(entry, "远端服务已停止,正在恢复");
481
- await startRemote(client, entry.installation, entry.profile.servicePort);
544
+ await startRemote(client, entry.installation, entry.profile.servicePort, entry.profile.deployedServiceHost ?? "127.0.0.1");
482
545
  for (let attempt = 0; attempt < 15; attempt++) {
483
546
  await this.health(id);
484
547
  if (this.entry(id).profile.service === "online")
@@ -494,12 +557,17 @@ export class ManagedServers {
494
557
  }
495
558
  void this.persist();
496
559
  }
560
+ preparePackage() {
561
+ return 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; });
562
+ }
497
563
  deploy(id, updateVersion) {
498
564
  const entry = this.entry(id);
499
565
  if (this.jobs.has(id))
500
566
  throw new Error("此服务器已有部署进行中");
501
567
  if (!entry.profile.fingerprint)
502
568
  throw new Error("请先测试 SSH 并确认主机指纹");
569
+ if (entry.profile.serviceHost === "127.0.0.1" && !entry.profile.allowServiceTunnel)
570
+ throw new Error("仅本机回环部署需要先启用 SSH 隧道访问,或选择可直连的监听方式。");
503
571
  if (updateVersion) {
504
572
  if (!entry.installation || entry.compatibility)
505
573
  throw new Error("此连接不是托管实例,应使用原服务的软件更新接口");
@@ -525,11 +593,9 @@ export class ManagedServers {
525
593
  if (entry.existingInstallation)
526
594
  throw new Error("检测到原有 Super Pi 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
527
595
  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;
596
+ const artifact = updateVersion ? await publishedServerUpdate(updateVersion, join(this.directory, "packages")) : await this.preparePackage();
531
597
  if (entry.profile.service === "online") {
532
- const state = await tunnelJson(client, entry.profile.servicePort, "/api/conversations", this.secrets.get(id).browserKey);
598
+ const state = await this.serviceJson(entry, "/api/conversations");
533
599
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
534
600
  throw new Error("远端仍有进行中的任务,请完成后再重新部署");
535
601
  }
@@ -542,13 +608,14 @@ export class ManagedServers {
542
608
  this.progress(entry, "建立模型通道并同步本地模型目录");
543
609
  await this.reverseModelChannel(entry, client);
544
610
  entry.modelHash = undefined;
545
- await this.syncModels(id);
611
+ await this.syncModels(id, false, false);
546
612
  this.progress(entry, "启动远端 Super Pi 服务");
547
613
  if (entry.profile.updateOperation && updateVersion) {
548
614
  entry.profile.updateOperation.phase = "restarting";
549
615
  entry.profile.updateOperation.changedAt = new Date().toISOString();
550
616
  }
551
- await startRemote(client, installation, entry.profile.servicePort);
617
+ await startRemote(client, installation, entry.profile.servicePort, entry.profile.serviceHost);
618
+ entry.profile.deployedServiceHost = entry.profile.serviceHost ?? "127.0.0.1";
552
619
  for (let attempt = 0; attempt < 30; attempt++) {
553
620
  await this.health(id);
554
621
  if (this.entry(id).profile.service === "online")
@@ -557,8 +624,10 @@ export class ManagedServers {
557
624
  }
558
625
  if (entry.profile.service !== "online")
559
626
  throw new Error("远端服务未能启动,请查看部署记录及远端 service.log");
627
+ if (entry.profile.serviceHost !== "127.0.0.1" && entry.profile.serviceHost !== undefined && !(await this.checkDirect(id)))
628
+ throw new Error("远端服务已启动,但客户端直连地址仍不可达;请检查服务端口的网络策略。SSH 隧道可用不代表直连成功。");
560
629
  if (updateVersion) {
561
- const health = await tunnelJson(client, entry.profile.servicePort, "/api/health", secret.browserKey);
630
+ const health = await this.serviceJson(entry, "/api/health");
562
631
  if (health.runningVersion !== updateVersion)
563
632
  throw new Error("远端尚未运行目标版本,请查看远端 service.log");
564
633
  if (entry.profile.updateOperation) {
@@ -609,6 +678,21 @@ export class ManagedServers {
609
678
  return { started, errors };
610
679
  }
611
680
  async waitForUpdates(ids) { await Promise.allSettled(ids.map(id => this.jobs.get(id))); }
681
+ async applyListener(id, host) {
682
+ if (!isServiceListenHost(host))
683
+ throw new Error("请选择有效的服务监听方式");
684
+ const entry = this.entry(id);
685
+ if (!entry.installation || entry.compatibility)
686
+ throw new Error("此服务由原启动方式管理,不能覆盖它的启动配置。");
687
+ if (this.jobs.has(id))
688
+ throw new Error("此服务器已有部署进行中");
689
+ if (!entry.profile.enabled || !entry.profile.fingerprint)
690
+ throw new Error("请先启用此连接并确认 SSH 主机指纹");
691
+ entry.profile.serviceHost = host;
692
+ const deployment = this.deploy(id);
693
+ await this.persist();
694
+ return deployment;
695
+ }
612
696
  async action(id, action) {
613
697
  const entry = this.entry(id);
614
698
  if (action === "disconnect") {
@@ -634,17 +718,42 @@ export class ManagedServers {
634
718
  entry.profile.phase = "idle";
635
719
  }
636
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
+ }
637
740
  else if (action === "connect" || action === "test") {
638
741
  entry.profile.enabled = true;
639
- if (!(await this.checkDirect(id)))
742
+ if (!(await this.checkDirect(id)) && entry.profile.allowServiceTunnel)
640
743
  this.startConnection(id);
641
744
  }
642
745
  else if (action === "connectSsh") {
643
746
  entry.profile.enabled = true;
644
747
  this.startConnection(id);
645
748
  }
646
- else if (action === "sync")
647
- 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
+ }
648
757
  else if (action === "startExisting")
649
758
  return this.startExisting(id);
650
759
  else if (action === "deploy")
@@ -673,21 +782,24 @@ export class ManagedServers {
673
782
  const check = async (entry) => {
674
783
  if (!entry.profile.enabled || this.jobs.has(entry.profile.id))
675
784
  return;
785
+ const client = this.clients.get(entry.profile.id);
676
786
  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(() => { });
787
+ if (entry.installation && client)
788
+ await this.restoreModelChannel(entry, client);
679
789
  return;
680
790
  }
681
791
  if (this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
682
792
  return;
683
793
  try {
684
- if (!this.clients.has(entry.profile.id))
685
- this.startConnection(entry.profile.id);
794
+ if (!client) {
795
+ if (entry.profile.allowServiceTunnel)
796
+ this.startConnection(entry.profile.id);
797
+ }
686
798
  else if (entry.installation) {
687
799
  await this.ensureService(entry.profile.id);
688
- await this.syncModels(entry.profile.id);
800
+ await this.restoreModelChannel(entry, client);
689
801
  }
690
- else if (entry.compatibility)
802
+ else if (entry.profile.allowServiceTunnel)
691
803
  await this.detectExisting(entry.profile.id);
692
804
  }
693
805
  catch { /* Each record carries its own actionable connection failure. */ }
@@ -701,11 +813,27 @@ export class ManagedServers {
701
813
  }
702
814
  }
703
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
+ }
704
831
  proxy(id, path, request, response) {
705
832
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
706
833
  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 隧道" }));
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 服务访问通道不可用,请检查直连地址。" }));
709
837
  return;
710
838
  }
711
839
  if (entry.compatibility && path.split("?")[0] === "/api/browser-access") {
@@ -715,21 +843,26 @@ export class ManagedServers {
715
843
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
716
844
  if (direct)
717
845
  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));
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
+ }
720
850
  }
721
851
  async upgrade(id, path, request, socket, head) {
722
852
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
723
853
  const direct = entry.profile.transport === "direct" && entry.profile.serviceUrl;
724
- 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) {
725
856
  socket.destroy();
726
857
  return;
727
858
  }
728
859
  const key = entry.compatibility ? secret.serviceAccessToken ?? "" : secret.browserKey;
729
860
  if (direct)
730
861
  proxyWebSocketThroughDirect(direct, key, path, request, socket, head);
731
- else
732
- 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
+ }
733
866
  }
734
867
  async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
735
868
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
@@ -55,6 +55,7 @@ interface PiSdk {
55
55
  additionalSkillPaths?: string[];
56
56
  systemPrompt?: string;
57
57
  appendSystemPrompt?: string[];
58
+ appendSystemPromptOverride?: (prompts: string[]) => string[];
58
59
  extensionFactories?: unknown[];
59
60
  }) => {
60
61
  reload(): Promise<void>;
@@ -29,6 +29,7 @@ import { StringDecoder } from "node:string_decoder";
29
29
  import { dirname, join, resolve } from "node:path";
30
30
  import { createModelResolver } from "./model-context-window.js";
31
31
  import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
32
+ import { SOURCE_LINK_GUIDANCE } from "../shared/message-source-link.js";
32
33
  import { fileURLToPath, pathToFileURL } from "node:url";
33
34
  import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, readNativeToolSettings } from "./native-tool-settings.js";
34
35
  const traceSession = (conversationId, phase, startedAt, extra = "") => {
@@ -362,6 +363,7 @@ export async function createPiSession(creation) {
362
363
  const loader = new sdk.DefaultResourceLoader({
363
364
  cwd: creation.cwd,
364
365
  agentDir,
366
+ appendSystemPromptOverride: prompts => [...prompts, SOURCE_LINK_GUIDANCE],
365
367
  ...(creation.extensionPaths.length ? { additionalExtensionPaths: creation.extensionPaths } : {}),
366
368
  ...(creation.skillPaths?.length ? { additionalSkillPaths: creation.skillPaths } : {}),
367
369
  ...(creation.systemPromptFile && creation.systemPromptMode === "replace"
@@ -1,4 +1,5 @@
1
1
  import type { Client } from "ssh2";
2
+ import { type ServiceListenHost } from "../shared/managed-servers.js";
2
3
  export interface RemoteInstallation {
3
4
  root: string;
4
5
  packageRoot: string;
@@ -14,4 +15,5 @@ export declare function installRemote(options: {
14
15
  cacheDir: string;
15
16
  progress(step: string, output?: string): void;
16
17
  }): Promise<RemoteInstallation>;
17
- export declare function startRemote(client: Client, installation: RemoteInstallation, port: number): Promise<void>;
18
+ export declare function remoteStartScript(installation: RemoteInstallation, port: number, host?: ServiceListenHost): string;
19
+ export declare function startRemote(client: Client, installation: RemoteInstallation, port: number, host?: ServiceListenHost): Promise<void>;
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { mkdir, readFile, writeFile } from "node:fs/promises";
3
3
  import { join, basename, posix } from "node:path";
4
4
  import { sh, sshExec, sshSftp, sshWrite } from "./managed-ssh.js";
5
+ import { isServiceListenHost } from "../shared/managed-servers.js";
5
6
  export async function uploadFile(client, local, remote) {
6
7
  const sftp = await sshSftp(client);
7
8
  try {
@@ -87,13 +88,18 @@ export async function installRemote(options) {
87
88
  await sshWrite(client, piCommand, `#!/bin/sh\nexec ${sh(node)} ${sh(piCli)} --extension ${sh(extension)} "$@"\n`, 0o700);
88
89
  return { root, packageRoot, node, piCommand };
89
90
  }
90
- export async function startRemote(client, installation, port) {
91
+ export function remoteStartScript(installation, port, host = "127.0.0.1") {
92
+ if (!isServiceListenHost(host) || !Number.isInteger(port) || port < 1 || port > 65535)
93
+ throw new Error("服务监听地址或端口无效");
91
94
  const { root, packageRoot, node, piCommand } = installation;
92
95
  const pidFile = posix.join(root, "service.pid");
93
96
  const entry = posix.join(packageRoot, "dist", "server", "index.js");
94
97
  const script = `#!/bin/sh
95
98
  set -eu
96
99
  umask 077
100
+ ${host !== "127.0.0.1" ? `${sh(node)} -e ${sh(`const fs=require('node:fs');const pkg=JSON.parse(fs.readFileSync(${JSON.stringify(posix.join(packageRoot, "package.json"))},'utf8'));if(pkg.superPi?.managedDirectListener!==true)throw new Error('Installed version does not support authenticated direct listening');const a=JSON.parse(fs.readFileSync(${JSON.stringify(posix.join(root, "data", "browser-access.json"))},'utf8'));if(typeof a.key!=='string'||a.key.length<32)throw new Error('Direct listening requires configured owner access')`)}
101
+ unset SUPER_PI_ACCESS_TOKEN
102
+ export SUPER_PI_REQUIRE_BROWSER_ACCESS=1` : ""}
97
103
  if [ -f ${sh(pidFile)} ]; then
98
104
  pid=$(cat ${sh(pidFile)})
99
105
  case "$pid" in *[!0-9]*|"") ;; *)
@@ -107,12 +113,17 @@ export SUPER_PI_DATA_DIR=${sh(posix.join(root, "data"))}
107
113
  export PI_CODING_AGENT_DIR=${sh(posix.join(root, "agent"))}
108
114
  export SUPER_PI_MANAGED_CONFIG=${sh(posix.join(root, "models.json"))}
109
115
  export SUPER_PI_PI_COMMAND=${sh(piCommand)}
110
- export SUPER_PI_HOST=127.0.0.1
116
+ export SUPER_PI_HOST=${sh(host)}
111
117
  export SUPER_PI_PORT=${port}
112
118
  export PATH=${sh(posix.dirname(node))}:"$PATH"
113
119
  nohup ${sh(node)} ${sh(entry)} >>${sh(posix.join(root, "service.log"))} 2>&1 </dev/null &
114
120
  echo $! >${sh(pidFile)}
115
121
  `;
122
+ return script;
123
+ }
124
+ export async function startRemote(client, installation, port, host = "127.0.0.1") {
125
+ const script = remoteStartScript(installation, port, host);
126
+ const { root } = installation;
116
127
  const launcher = posix.join(root, "start-service.sh");
117
128
  await sshWrite(client, launcher, script, 0o700);
118
129
  await sshExec(client, `sh ${sh(launcher)}`, { timeout: 30_000 });
@@ -384,6 +384,10 @@ export class WsServer {
384
384
  setupUpgrade(httpServer) {
385
385
  httpServer.on("upgrade", (request, socket, head) => {
386
386
  const browserAuthorized = this.browserAccess?.authorize(request, true) ?? false;
387
+ if (process.env.SUPER_PI_REQUIRE_BROWSER_ACCESS === "1" && !isLoopbackAddress(request.socket.remoteAddress) && !browserAuthorized) {
388
+ socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
389
+ return;
390
+ }
387
391
  const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
388
392
  const managed = /^\/managed\/([a-f0-9-]+)(\/ws)$/.exec(url.pathname);
389
393
  if (managed) {