@evandu/super-pi 0.1.272 → 0.1.273

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-BsfNx6DV.js"></script>
11
+ <script type="module" crossorigin src="/assets/index-Bqutm6qV.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>
@@ -1,4 +1,6 @@
1
1
  import { handleManagedHttp } from "./managed-http.js";
2
+ import { remoteModelRelay } from "./managed-model-relay.js";
3
+ import { readManagedModelConfig } from "./managed-model-adapter.js";
2
4
  import { ReadReceipts } from "./read-receipts.js";
3
5
  import { createReadStream, existsSync } from "node:fs";
4
6
  import { matchPathMentions } from "../shared/file-mentions.js";
@@ -7,7 +9,7 @@ import { randomUUID } from "node:crypto";
7
9
  import { BrowserAccess, isBrowserAuthorized } from "./browser-access.js";
8
10
  import { NativeToolsService, NativeToolsError } from "./native-tools-service.js";
9
11
  import { once } from "node:events";
10
- import { readdir, realpath, rm, stat } from "node:fs/promises";
12
+ import { access, readFile, readdir, realpath, rm, stat } from "node:fs/promises";
11
13
  import { createServer } from "node:http";
12
14
  import { gzip } from "node:zlib";
13
15
  import { promisify } from "node:util";
@@ -30,7 +32,7 @@ import { GroupChatNotFoundError } from "./application/group-chat-service.js";
30
32
  import { MAX_FEISHU_REQUEST_BYTES } from "./application/feishu-service.js";
31
33
  import { MAX_WEB_REQUEST_BYTES } from "./web.js";
32
34
  import { MAX_TOOL_BODY_BYTES } from "./tool-registry.js";
