@evandu/super-pi 0.1.271 → 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.
- package/dist/client/.super-pi-client-sources.json +10 -10
- package/dist/client/assets/{CodeMirrorEditor-Q77Plbqw.js → CodeMirrorEditor-D8MjtASz.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-C0XYcNpE.js → GitDiffEditor-DFJmhUHc.js} +1 -1
- package/dist/client/assets/{index-CoLvWsuI.js → index-Bqutm6qV.js} +62 -62
- package/dist/client/index.html +1 -1
- package/dist/server/application/run-service.js +2 -2
- package/dist/server/http-server.js +39 -8
- package/dist/server/managed-http.js +37 -2
- package/dist/server/managed-model-adapter.js +11 -3
- package/dist/server/managed-model-relay.d.ts +12 -0
- package/dist/server/managed-model-relay.js +182 -0
- package/dist/server/managed-servers.d.ts +4 -0
- package/dist/server/managed-servers.js +93 -8
- package/dist/server/turn-failure.d.ts +2 -0
- package/dist/server/turn-failure.js +11 -0
- package/dist/server/types.d.ts +1 -0
- package/dist/server/update.d.ts +6 -0
- package/dist/server/update.js +16 -1
- package/dist/server/ws-server.js +16 -0
- package/dist/shared/managed-servers.d.ts +2 -0
- package/dist/shared/update-status.d.ts +1 -0
- package/package.json +1 -1
package/dist/client/index.html
CHANGED
|
@@ -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-
|
|
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>
|
|
@@ -6,7 +6,7 @@ import { readAgents } from "../agents.js";
|
|
|
6
6
|
import { verifyCapability } from "../capability.js";
|
|
7
7
|
import { capText, validateWorkflowPlan, workflowSummary } from "../workflow.js";
|
|
8
8
|
import { ensureNameIndex, recordWorkspacePath } from "../file-name-index.js";
|
|
9
|
-
import { formatTurnFailure, isLengthExceededError } from "../turn-failure.js";
|
|
9
|
+
import { formatTurnFailure, isLengthExceededError, recordedTurnFailure } from "../turn-failure.js";
|
|
10
10
|
import { isLengthContinuation, lengthContinuationText, MAX_LENGTH_CONTINUATIONS, buildLengthContinuationPrompt } from "../length-continuation.js";
|
|
11
11
|
import { describeThrownWithStack } from "../failure-text.js";
|
|
12
12
|
import { toWorkspaceRelative } from "../files.js";
|
|
@@ -2134,7 +2134,7 @@ export class RunService {
|
|
|
2134
2134
|
// A turn that broke is the failure the reader will complain about, and the banner only carries
|
|
2135
2135
|
// the sentence. The stack goes to the server log, where it can still be found.
|
|
2136
2136
|
console.error("Super Pi turn failed:", describeThrownWithStack(error));
|
|
2137
|
-
throw error;
|
|
2137
|
+
throw recordedTurnFailure(error);
|
|
2138
2138
|
}
|
|
2139
2139
|
finally {
|
|
2140
2140
|
this.releaseRunSlot(conversation.id, controller);
|
|
@@ -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
|
-
|
|
1577
|
-
|
|
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 =
|
|
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
|
-
|
|
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();
|
|
@@ -19,13 +19,21 @@ export async function managedProviderDefinitions(config) {
|
|
|
19
19
|
const latest = await readManagedModelConfig() ?? config;
|
|
20
20
|
const { signal, ...rest } = options ?? {};
|
|
21
21
|
const safeOptions = Object.fromEntries(Object.entries(rest).filter(([key, value]) => ["maxTokens", "temperature", "reasoning", "cacheRetention", "sessionId", "samplingParams", "thinkingBudgets"].includes(key) && typeof value !== "function"));
|
|
22
|
-
const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json" }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions }) })
|
|
22
|
+
const response = await fetch(latest.endpoint, { method: "POST", signal, headers: { authorization: `Bearer ${latest.token}`, "content-type": "application/json" }, body: JSON.stringify({ provider: model.provider, modelId: model.id, context, options: safeOptions }) }).catch(cause => {
|
|
23
|
+
if (signal?.aborted)
|
|
24
|
+
throw cause;
|
|
25
|
+
throw new Error("本地模型通道未连接。请确认入口电脑的 Super Pi 服务正在运行,并查看该服务器的模型通道状态。", { cause });
|
|
26
|
+
});
|
|
23
27
|
if (!response.ok || !response.body)
|
|
24
|
-
throw new Error(
|
|
28
|
+
throw new Error(`模型通道未能完成请求(HTTP ${response.status}),请查看入口电脑的模型通道状态和供应商配置。`);
|
|
25
29
|
const reader = response.body.getReader(), decoder = new TextDecoder();
|
|
26
30
|
let pending = "", settled = false;
|
|
27
31
|
for (;;) {
|
|
28
|
-
const { done, value } = await reader.read()
|
|
32
|
+
const { done, value } = await reader.read().catch(cause => {
|
|
33
|
+
if (signal?.aborted)
|
|
34
|
+
throw cause;
|
|
35
|
+
throw new Error("模型通道在回复完成前断开,请重连后重试", { cause });
|
|
36
|
+
});
|
|
29
37
|
pending += decoder.decode(value, { stream: !done });
|
|
30
38
|
let end;
|
|
31
39
|
while ((end = pending.indexOf("\n")) >= 0) {
|
|
@@ -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,8 @@ 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";
|
|
62
|
+
modelChannelPaused?: boolean;
|
|
59
63
|
phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
|
|
60
64
|
existingService?: {
|
|
61
65
|
running: boolean;
|
|
@@ -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);
|
|
@@ -287,7 +292,7 @@ export class ManagedServers {
|
|
|
287
292
|
return client;
|
|
288
293
|
}
|
|
289
294
|
catch (cause) {
|
|
290
|
-
if (requestedVerification || controller.signal.aborted)
|
|
295
|
+
if (requestedVerification || controller.signal.aborted || cause instanceof Error && cause.message.startsWith("SSH 认证失败"))
|
|
291
296
|
this.authBlocked.add(id);
|
|
292
297
|
this.verifications.get(id)?.reject(cause instanceof Error ? cause : new Error("SSH 验证已结束"));
|
|
293
298
|
this.verifications.delete(id);
|
|
@@ -323,6 +328,10 @@ 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;
|
|
333
|
+
if (entry.profile.modelChannelPaused)
|
|
334
|
+
return;
|
|
326
335
|
try {
|
|
327
336
|
await this.reverseModelChannel(entry, client);
|
|
328
337
|
if (entry.profile.service === "online")
|
|
@@ -345,10 +354,31 @@ export class ManagedServers {
|
|
|
345
354
|
}
|
|
346
355
|
async syncModels(id, force = false, reload = true) {
|
|
347
356
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
348
|
-
|
|
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)
|
|
349
378
|
throw new Error("请先部署并连接此服务器");
|
|
350
379
|
const models = await this.gateway.catalog(force);
|
|
351
|
-
const
|
|
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() });
|
|
352
382
|
const hash = createHash("sha256").update(content).digest("hex");
|
|
353
383
|
if (hash === entry.modelHash)
|
|
354
384
|
return;
|
|
@@ -425,6 +455,34 @@ export class ManagedServers {
|
|
|
425
455
|
profile.transport = "direct";
|
|
426
456
|
profile.service = "online";
|
|
427
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
|
+
}
|
|
428
486
|
if (!this.jobs.has(id) && !this.connecting.has(id))
|
|
429
487
|
profile.phase = "ready";
|
|
430
488
|
return true;
|
|
@@ -432,6 +490,8 @@ export class ManagedServers {
|
|
|
432
490
|
catch (error) {
|
|
433
491
|
if (!profile.enabled || this.records.get(id) !== entry)
|
|
434
492
|
return false;
|
|
493
|
+
if (!this.relays.has(id) && profile.allowServiceTunnel)
|
|
494
|
+
delete profile.modelTransport;
|
|
435
495
|
if (profile.transport === "ssh" && profile.allowServiceTunnel && this.clients.has(id))
|
|
436
496
|
return false;
|
|
437
497
|
profile.serviceError = error instanceof Error && error.message !== "fetch failed" ? error.message : "直连服务端口不可达,请检查 IP、端口和服务监听地址。";
|
|
@@ -606,7 +666,19 @@ export class ManagedServers {
|
|
|
606
666
|
const secret = this.secrets.get(id);
|
|
607
667
|
await sshWrite(client, posix.join(installation.root, "data", "browser-access.json"), JSON.stringify({ id: entry.profile.identity, key: secret.browserKey }));
|
|
608
668
|
this.progress(entry, "建立模型通道并同步本地模型目录");
|
|
609
|
-
await
|
|
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
|
+
}
|
|
610
682
|
entry.modelHash = undefined;
|
|
611
683
|
await this.syncModels(id, false, false);
|
|
612
684
|
this.progress(entry, "启动远端 Super Pi 服务");
|
|
@@ -695,6 +767,8 @@ export class ManagedServers {
|
|
|
695
767
|
}
|
|
696
768
|
async action(id, action) {
|
|
697
769
|
const entry = this.entry(id);
|
|
770
|
+
if (action === "disconnect" || action === "remove")
|
|
771
|
+
this.relays.get(id)?.terminate();
|
|
698
772
|
if (action === "disconnect") {
|
|
699
773
|
entry.profile.enabled = false;
|
|
700
774
|
await this.cancelConnection(id);
|
|
@@ -707,6 +781,8 @@ export class ManagedServers {
|
|
|
707
781
|
delete entry.profile.error;
|
|
708
782
|
}
|
|
709
783
|
else if (action === "disconnectSsh") {
|
|
784
|
+
if (entry.installation)
|
|
785
|
+
entry.profile.modelChannelPaused = true;
|
|
710
786
|
this.authBlocked.add(id);
|
|
711
787
|
await this.cancelConnection(id);
|
|
712
788
|
this.clients.get(id)?.end();
|
|
@@ -744,7 +820,11 @@ export class ManagedServers {
|
|
|
744
820
|
}
|
|
745
821
|
else if (action === "connectSsh") {
|
|
746
822
|
entry.profile.enabled = true;
|
|
747
|
-
|
|
823
|
+
delete entry.profile.modelChannelPaused;
|
|
824
|
+
if (entry.installation && this.clients.has(id))
|
|
825
|
+
await this.restoreModelChannel(entry, this.clients.get(id));
|
|
826
|
+
else
|
|
827
|
+
this.startConnection(id);
|
|
748
828
|
}
|
|
749
829
|
else if (action === "sync") {
|
|
750
830
|
try {
|
|
@@ -784,8 +864,12 @@ export class ManagedServers {
|
|
|
784
864
|
return;
|
|
785
865
|
const client = this.clients.get(entry.profile.id);
|
|
786
866
|
if (await this.checkDirect(entry.profile.id)) {
|
|
787
|
-
if (entry.installation &&
|
|
788
|
-
|
|
867
|
+
if (entry.installation && entry.profile.modelTransport !== "direct" && !entry.profile.modelChannelPaused) {
|
|
868
|
+
if (client)
|
|
869
|
+
await this.restoreModelChannel(entry, client);
|
|
870
|
+
else if (!this.connecting.has(entry.profile.id) && !this.authBlocked.has(entry.profile.id) && entry.profile.fingerprint && entry.profile.ssh !== "needsTrust")
|
|
871
|
+
this.startConnection(entry.profile.id);
|
|
872
|
+
}
|
|
789
873
|
return;
|
|
790
874
|
}
|
|
791
875
|
if (this.connecting.has(entry.profile.id) || this.authBlocked.has(entry.profile.id) || entry.profile.ssh === "needsTrust")
|
|
@@ -864,7 +948,8 @@ export class ManagedServers {
|
|
|
864
948
|
await proxyWebSocketThroughSsh(tunnel, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
|
|
865
949
|
}
|
|
866
950
|
}
|
|
867
|
-
async close() { this.stopped = true; clearInterval(this.timer); for (const
|
|
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()])
|
|
868
953
|
await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
|
|
869
954
|
client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
|
|
870
955
|
}
|