@evandu/super-pi 0.1.264 → 0.1.265

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +12 -0
  2. package/bin/completion.js +91 -0
  3. package/bin/super-pi.js +11 -1
  4. package/desktop/main.cjs +35 -3
  5. package/desktop/preload.cjs +1 -0
  6. package/desktop/update-lifecycle.cjs +8 -0
  7. package/dist/client/.super-pi-client-sources.json +11 -10
  8. package/dist/client/assets/{CodeMirrorEditor-D-PnT2mx.js → CodeMirrorEditor-B2cHfrUS.js} +2 -2
  9. package/dist/client/assets/GitDiffEditor-Bl7XQIDD.js +29 -0
  10. package/dist/client/assets/dist-3qQVP6l8.js +6 -0
  11. package/dist/client/assets/{dist-BXAOrsjq.js → dist-BlRuQIg1.js} +1 -1
  12. package/dist/client/assets/{dist-BRVQKlcp.js → dist-BvjUKkwy.js} +1 -1
  13. package/dist/client/assets/{dist-QzbOCAU6.js → dist-CQncCwUc.js} +1 -1
  14. package/dist/client/assets/dist-CZ4PyxQu.js +9 -0
  15. package/dist/client/assets/dist-CfTFp0AF.js +2 -0
  16. package/dist/client/assets/dist-CxmJXjJI.js +1 -0
  17. package/dist/client/assets/{dist-Dvb0SqcK.js → dist-D5u1uPmZ.js} +2 -2
  18. package/dist/client/assets/dist-D8HpMxmZ.js +1 -0
  19. package/dist/client/assets/{dist-AW5lyI3I.js → dist-DGBjhKI9.js} +1 -1
  20. package/dist/client/assets/dist-DRBIy9A1.js +1 -0
  21. package/dist/client/assets/dist-Dcww9FSw.js +1 -0
  22. package/dist/client/assets/{dist-moiMRpw_.js → dist-DjI7p99D.js} +1 -1
  23. package/dist/client/assets/dist-DlPa5gNa.js +7 -0
  24. package/dist/client/assets/dist-DxPJ1PN-.js +1 -0
  25. package/dist/client/assets/dist-HXD8sSA4.js +23 -0
  26. package/dist/client/assets/dist-LbeLCeoq.js +1 -0
  27. package/dist/client/assets/dist-ONdtnupI.js +1 -0
  28. package/dist/client/assets/dist-YqmXusLA.js +11 -0
  29. package/dist/client/assets/dist-ZAR1Tu2c.js +3 -0
  30. package/dist/client/assets/{dist-Cus6_oaF.js → dist-i79xiXVk.js} +2 -2
  31. package/dist/client/assets/index-Cl8iehsn.css +1 -0
  32. package/dist/client/assets/index-DW2nd-Cf.js +350 -0
  33. package/dist/client/index.html +2 -2
  34. package/dist/server/application/provider-service.d.ts +1 -0
  35. package/dist/server/application/provider-service.js +12 -2
  36. package/dist/server/http-server.js +105 -41
  37. package/dist/server/managed-http-direct.d.ts +9 -0
  38. package/dist/server/managed-http-direct.js +100 -0
  39. package/dist/server/managed-http.js +14 -0
  40. package/dist/server/managed-servers.d.ts +17 -1
  41. package/dist/server/managed-servers.js +196 -30
  42. package/dist/server/pi-session.js +1 -1
  43. package/dist/server/published-server-update.d.ts +6 -0
  44. package/dist/server/published-server-update.js +54 -0
  45. package/dist/server/read-receipts.d.ts +10 -0
  46. package/dist/server/read-receipts.js +55 -0
  47. package/dist/server/update-status.d.ts +3 -1
  48. package/dist/server/update-status.js +5 -3
  49. package/dist/shared/directory-completion.d.ts +5 -0
  50. package/dist/shared/directory-completion.js +10 -0
  51. package/dist/shared/managed-servers.d.ts +15 -0
  52. package/dist/shared/managed-servers.js +3 -1
  53. package/dist/shared/read-receipts.d.ts +7 -0
  54. package/dist/shared/read-receipts.js +3 -0
  55. package/dist/shared/update-status.d.ts +1 -1
  56. package/dist/shared/update-status.js +1 -1
  57. package/package.json +14 -1
  58. package/scripts/restart-process.mjs +11 -0
  59. package/scripts/restart-server.mjs +2 -2
  60. package/dist/client/assets/GitDiffEditor-Bb81nrRq.js +0 -29
  61. package/dist/client/assets/dist-B3-a6uF0.js +0 -7
  62. package/dist/client/assets/dist-BGxkyh6e.js +0 -1
  63. package/dist/client/assets/dist-BJxfd7yb.js +0 -11
  64. package/dist/client/assets/dist-BV64A9Ji.js +0 -1
  65. package/dist/client/assets/dist-CKF2Jksy.js +0 -1
  66. package/dist/client/assets/dist-CX_Hm4GS.js +0 -1
  67. package/dist/client/assets/dist-Cx00EZKR.js +0 -23
  68. package/dist/client/assets/dist-D71y2EI1.js +0 -1
  69. package/dist/client/assets/dist-Dc1MBGAG.js +0 -1
  70. package/dist/client/assets/dist-Dds-qLxY.js +0 -9
  71. package/dist/client/assets/dist-DeD9copn.js +0 -1
  72. package/dist/client/assets/dist-DuvGReu-.js +0 -6
  73. package/dist/client/assets/dist-J6XWqRpB.js +0 -3
  74. package/dist/client/assets/dist-scBkrwv-.js +0 -2
  75. package/dist/client/assets/index-BeRJ1cQe.js +0 -350
  76. package/dist/client/assets/index-D6ei0DbU.css +0 -1