33
- import { claimUpdateSlot, fetchLatestPackageVersion, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
35
+ import { claimUpdateSlot, fetchLatestPackageVersion, managedUpdatePlan, packageUpdateArgs, releaseUpdateSlot, shellArgs } from "./update.js";
34
36
  import { UpdateTracker } from "./update-status.js";
35
37
  import { updateIsActive } from "../shared/update-status.js";
36
38
  import { FileIndex, refreshWorkspaceIndex } from "./file-index.js";
@@ -386,7 +388,7 @@ export function createHttpServer(options) {
386
388
  const operation = status.operation;
387
389
  const lastUpdate = operation?.phase === "completed" || operation?.phase === "failed"
388
390
  ? { ok: operation.phase === "completed", code: operation.failure?.code, at: operation.changedAt } : null;
389
- return { ...status, updating: updateIsActive(operation), lastUpdate };
391
+ return { ...status, serviceSelfUpdate: true, updating: updateIsActive(operation), lastUpdate };
390
392
  };
391
393
  const server = createServer(async (request, response) => {
392
394
  // Every HTTP request gets one stable id. It is returned to the browser and
@@ -411,6 +413,19 @@ export function createHttpServer(options) {
411
413
  return;
412
414
  }
413
415
  browserAccess.authorize(request);
416
+ if (requestPath === "/api/managed-model/invoke") {
417
+ if (request.method !== "POST" || !isLoopbackAddress(request.socket.remoteAddress) || !process.env.SUPER_PI_MANAGED_CONFIG) {
418
+ response.writeHead(403).end();
419
+ return;
420
+ }
421
+ const config = await readManagedModelConfig();
422
+ if (!config || request.headers.authorization !== `Bearer ${config.token}`) {
423
+ response.writeHead(403).end();
424
+ return;
425
+ }
426
+ await remoteModelRelay.invoke(request, response);
427
+ return;
428
+ }
414
429
  if (process.env.SUPER_PI_REQUIRE_BROWSER_ACCESS === "1" && !isLoopbackAddress(request.socket.remoteAddress) && !isBrowserAuthorized(request)) {
415
430
  response.writeHead(401, { "content-type": "application/json" }).end(JSON.stringify({ error: "远程访问需要服务器连接密钥。" }));
416
431
  return;
@@ -1573,8 +1588,9 @@ export function createHttpServer(options) {
1573
1588
  json(403, { error: "只允许从本机或局域网更新服务。" });
1574
1589
  return;
1575
1590
  }
1576
- if (process.env.SUPER_PI_MANAGED_CONFIG) {
1577
- json(409, { error: "此服务由本地入口托管,请在本地设置的「服务器连接 → SSH 托管」中重新部署以升级。" });
1591
+ const managedConfig = process.env.SUPER_PI_MANAGED_CONFIG;
1592
+ if (managedConfig && !isBrowserAuthorized(request)) {
1593
+ json(403, { error: "升级托管服务需要此服务的管理授权。" });
1578
1594
  return;
1579
1595
  }
1580
1596
  let body = {};
@@ -1601,6 +1617,19 @@ export function createHttpServer(options) {
1601
1617
  json(400, { error: "目标版本格式无效。" });
1602
1618
  return;
1603
1619
  }
1620
+ let managedPlan;
1621
+ if (managedConfig) {
1622
+ try {
1623
+ managedPlan = managedUpdatePlan(rootDir, managedConfig, wantedVersion);
1624
+ await access(managedPlan.launcher);
1625
+ if ((await readFile(managedPlan.pidFile, "utf8")).trim() !== String(process.pid))
1626
+ throw new Error("pid mismatch");
1627
+ }
1628
+ catch {
1629
+ json(409, { error: "无法核对当前托管实例的安装目录、启动脚本或进程号,升级未开始。" });
1630
+ return;
1631
+ }
1632
+ }
1604
1633
  if (!claimUpdateSlot()) {
1605
1634
  const current = updateStatus();
1606
1635
  const error = current.operation?.phase === "restarting" ? "服务正在重启,请等它结束。" : "更新已经在进行中,请等它结束。";
@@ -1637,7 +1666,9 @@ export function createHttpServer(options) {
1637
1666
  const deadline = setTimeout(() => fail("restarting", "等待新服务上线超时,请查看服务日志后重试。"), 150_000);
1638
1667
  deadline.unref();
1639
1668
  try {
1640
- const restart = spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "inherit", env: restartEnv });
1669
+ const restart = managedPlan
1670
+ ? spawn("/bin/sh", [managedPlan.launcher], { cwd: rootDir, detached: true, stdio: "ignore", env: restartEnv })
1671
+ : spawn(process.execPath, [join(rootDir, "scripts", "restart-server.mjs")], { cwd: rootDir, detached: true, stdio: "inherit", env: restartEnv });
1641
1672
  restart.once("error", () => { clearTimeout(deadline); fail("restarting", "无法启动重启程序,请查看服务日志后重试。"); });
1642
1673
  restart.once("exit", (code) => {
1643
1674
  if (code !== 0) {
@@ -1660,7 +1691,7 @@ export function createHttpServer(options) {
1660
1691
  }
1661
1692
  updateTracker.installing(id);
1662
1693
  const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
1663
- const update = packageUpdateArgs(rootDir, wantedVersion);
1694
+ const update = managedPlan ?? packageUpdateArgs(rootDir, wantedVersion);
1664
1695
  try {
1665
1696
  const child = spawn(npmCmd, shellArgs(update.args), { stdio: ["ignore", "ignore", "pipe"], shell: process.platform === "win32", env: process.env });
1666
1697
  let stderr = "";
@@ -1728,7 +1759,7 @@ export function createHttpServer(options) {
1728
1759
  if (url.pathname === "/api/health") {
1729
1760
  const version = checkDiskVersion(rootDir);
1730
1761
  response.writeHead(200, { "content-type": "application/json; charset=utf-8" })
1731
- .end(JSON.stringify({ status: "ok", service: "super-pi", manager: Boolean(context.managedServers), managed: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), ...version }));
1762
+ .end(JSON.stringify({ status: "ok", service: "super-pi", manager: Boolean(context.managedServers), managed: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), modelRelay: Boolean(process.env.SUPER_PI_MANAGED_CONFIG), ...version }));
1732
1763
  return;
1733
1764
  }
1734
1765
  /**
@@ -1,13 +1,17 @@
1
1
  import { isBrowserAuthorized } from "./browser-access.js";
2
2
  import { isLoopbackAddress } from "./http-server.js";
3
+ import { randomUUID } from "node:crypto";
4
+ import { rename, writeFile, rm } from "node:fs/promises";
5
+ import { readManagedModelConfig } from "./managed-model-adapter.js";
3
6
  /** A model-channel token is deliberately never accepted by these management routes. */
4
7
  export async function handleManagedHttp(context, request, response, url) {
5
8
  const route = url.pathname === "/api/managed-servers";
6
9
  const proxy = /^\/managed\/([a-f0-9-]+)(\/.*)$/.exec(url.pathname);
7
- if (!route && !proxy && url.pathname !== "/api/managed-model/reload")
10
+ const syncCatalog = url.pathname === "/api/managed-model/catalog";
11
+ if (!route && !proxy && !syncCatalog && url.pathname !== "/api/managed-model/reload")
8
12
  return false;
9
13
  const json = (status, value) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(value)); };
10
- if (url.pathname === "/api/managed-model/reload") {
14
+ if (syncCatalog || url.pathname === "/api/managed-model/reload") {
11
15
  if (!process.env.SUPER_PI_MANAGED_CONFIG) {
12
16
  json(404, { error: "当前服务未由本地入口托管" });
13
17
  return true;
@@ -16,6 +20,37 @@ export async function handleManagedHttp(context, request, response, url) {
16
20
  json(403, { error: "需要托管服务的管理授权" });
17
21
  return true;
18
22
  }
23
+ if (syncCatalog) {
24
+ const config = await readManagedModelConfig();
25
+ if (!config) {
26
+ json(409, { error: "缺少初始配对配置" });
27
+ return true;
28
+ }
29
+ const parts = [];
30
+ let size = 0;
31
+ for await (const part of request) {
32
+ size += part.length;
33
+ if (size > 8 * 1024 * 1024) {
34
+ json(413, { error: "模型目录过大" });
35
+ return true;
36
+ }
37
+ parts.push(part);
38
+ }
39
+ const catalog = JSON.parse(Buffer.concat(parts).toString("utf8"));
40
+ if (!Array.isArray(catalog.models) || !catalog.models.every((m) => m && typeof m.id === "string" && typeof m.provider === "string")) {
41
+ json(400, { error: "模型目录无效" });
42
+ return true;
43
+ }
44
+ const path = process.env.SUPER_PI_MANAGED_CONFIG;
45
+ const temp = path + "." + randomUUID() + ".tmp";
46
+ try {
47
+ await writeFile(temp, JSON.stringify({ ...config, models: catalog.models, defaultModel: catalog.defaultModel, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
48
+ await rename(temp, path);
49
+ }
50
+ finally {
51
+ await rm(temp, { force: true });
52
+ }
53
+ }
19
54
  context.runtime.invalidateCatalog?.();
20
55
  context.runtime.bumpModelEpoch?.();
21
56
  await context.catalogService.broadcastAllCatalog();
@@ -22,10 +22,10 @@ export async function managedProviderDefinitions(config) {
22
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
23
  if (signal?.aborted)
24
24
  throw cause;
25
- throw new Error("本地模型通道未连接。请在管理电脑的服务器连接中检查模型通道,必要时完成 SSH 验证后重试。", { cause });
25
+ throw new Error("本地模型通道未连接。请确认入口电脑的 Super Pi 服务正在运行,并查看该服务器的模型通道状态。", { cause });
26
26
  });
27
27
  if (!response.ok || !response.body)
28
- throw new Error(`本地模型通道不可用(${response.status}),请检查管理电脑和 SSH 连接`);
28
+ throw new Error(`模型通道未能完成请求(HTTP ${response.status}),请查看入口电脑的模型通道状态和供应商配置。`);
29
29
  const reader = response.body.getReader(), decoder = new TextDecoder();
30
30
  let pending = "", settled = false;
31
31
  for (;;) {
@@ -0,0 +1,12 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import { WebSocket } from "ws";
3
+ export declare class ModelRelay {
4
+ private socket?;
5
+ private requests;
6
+ private waiting;
7
+ close(): void;
8
+ attach(socket: WebSocket): void;
9
+ invoke(request: IncomingMessage, response: ServerResponse): Promise<void>;
10
+ }
11
+ export declare const remoteModelRelay: ModelRelay;
12
+ export declare function connectModelRelay(origin: string, key: string, gatewayPort: number, modelToken: string): WebSocket;
@@ -0,0 +1,182 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { WebSocket } from "ws";
3
+ // Only model requests cross this connection. The destination and credential are
4
+ // selected by the manager and never taken from a remote request.
5
+ const maxRequest = 32 * 1024 * 1024;
6
+ const maxConcurrent = 32;
7
+ export class ModelRelay {
8
+ socket;
9
+ requests = new Map();
10
+ waiting = new Set();
11
+ close() {
12
+ this.socket?.terminate();
13
+ for (const resume of this.waiting)
14
+ resume();
15
+ }
16
+ attach(socket) {
17
+ this.socket?.terminate();
18
+ for (const response of this.requests.values())
19
+ response.destroy();
20
+ this.requests.clear();
21
+ this.socket = socket;
22
+ for (const resume of this.waiting)
23
+ resume();
24
+ socket.on("error", () => socket.terminate());
25
+ socket.on("close", () => {
26
+ if (this.socket !== socket)
27
+ return;
28
+ this.socket = undefined;
29
+ for (const response of this.requests.values())
30
+ response.destroy();
31
+ this.requests.clear();
32
+ });
33
+ socket.on("message", raw => {
34
+ if (this.socket !== socket)
35
+ return;
36
+ try {
37
+ const { id, type, data, status } = JSON.parse(raw.toString());
38
+ const response = this.requests.get(id);
39
+ if (!response)
40
+ return;
41
+ if (type === "start")
42
+ response.writeHead(status, { "content-type": "application/x-ndjson", "cache-control": "no-store" });
43
+ else if (type === "data") {
44
+ if (response.writableLength > maxRequest)
45
+ response.destroy();
46
+ else
47
+ response.write(Buffer.from(data, "base64"));
48
+ }
49
+ else if (type === "end") {
50
+ this.requests.delete(id);
51
+ response.end();
52
+ }
53
+ else if (type === "error") {
54
+ this.requests.delete(id);
55
+ if (response.headersSent)
56
+ response.destroy();
57
+ else
58
+ response.writeHead(502).end();
59
+ }
60
+ }
61
+ catch {
62
+ socket.terminate();
63
+ }
64
+ });
65
+ }
66
+ async invoke(request, response) {
67
+ // Allow the manager's next health poll to reconnect after a service restart.
68
+ if (this.socket?.readyState !== WebSocket.OPEN && this.waiting.size < maxConcurrent) {
69
+ await new Promise(resolve => {
70
+ const resume = () => {
71
+ clearTimeout(timer);
72
+ response.off("close", resume);
73
+ this.waiting.delete(resume);
74
+ resolve();
75
+ };
76
+ const timer = setTimeout(resume, 15000);
77
+ response.once("close", resume);
78
+ this.waiting.add(resume);
79
+ });
80
+ if (response.destroyed)
81
+ return;
82
+ }
83
+ const socket = this.socket;
84
+ if (socket?.readyState !== WebSocket.OPEN) {
85
+ response.writeHead(503).end();
86
+ return;
87
+ }
88
+ const parts = [];
89
+ let size = 0;
90
+ for await (const chunk of request) {
91
+ size += chunk.length;
92
+ if (size > maxRequest) {
93
+ response.writeHead(413).end();
94
+ return;
95
+ }
96
+ parts.push(chunk);
97
+ }
98
+ if (this.socket !== socket || socket.readyState !== WebSocket.OPEN || this.requests.size >= maxConcurrent || socket.bufferedAmount > maxRequest) {
99
+ response.writeHead(503).end();
100
+ return;
101
+ }
102
+ const id = randomUUID();
103
+ this.requests.set(id, response);
104
+ response.once("close", () => {
105
+ if (this.requests.delete(id) && socket.readyState === WebSocket.OPEN)
106
+ socket.send(JSON.stringify({ type: "cancel", id }));
107
+ });
108
+ socket.send(JSON.stringify({ id, type: "request", body: Buffer.concat(parts).toString("base64") }), error => { if (error)
109
+ response.destroy(); });
110
+ }
111
+ }
112
+ export const remoteModelRelay = new ModelRelay();
113
+ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
114
+ const url = new URL("/api/managed-model/channel", origin);
115
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
116
+ const socket = new WebSocket(url, { headers: { authorization: `Bearer ${key}` }, handshakeTimeout: 5000, maxPayload: 48 * 1024 * 1024 });
117
+ const active = new Map();
118
+ let alive = true;
119
+ const heartbeat = setInterval(() => {
120
+ if (socket.readyState !== WebSocket.OPEN)
121
+ return;
122
+ if (!alive) {
123
+ socket.terminate();
124
+ return;
125
+ }
126
+ alive = false;
127
+ socket.ping();
128
+ }, 15000);
129
+ heartbeat.unref();
130
+ socket.on("pong", () => { alive = true; });
131
+ socket.on("error", () => socket.terminate());
132
+ socket.on("close", () => { clearInterval(heartbeat); for (const controller of active.values())
133
+ controller.abort(); });
134
+ const send = (value) => new Promise((resolve, reject) => socket.send(JSON.stringify(value), error => error ? reject(error) : resolve()));
135
+ socket.on("message", async (raw) => {
136
+ let message;
137
+ try {
138
+ message = JSON.parse(raw.toString());
139
+ }
140
+ catch {
141
+ socket.terminate();
142
+ return;
143
+ }
144
+ if (!message || typeof message !== "object") {
145
+ socket.terminate();
146
+ return;
147
+ }
148
+ const { id, type, body } = message;
149
+ if (type === "cancel") {
150
+ active.get(id)?.abort();
151
+ return;
152
+ }
153
+ if (type !== "request" || typeof id !== "string" || typeof body !== "string" || active.has(id) || active.size >= maxConcurrent) {
154
+ socket.terminate();
155
+ return;
156
+ }
157
+ const controller = new AbortController();
158
+ active.set(id, controller);
159
+ try {
160
+ const result = await fetch(`http://127.0.0.1:${gatewayPort}/model`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
161
+ await send({ id, type: "start", status: result.status });
162
+ const reader = result.body?.getReader();
163
+ if (reader)
164
+ for (;;) {
165
+ const { value, done } = await reader.read();
166
+ if (done)
167
+ break;
168
+ await send({ id, type: "data", data: Buffer.from(value).toString("base64") });
169
+ }
170
+ await send({ id, type: "end" });
171
+ }
172
+ catch {
173
+ if (socket.readyState === WebSocket.OPEN)
174
+ await send({ id, type: "error" }).catch(() => { });
175
+ }
176
+ finally {
177
+ controller.abort();
178
+ active.delete(id);
179
+ }
180
+ });
181
+ return socket;
182
+ }
@@ -18,6 +18,8 @@ export declare class ManagedServers {
18
18
  private readonly recoveries;
19
19
  private readonly vault;
20
20
  private readonly gateway;
21
+ private readonly relays;
22
+ private readonly syncedRelays;
21
23
  private gatewayServer?;
22
24
  private gatewayPort;
23
25
  private timer?;
@@ -56,6 +58,7 @@ export declare class ManagedServers {
56
58
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
57
59
  service: "unknown" | "offline" | "online";
58
60
  modelChannel: "offline" | "online";
61
+ modelTransport?: "direct";
59
62
  modelChannelPaused?: boolean;
60
63
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
61
64
  existingService?: {
@@ -6,6 +6,8 @@ import { join, posix } from "node:path";
6
6
  import { pathToFileURL } from "node:url";
7
7
  import { ManagerVault } from "./manager-vault.js";
8
8
  import { ManagedModelGateway } from "./managed-model-gateway.js";
9
+ import { WebSocket } from "ws";
10
+ import { connectModelRelay } from "./managed-model-relay.js";
9
11
  import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
10
12
  import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
11
13
  import { installRemote, startRemote } from "./remote-bootstrap.js";
@@ -29,6 +31,8 @@ export class ManagedServers {
29
31
  recoveries = new Map();
30
32
  vault;
31
33
  gateway = new ManagedModelGateway();
34
+ relays = new Map();
35
+ syncedRelays = new Map();
32
36
  gatewayServer;
33
37
  gatewayPort = 0;
34
38
  timer;
@@ -180,6 +184,7 @@ export class ManagedServers {
180
184
  profile.serviceError = undefined;
181
185
  profile.sshError = undefined;
182
186
  profile.modelError = undefined;
187
+ this.relays.get(id)?.terminate();
183
188
  this.clients.get(id)?.end();
184
189
  this.clients.delete(id);
185
190
  await this.vault.write(id, secret);
@@ -323,6 +328,8 @@ export class ManagedServers {
323
328
  entry.profile.modelChannel = "online";
324
329
  }
325
330
  async restoreModelChannel(entry, client) {
331
+ if (this.relays.has(entry.profile.id))
332
+ return;
326
333
  if (entry.profile.modelChannelPaused)
327
334
  return;
328
335
  try {
@@ -347,10 +354,31 @@ export class ManagedServers {
347
354
  }
348
355
  async syncModels(id, force = false, reload = true) {
349
356
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
350
- if (!entry.installation || !entry.reversePort || !client || !secret)
357
+ const relay = this.relays.get(id);
358
+ if (reload && entry.profile.modelTransport === "direct" && relay?.readyState !== WebSocket.OPEN)
359
+ throw new Error("服务端口的模型通道正在连接,请稍后重试");
360
+ if (reload && entry.installation && secret && relay?.readyState === WebSocket.OPEN && entry.profile.serviceUrl) {
361
+ const body = JSON.stringify({ models: await this.gateway.catalog(force), defaultModel: this.defaultModel() });
362
+ const hash = createHash("sha256").update(body).digest("hex");
363
+ if (!force && this.syncedRelays.get(relay) === hash)
364
+ return;
365
+ const res = await fetch(new URL("/api/managed-model/catalog", entry.profile.serviceUrl), { method: "POST", redirect: "error", headers: { authorization: `Bearer ${secret.browserKey}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(30000) });
366
+ if (!res.ok)
367
+ throw new Error(`通过服务端口同步模型目录失败(HTTP ${res.status})`);
368
+ await res.arrayBuffer();
369
+ if (this.relays.get(id) === relay) {
370
+ this.syncedRelays.set(relay, hash);
371
+ entry.profile.modelChannel = "online";
372
+ delete entry.profile.modelError;
373
+ }
374
+ return;
375
+ }
376
+ const directBootstrap = !reload && entry.profile.modelTransport === "direct";
377
+ if (!entry.installation || (!entry.reversePort && !directBootstrap) || !client || !secret)
351
378
  throw new Error("请先部署并连接此服务器");
352
379
  const models = await this.gateway.catalog(force);
353
- const content = JSON.stringify({ endpoint: `http://127.0.0.1:${entry.reversePort}/model`, token: secret.modelToken, models, defaultModel: this.defaultModel() });
380
+ const endpoint = directBootstrap ? `http://127.0.0.1:${entry.profile.servicePort}/api/managed-model/invoke` : `http://127.0.0.1:${entry.reversePort}/model`;
381
+ const content = JSON.stringify({ endpoint, token: secret.modelToken, models, defaultModel: this.defaultModel() });
354
382
  const hash = createHash("sha256").update(content).digest("hex");
355
383
  if (hash === entry.modelHash)
356
384
  return;
@@ -427,6 +455,34 @@ export class ManagedServers {
427
455
  profile.transport = "direct";
428
456
  profile.service = "online";
429
457
  delete profile.serviceError;
458
+ if (entry.installation && health.modelRelay === true && !this.stopped) {
459
+ profile.modelTransport = "direct";
460
+ delete profile.modelChannelPaused;
461
+ let relay = this.relays.get(id);
462
+ if (!relay) {
463
+ profile.modelChannel = "offline";
464
+ relay = connectModelRelay(profile.serviceUrl, key, this.gatewayPort, secret.modelToken);
465
+ this.relays.set(id, relay);
466
+ const current = relay;
467
+ relay.once("close", () => {
468
+ this.syncedRelays.delete(current);
469
+ if (this.relays.get(id) !== current)
470
+ return;
471
+ this.relays.delete(id);
472
+ profile.modelChannel = "offline";
473
+ });
474
+ relay.once("open", () => { void this.syncModels(id).catch(error => { profile.modelError = String(error.message); }); });
475
+ }
476
+ else if (relay.readyState === WebSocket.OPEN) {
477
+ await this.syncModels(id).catch(error => { profile.modelError = String(error.message); });
478
+ if (this.syncedRelays.has(relay))
479
+ profile.modelChannel = "online";
480
+ }
481
+ }
482
+ else {
483
+ delete profile.modelTransport;
484
+ this.relays.get(id)?.terminate();
485
+ }
430
486
  if (!this.jobs.has(id) && !this.connecting.has(id))
431
487
  profile.phase = "ready";
432
488
  return true;
@@ -434,6 +490,8 @@ export class ManagedServers {
434
490
  catch (error) {
435
491
  if (!profile.enabled || this.records.get(id) !== entry)
436
492
  return false;
493
+ if (!this.relays.has(id) && profile.allowServiceTunnel)
494
+ delete profile.modelTransport;
437
495
  if (profile.transport === "ssh" && profile.allowServiceTunnel && this.clients.has(id))
438
496
  return false;
439
497
  profile.serviceError = error instanceof Error && error.message !== "fetch failed" ? error.message : "直连服务端口不可达,请检查 IP、端口和服务监听地址。";
@@ -608,7 +666,19 @@ export class ManagedServers {
608
666
  const secret = this.secrets.get(id);
609
667
  await sshWrite(client, posix.join(installation.root, "data", "browser-access.json"), JSON.stringify({ id: entry.profile.identity, key: secret.browserKey }));
610
668
  this.progress(entry, "建立模型通道并同步本地模型目录");
611
- await this.reverseModelChannel(entry, client);
669
+ const directBootstrap = entry.profile.serviceHost && entry.profile.serviceHost !== "127.0.0.1" && (await sshExec(client, `test -f ${sh(posix.join(installation.packageRoot, "dist/server/managed-model-relay.js"))} && echo ready || echo legacy`)).trim() === "ready";
670
+ this.relays.get(id)?.terminate();
671
+ this.relays.delete(id);
672
+ if (directBootstrap) {
673
+ entry.profile.modelChannel = "offline";
674
+ entry.profile.modelTransport = "direct";
675
+ }
676
+ else {
677
+ if (entry.profile.modelTransport === "direct")
678
+ entry.profile.modelChannel = "offline";
679
+ delete entry.profile.modelTransport;
680
+ await this.reverseModelChannel(entry, client);
681
+ }
612
682
  entry.modelHash = undefined;
613
683
  await this.syncModels(id, false, false);
614
684
  this.progress(entry, "启动远端 Super Pi 服务");
@@ -697,6 +767,8 @@ export class ManagedServers {
697
767
  }
698
768
  async action(id, action) {
699
769
  const entry = this.entry(id);
770
+ if (action === "disconnect" || action === "remove")
771
+ this.relays.get(id)?.terminate();
700
772
  if (action === "disconnect") {
701
773
  entry.profile.enabled = false;
702
774
  await this.cancelConnection(id);
@@ -792,7 +864,7 @@ export class ManagedServers {
792
864
  return;
793
865
  const client = this.clients.get(entry.profile.id);
794
866
  if (await this.checkDirect(entry.profile.id)) {
795
- if (entry.installation && !entry.profile.modelChannelPaused) {
867
+ if (entry.installation && entry.profile.modelTransport !== "direct" && !entry.profile.modelChannelPaused) {
796
868
  if (client)
797
869
  await this.restoreModelChannel(entry, client);
798
870
  else if (!this.connecting.has(entry.profile.id) && !this.authBlocked.has(entry.profile.id) && entry.profile.fingerprint && entry.profile.ssh !== "needsTrust")
@@ -876,7 +948,8 @@ export class ManagedServers {
876
948
  await proxyWebSocketThroughSsh(tunnel, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
877
949
  }
878
950
  }
879
- async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
951
+ async close() { this.stopped = true; clearInterval(this.timer); for (const relay of this.relays.values())
952
+ relay.terminate(); for (const id of [...this.pendingConnections.keys()])
880
953
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
881
954
  client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
882
955
  }
@@ -40,6 +40,12 @@ export declare function packageUpdateArgs(rootDir: string, version?: string, pla
40
40
  args: string[];
41
41
  prefix?: string;
42
42
  };
43
+ /** Managed installs are private npm projects underneath the instance directory. */
44
+ export declare function managedUpdatePlan(rootDir: string, config: string, version?: string): {
45
+ launcher: string;
46
+ pidFile: string;
47
+ args: string[];
48
+ };
43
49
  /** Claims the update slot. False when an update is already running. */
44
50
  export declare function claimUpdateSlot(): boolean;
45
51
  /** Releases the update slot, so the next update can start. */
@@ -1,5 +1,5 @@
1
1
  import { readFileSync } from "node:fs";
2
- import { join, resolve } from "node:path";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
3
  import { npmInstallPrefix } from "../../bin/npm-prefix.js";
4
4
  /**
5
5
  * Quote an argument for a shell on Windows.
@@ -82,6 +82,21 @@ export function packageUpdateArgs(rootDir, version, platform = process.platform)
82
82
  }
83
83
  return { args: ["install", "-g", "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
84
84
  }
85
+ /** Managed installs are private npm projects underneath the instance directory. */
86
+ export function managedUpdatePlan(rootDir, config, version) {
87
+ const instance = dirname(resolve(config));
88
+ const prefix = resolve(rootDir, "../../..");
89
+ if (basename(config) !== "models.json" || dirname(prefix) !== instance ||
90
+ !/^runtime-[a-f0-9]{16}$/.test(basename(prefix)) ||
91
+ resolve(rootDir) !== join(prefix, "node_modules", "@evandu", "super-pi-server")) {
92
+ throw new Error("当前服务的安装路径与托管实例不匹配,无法确定升级位置。");
93
+ }
94
+ return {
95
+ launcher: join(instance, "start-service.sh"),
96
+ pidFile: join(instance, "service.pid"),
97
+ args: ["install", "--prefix", prefix, "--omit=dev", "--no-audit", "--no-fund", "--fetch-timeout=900000", "--fetch-retries=3", `@evandu/super-pi-server@${version ?? "latest"}`],
98
+ };
99
+ }
85
100
  /**
86
101
  * ONE UPDATE AT A TIME.
87
102
  *
@@ -1,5 +1,6 @@
1
1
  import { isBrowserAuthorized } from "./browser-access.js";
2
2
  import { WebSocket, WebSocketServer } from "ws";
3
+ import { remoteModelRelay } from "./managed-model-relay.js";
3
4
  import { isAuthorized, isLoopbackAddress } from "./http-server.js";
4
5
  import { describeThrown, describeThrownWithStack } from "./failure-text.js";
5
6
  import { isRecordedTurnFailure } from "./turn-failure.js";
@@ -390,6 +391,18 @@ export class WsServer {
390
391
  return;
391
392
  }
392
393
  const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
394
+ if (url.pathname === "/api/managed-model/channel") {
395
+ if (!process.env.SUPER_PI_MANAGED_CONFIG || !browserAuthorized) {
396
+ socket.destroy();
397
+ return;
398
+ }
399
+ this.websocketServer.handleUpgrade(request, socket, head, ws => {
400
+ const release = this.browserAccess.onRevoke(() => ws.terminate());
401
+ ws.once("close", release);
402
+ remoteModelRelay.attach(ws);
403
+ });
404
+ return;
405
+ }
393
406
  const managed = /^\/managed\/([a-f0-9-]+)(\/ws)$/.exec(url.pathname);
394
407
  if (managed) {
395
408
  if (!this.managedServers || !isAuthorized(request, this.accessToken)
@@ -638,6 +651,7 @@ export class WsServer {
638
651
  // A pending state window must not outlive the server: the timer holds the event loop
639
652
  // open, and a flush after the sockets are closed would send to a dead peer.
640
653
  this.broadcaster.dispose();
654
+ remoteModelRelay.close();
641
655
  for (const socket of this.broadcaster.getSockets()) {
642
656
  socket.close(1001, "server-shutdown");
643
657
  }
@@ -46,6 +46,7 @@ export interface ManagedServerProfile {
46
46
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
47
47
  service: "unknown" | "offline" | "online";
48
48
  modelChannel: "offline" | "online";
49
+ modelTransport?: "direct";
49
50
  modelChannelPaused?: boolean;
50
51
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
51
52
  verification?: SshVerification;