@@ -8,9 +8,9 @@
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-BeRJ1cQe.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-DW2nd-Cf.js"></script>
12
12
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
13
- <link rel="stylesheet" crossorigin href="/assets/index-D6ei0DbU.css">
13
+ <link rel="stylesheet" crossorigin href="/assets/index-Cl8iehsn.css">
14
14
  </head>
15
15
  <body>
16
16
  <div id="root"></div>
@@ -62,6 +62,7 @@ export declare class ProviderService {
62
62
  }[];
63
63
  };
64
64
  error?: string;
65
+ warning?: string;
65
66
  }[];
66
67
  startOAuthLogin(providerId: unknown): Promise<string>;
67
68
  answerOAuthPrompt(id: unknown, answer: unknown): void;
@@ -158,11 +158,21 @@ export class ProviderService {
158
158
  });
159
159
  job.state = "completed";
160
160
  job.event = undefined;
161
- await this.afterChange();
161
+ try {
162
+ await this.afterChange();
163
+ }
164
+ catch {
165
+ job.warning = "登录凭据已保存,但模型清单刷新失败,请刷新模型列表后重试,无需重新登录。";
166
+ }
162
167
  }
163
168
  catch (error) {
164
169
  job.state = job.abort.signal.aborted ? "cancelled" : "failed";
165
- job.error = job.abort.signal.aborted ? "登录已取消。" : "Pi OAuth 登录失败,请重试并检查授权页面。";
170
+ const reason = error instanceof Error ? error.message : "";
171
+ // Select fixed descriptions instead of exposing SDK messages containing callback secrets.
172
+ job.error = job.abort.signal.aborted ? "登录已取消。"
173
+ : /fetch|network|ECONN|ENOTFOUND|timeout|timed out/i.test(reason) ? "授权凭据交换未完成:服务端网络连接失败或超时。请检查该供应商的代理设置后重试;网页授权成功不代表凭据已保存。"
174
+ : /EACCES|EPERM|EROFS|ENOSPC/i.test(reason) ? "授权凭据无法保存,请检查服务端凭据目录的写入权限和磁盘空间。"
175
+ : "Pi OAuth 凭据交换或保存失败,请重试;授权网页的成功提示仅表示已收到回调。";
166
176
  job.prompt = undefined;
167
177
  job.event = undefined;
168
178
  }
@@ -1,4 +1,5 @@
1
1
  import { handleManagedHttp } from "./managed-http.js";
2
+ import { ReadReceipts } from "./read-receipts.js";
2
3
  import { createReadStream, existsSync } from "node:fs";
3
4
  import { matchPathMentions } from "../shared/file-mentions.js";
4
5
  import { spawn } from "node:child_process";
@@ -366,6 +367,18 @@ export function createHttpServer(options) {
366
367
  const explicitFileOpen = createExplicitFileOpen();
367
368
  const browserAccess = context.browserAccess ??= new BrowserAccess(join(paths.dataDir, "browser-access.json"));
368
369
  const nativeTools = new NativeToolsService(paths.dataDir, () => context.runtime?.reloadNativeTools?.());
370
+ const readBaseline = [];
371
+ const initialReadState = store.clientState({});
372
+ for (const conversation of initialReadState.conversations) {
373
+ if (!["running", "waiting", "awaiting_background"].includes(conversation.status))
374
+ readBaseline.push({ workspaceId: conversation.workspaceId, conversationId: conversation.id, at: conversation.updatedAt });
375
+ }
376
+ for (const workspace of initialReadState.workspaces)
377
+ for (const room of context.groupChatService?.list(workspace.id) ?? []) {
378
+ if (room.activity.lastReplyAt && !["running", "awaiting_background"].includes(room.activity.status))
379
+ readBaseline.push({ workspaceId: workspace.id, roomId: room.id, at: room.activity.lastReplyAt });
380
+ }
381
+ const readReceipts = new ReadReceipts(join(paths.dataDir, "read-receipts.json"), readBaseline);
369
382
  let tracker;
370
383
  const getUpdateTracker = () => tracker ??= new UpdateTracker(join(paths.dataDir ?? rootDir, "update-status.json"), rootDir);
371
384
  const updateStatus = () => {
@@ -428,6 +441,41 @@ export function createHttpServer(options) {
428
441
  const json = (status, body) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }); response.end(JSON.stringify(body)); };
429
442
  if (await handleManagedHttp(context, request, response, url))
430
443
  return;
444
+ if (url.pathname === "/api/read-receipts") {
445
+ if (request.method === "GET") {
446
+ json(200, { receipts: readReceipts.list() });
447
+ return;
448
+ }
449
+ if (request.method !== "POST") {
450
+ json(405, { error: "仅支持 GET / POST" });
451
+ return;
452
+ }
453
+ let body = "";
454
+ for await (const part of request) {
455
+ body += part;
456
+ if (body.length > 256_000) {
457
+ json(413, { error: "已读同步请求过大" });
458
+ return;
459
+ }
460
+ }
461
+ try {
462
+ const receipts = readReceipts.merge(JSON.parse(body).receipts, value => {
463
+ const workspace = store.workspace(value.workspaceId);
464
+ if (!workspace || workspace.closedAt)
465
+ return undefined;
466
+ if (value.conversationId) {
467
+ const conversation = store.conversation(value.conversationId);
468
+ return conversation?.workspaceId === value.workspaceId ? conversation.updatedAt : undefined;
469
+ }
470
+ return context.groupChatService?.list(value.workspaceId).find(room => room.id === value.roomId)?.activity.lastReplyAt;
471
+ });
472
+ json(200, { receipts });
473
+ }
474
+ catch (error) {
475
+ json(400, { error: error instanceof Error ? error.message : "已读同步失败" });
476
+ }
477
+ return;
478
+ }
431
479
  if (url.pathname === "/api/browser-access") {
432
480
  if (request.method === "GET") {
433
481
  json(200, { ...browserAccess.status(), ...(isBrowserAuthorized(request) ? { assetLease: browserAccess.lease(String(request.headers.origin ?? url.origin)) } : {}) });
@@ -1527,7 +1575,7 @@ export function createHttpServer(options) {
1527
1575
  }
1528
1576
  let body = {};
1529
1577
  try {
1530
- const input = await readRequestText(request, 4096);
1578
+ const input = await readRequestText(request, 32_768);
1531
1579
  if (input.tooLarge) {
1532
1580
  json(413, { error: "更新请求过大。" });
1533
1581
  return;
@@ -1540,6 +1588,11 @@ export function createHttpServer(options) {
1540
1588
  }
1541
1589
  const wantedVersion = typeof body?.version === "string" && body.version ? body.version : undefined;
1542
1590
  const restartOnly = body?.restartOnly === true;
1591
+ const managedUpdates = body.managedUpdates ?? [];
1592
+ if (!Array.isArray(managedUpdates) || managedUpdates.length > 64 || managedUpdates.some(item => typeof item?.id !== "string" || typeof item.version !== "string") || new Set(managedUpdates.map(item => item.id)).size !== managedUpdates.length || (managedUpdates.length && !context.managedServers)) {
1593
+ json(400, { error: "托管更新目标无效" });
1594
+ return;
1595
+ }
1543
1596
  if (wantedVersion && (wantedVersion.length > 128 || !/^\d+\.\d+\.\d+(?:-[a-z0-9.-]+)?(?:\+[a-z0-9.-]+)?$/iu.test(wantedVersion))) {
1544
1597
  json(400, { error: "目标版本格式无效。" });
1545
1598
  return;
@@ -1553,7 +1606,7 @@ export function createHttpServer(options) {
1553
1606
  const updateTracker = getUpdateTracker();
1554
1607
  let id;
1555
1608
  try {
1556
- id = updateTracker.begin(restartOnly ? "restart" : "update", restartOnly ? checkDiskVersion(rootDir).diskVersion : wantedVersion);
1609
+ id = updateTracker.begin(restartOnly ? "restart" : "update", restartOnly ? checkDiskVersion(rootDir).diskVersion : wantedVersion, managedUpdates.length > 0);
1557
1610
  }
1558
1611
  catch (error) {
1559
1612
  releaseUpdateSlot();
@@ -1561,7 +1614,8 @@ export function createHttpServer(options) {
1561
1614
  json(500, { error: "无法保存更新记录,请检查服务数据目录。" });
1562
1615
  return;
1563
1616
  }
1564
- json(202, { ...updateStatus(), status: "updating" });
1617
+ const managedResult = managedUpdates.length ? context.managedServers.updateSelected(managedUpdates) : undefined;
1618
+ json(202, { ...updateStatus(), status: "updating", managedResult });
1565
1619
  let failed = false;
1566
1620
  const fail = (step, message, code) => {
1567
1621
  if (failed)
@@ -1594,44 +1648,52 @@ export function createHttpServer(options) {
1594
1648
  fail("restarting", "无法启动重启程序,请查看服务日志后重试。");
1595
1649
  }
1596
1650
  };
1597
- if (restartOnly) {
1598
- restartNow();
1599
- return;
1600
- }
1601
- const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1602
- const update = packageUpdateArgs(rootDir, wantedVersion);
1603
- try {
1604
- const child = spawn(npmCmd, shellArgs(update.args), { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32", env: process.env });
1605
- let stderr = "";
1606
- child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-4096); });
1607
- child.once("error", () => fail("installing", "无法启动 npm 安装程序,请检查服务日志。"));
1608
- child.once("close", (code) => {
1609
- if (failed)
1610
- return;
1611
- if (code !== 0) {
1612
- const npmCode = /\bnpm\s+(?:ERR!|error)\s+code\s+([A-Z][A-Z0-9_]{1,30})\b/u.exec(stderr)?.[1];
1613
- const detail = [npmCode, code === null ? "进程已中断" : `退出码 ${code}`].filter(Boolean).join(",");
1614
- fail("installing", `安装更新失败(${detail})。`, code ?? undefined);
1615
- return;
1616
- }
1617
- const installed = readPackageVersion(rootDir);
1618
- if (!installed || (wantedVersion && installed !== wantedVersion)) {
1619
- fail("installing", "npm 已退出,但当前服务的安装目录缺少目标版本。请核对安装位置。");
1620
- return;
1621
- }
1622
- try {
1623
- updateTracker.restarting(id, installed);
1624
- }
1625
- catch {
1626
- fail("installing", "版本已安装,但无法保存重启状态。请手动重启服务。");
1627
- return;
1628
- }
1651
+ const performUpdate = () => {
1652
+ if (restartOnly) {
1653
+ updateTracker.readyToRestart(id);
1629
1654
  restartNow();
1630
- });
1631
- }
1632
- catch {
1633
- fail("installing", "无法启动 npm 安装程序,请检查服务日志。");
1634
- }
1655
+ return;
1656
+ }
1657
+ updateTracker.installing(id);
1658
+ const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1659
+ const update = packageUpdateArgs(rootDir, wantedVersion);
1660
+ try {
1661
+ const child = spawn(npmCmd, shellArgs(update.args), { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32", env: process.env });
1662
+ let stderr = "";
1663
+ child.stderr?.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-4096); });
1664
+ child.once("error", () => fail("installing", "无法启动 npm 安装程序,请检查服务日志。"));
1665
+ child.once("close", (code) => {
1666
+ if (failed)
1667
+ return;
1668
+ if (code !== 0) {
1669
+ const npmCode = /\bnpm\s+(?:ERR!|error)\s+code\s+([A-Z][A-Z0-9_]{1,30})\b/u.exec(stderr)?.[1];
1670
+ const detail = [npmCode, code === null ? "进程已中断" : `退出码 ${code}`].filter(Boolean).join(",");
1671
+ fail("installing", `安装更新失败(${detail})。`, code ?? undefined);
1672
+ return;
1673
+ }
1674
+ const installed = readPackageVersion(rootDir);
1675
+ if (!installed || (wantedVersion && installed !== wantedVersion)) {
1676
+ fail("installing", "npm 已退出,但当前服务的安装目录缺少目标版本。请核对安装位置。");
1677
+ return;
1678
+ }
1679
+ try {
1680
+ updateTracker.restarting(id, installed);
1681
+ }
1682
+ catch {
1683
+ fail("installing", "版本已安装,但无法保存重启状态。请手动重启服务。");
1684
+ return;
1685
+ }
1686
+ restartNow();
1687
+ });
1688
+ }
1689
+ catch {
1690
+ fail("installing", "无法启动 npm 安装程序,请检查服务日志。");
1691
+ }
1692
+ };
1693
+ if (managedResult)
1694
+ void context.managedServers.waitForUpdates(managedResult.started).then(performUpdate).catch(() => fail("installing", "等待远端更新时连接中断,请检查远端状态后重试本地更新。"));
1695
+ else
1696
+ performUpdate();
1635
1697
  return;
1636
1698
  }
1637
1699
  if ((url.pathname === "/api/update-status" || url.pathname === "/api/update-check") && request.method === "GET") {
@@ -3643,10 +3705,12 @@ export function createHttpServer(options) {
3643
3705
  return;
3644
3706
  }
3645
3707
  const dirents = await readdir(target, { withFileTypes: true });
3708
+ const prefix = (url.searchParams.get("prefix") ?? "").toLocaleLowerCase();
3646
3709
  const entries = dirents
3647
3710
  .filter((item) => item.isDirectory())
3711
+ .filter((item) => item.name.toLocaleLowerCase().includes(prefix))
3648
3712
  .map((item) => ({ name: item.name, path: join(target, item.name) }))
3649
- .sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
3713
+ .sort((a, b) => Number(b.name.toLocaleLowerCase().startsWith(prefix)) - Number(a.name.toLocaleLowerCase().startsWith(prefix)) || a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }));
3650
3714
  const truncated = entries.length > 2000;
3651
3715
  const parent = dirname(target);
3652
3716
  const getAvailableDrives = () => {
@@ -0,0 +1,9 @@
1
+ import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import type { Duplex } from "node:stream";
3
+ import type { ServiceProbe } from "../shared/managed-servers.js";
4
+ export declare function serviceOrigin(value: string): string;
5
+ export declare function defaultServiceOrigin(host: string, port: number): string;
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>>;
8
+ export declare function proxyThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath: string): void;
9
+ export declare function proxyWebSocketThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): void;
@@ -0,0 +1,100 @@
1
+ import { request as httpRequest } from "node:http";
2
+ import { request as httpsRequest } from "node:https";
3
+ import { defaultServiceUrl } from "../shared/managed-servers.js";
4
+ export function serviceOrigin(value) {
5
+ const url = new URL(value);
6
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || url.pathname !== "/")
7
+ throw new Error("服务地址必须是 http(s)://主机:端口,不包含路径或凭据");
8
+ return url.origin;
9
+ }
10
+ export function defaultServiceOrigin(host, port) {
11
+ return serviceOrigin(defaultServiceUrl(host, port));
12
+ }
13
+ export async function probeServiceEndpoint(origin, key = "") {
14
+ const address = serviceOrigin(origin), started = performance.now();
15
+ const result = (value) => ({ ...value, address, latencyMs: Math.round(performance.now() - started) });
16
+ try {
17
+ const response = await fetch(new URL("/api/health", address), { headers: key ? { authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(5000), redirect: "manual" });
18
+ if ([401, 403].includes(response.status)) {
19
+ await response.body?.cancel();
20
+ return result({ reachable: true, service: false, authorized: false, status: response.status, message: "端口可达,但访问被拒绝。请确认这是 Super Pi 服务并填写正确的访问密钥。" });
21
+ }
22
+ let health;
23
+ try {
24
+ health = await response.json();
25
+ }
26
+ catch { /* Report an HTTP endpoint that is not Super Pi. */ }
27
+ if (!response.ok || !health || typeof health !== "object" || health.service !== "super-pi")
28
+ return result({ reachable: true, service: false, authorized: false, status: response.status, message: `端口可达,但未检测到 Super Pi 服务(HTTP ${response.status})。请检查服务端口或 HTTP / HTTPS 地址。` });
29
+ const access = await fetch(new URL("/api/terminal-shell", address), { headers: key ? { authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(5000), redirect: "manual" });
30
+ const allowed = await access.json().catch(() => null);
31
+ const authorized = access.ok && Boolean(allowed && "shell" in allowed);
32
+ return result({ reachable: true, service: true, authorized, status: access.status, message: authorized ? "Super Pi 服务可直接访问,无需 SSH 隧道。" : "已找到 Super Pi 服务,但访问授权尚未通过,请检查服务访问密钥。" });
33
+ }
34
+ catch {
35
+ return result({ reachable: false, service: false, authorized: false, message: "未能连接此服务端口。请检查 IP、端口、服务监听地址、防火墙或 TLS 配置;本次未尝试 SSH。" });
36
+ }
37
+ }
38
+ export async function directJson(origin, path, key) {
39
+ const response = await fetch(new URL(path, origin), { headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(5000), redirect: "error" });
40
+ if (!response.ok || !response.headers.get("content-type")?.includes("application/json"))
41
+ throw new Error(`Super Pi 服务直连检测失败(HTTP ${response.status})`);
42
+ const value = await response.json();
43
+ if (!value || typeof value !== "object" || Array.isArray(value))
44
+ throw new Error("Super Pi 服务未返回有效状态");
45
+ return value;
46
+ }
47
+ function upstreamHeaders(request, target, key) {
48
+ const result = { ...request.headers, host: target.host, origin: target.origin, authorization: `Bearer ${key}` };
49
+ delete result.cookie;
50
+ delete result["sec-websocket-protocol"];
51
+ return result;
52
+ }
53
+ export function proxyThroughDirect(origin, key, path, request, response, basePath) {
54
+ const target = new URL(path, origin);
55
+ const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(target, { method: request.method, headers: upstreamHeaders(request, target, key) }, result => {
56
+ const outgoing = { ...result.headers };
57
+ delete outgoing["set-cookie"];
58
+ if (path.startsWith("/api/message-artifact?") && target.searchParams.has("frame") && String(outgoing["content-type"]).startsWith("text/html")) {
59
+ delete outgoing["content-length"];
60
+ let html = "";
61
+ result.setEncoding("utf8");
62
+ result.on("data", chunk => { html += chunk; if (html.length > 1024 * 1024)
63
+ result.destroy(); });
64
+ result.once("end", () => response.writeHead(result.statusCode ?? 502, outgoing).end(html.replaceAll('src="/api/message-artifact', `src="${basePath}/api/message-artifact`)));
65
+ }
66
+ else {
67
+ response.writeHead(result.statusCode ?? 502, outgoing);
68
+ result.pipe(response);
69
+ }
70
+ });
71
+ upstream.once("error", () => { if (!response.headersSent)
72
+ response.writeHead(502, { "content-type": "application/json" }).end(JSON.stringify({ error: "Super Pi 服务暂不可达,SSH 状态不影响此直连检测" }));
73
+ else
74
+ response.destroy(); });
75
+ response.once("close", () => upstream.destroy());
76
+ request.pipe(upstream);
77
+ }
78
+ export function proxyWebSocketThroughDirect(origin, key, path, request, socket, head) {
79
+ const target = new URL(path, origin);
80
+ const upstream = (target.protocol === "https:" ? httpsRequest : httpRequest)(target, { headers: upstreamHeaders(request, target, key) });
81
+ const timer = setTimeout(() => upstream.destroy(new Error("Super Pi WebSocket handshake timed out")), 12_000);
82
+ upstream.once("upgrade", (result, channel, upstreamHead) => {
83
+ clearTimeout(timer);
84
+ socket.write(`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(result.headers).filter(([name]) => name !== "set-cookie").map(([name, value]) => `${name}: ${Array.isArray(value) ? value.join(", ") : value}`).join("\r\n")}\r\n\r\n`);
85
+ if (upstreamHead.length)
86
+ socket.write(upstreamHead);
87
+ if (head.length)
88
+ channel.write(head);
89
+ channel.pipe(socket);
90
+ socket.pipe(channel);
91
+ socket.once("close", () => channel.destroy());
92
+ channel.once("close", () => socket.destroy());
93
+ socket.once("error", () => channel.destroy());
94
+ channel.once("error", () => socket.destroy());
95
+ });
96
+ upstream.once("response", result => { clearTimeout(timer); result.resume(); socket.destroy(); });
97
+ upstream.once("error", () => { clearTimeout(timer); socket.destroy(); });
98
+ socket.once("close", () => { clearTimeout(timer); upstream.destroy(); });
99
+ upstream.end();
100
+ }
@@ -61,6 +61,13 @@ export async function handleManagedHttp(context, request, response, url) {
61
61
  }
62
62
  try {
63
63
  const body = JSON.parse(text);
64
+ if (body.action === "probeService") {
65
+ const profile = body.profile ?? { id: body.id };
66
+ if (!profile || typeof profile !== "object" || Array.isArray(profile))
67
+ throw new Error("服务端口测试参数无效");
68
+ json(200, { ...status(), probe: await context.managedServers.probeService(profile) });
69
+ return true;
70
+ }
64
71
  if (body.action === "save") {
65
72
  await context.managedServers.save(body.profile);
66
73
  }
@@ -70,6 +77,13 @@ export async function handleManagedHttp(context, request, response, url) {
70
77
  context.managedServers.answerVerification(body.id, body.verificationId, body.answers);
71
78
  else if (body.action === "cancelVerification")
72
79
  await context.managedServers.cancelVerification(body.id, body.verificationId);
80
+ else if (body.action === "updateSelected") {
81
+ if (!Array.isArray(body.updates) || body.updates.some((item) => typeof item?.id !== "string" || typeof item.version !== "string"))
82
+ throw new Error("更新目标无效");
83
+ const result = context.managedServers.updateSelected(body.updates);
84
+ json(202, { ...status(), ...result });
85
+ return true;
86
+ }
73
87
  else if (body.action === "syncAll") {
74
88
  for (const profile of context.managedServers.list())
75
89
  if (profile.enabled && profile.service === "online" && !profile.existingService?.attached)
@@ -21,6 +21,7 @@ export declare class ManagedServers {
21
21
  private gatewayPort;
22
22
  private timer?;
23
23
  private stopped;
24
+ private maintaining;
24
25
  private persistence;
25
26
  private artifact?;
26
27
  constructor(directory: string, packageRoot: string, defaultModel: () => {
@@ -43,6 +44,9 @@ export declare class ManagedServers {
43
44
  identity?: string;
44
45
  deployedAt?: string;
45
46
  remoteRoot?: string;
47
+ serviceUrl?: string;
48
+ transport?: "direct" | "ssh";
49
+ serviceError?: string;
46
50
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
47
51
  service: "unknown" | "offline" | "online";
48
52
  modelChannel: "offline" | "online";
@@ -59,8 +63,10 @@ export declare class ManagedServers {
59
63
  step?: string;
60
64
  error?: string;
61
65
  log?: string[];
66
+ updateOperation?: import("../shared/update-status.js").UpdateOperation;
62
67
  verification: SshVerification | undefined;
63
68
  }[];
69
+ probeService(input: Partial<ManagedServerInput>): Promise<import("../shared/managed-servers.js").ServiceProbe>;
64
70
  private cancelConnection;
65
71
  private startConnection;
66
72
  answerVerification(id: string, verificationId: string, answers: unknown): void;
@@ -74,17 +80,27 @@ export declare class ManagedServers {
74
80
  private reverseModelChannel;
75
81
  syncModels(id: string, force?: boolean): Promise<void>;
76
82
  private health;
83
+ private checkDirect;
77
84
  private detectExisting;
78
85
  private startExisting;
79
86
  private ensureService;
80
87
  private progress;
81
- deploy(id: string): ManagedServerProfile;
88
+ deploy(id: string, updateVersion?: string): ManagedServerProfile;
89
+ updateSelected(updates: {
90
+ id: string;
91
+ version: string;
92
+ }[]): {
93
+ started: string[];
94
+ errors: Record<string, string>;
95
+ };
96
+ waitForUpdates(ids: string[]): Promise<void>;
82
97
  action(id: string, action: string): Promise<ManagedServerProfile | undefined>;
83
98
  private maintain;
84
99
  connectionProfiles(): {
85
100
  id: string;
86
101
  managedId: string;
87
102
  managed: boolean;
103
+ transport: "direct" | "ssh" | undefined;
88
104
  legacy: boolean;
89
105
  name: string;
90
106
  url: string;