@evandu/super-pi 0.1.272 → 0.1.274

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 (75) hide show
  1. package/agents/group-rsi.md +18 -0
  2. package/agents/super-pi-task/core.ts +7 -7
  3. package/bin/completion.js +19 -5
  4. package/bin/super-pi.js +3 -0
  5. package/desktop/runtime.cjs +28 -4
  6. package/dist/client/.super-pi-client-sources.json +26 -18
  7. package/dist/client/assets/CodeMirrorEditor-DjMbNm7l.js +2 -0
  8. package/dist/client/assets/GitDiffEditor-Cwim9Ua1.js +29 -0
  9. package/dist/client/assets/{dist-DGBjhKI9.js → dist-AW5lyI3I.js} +1 -1
  10. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  11. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  12. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  13. package/dist/client/assets/{dist-BvjUKkwy.js → dist-BRVQKlcp.js} +1 -1
  14. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  15. package/dist/client/assets/{dist-BlRuQIg1.js → dist-BXAOrsjq.js} +1 -1
  16. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  17. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  18. package/dist/client/assets/{dist-i79xiXVk.js → dist-Cus6_oaF.js} +2 -2
  19. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  20. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  21. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  22. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  23. package/dist/client/assets/dist-DeD9copn.js +1 -0
  24. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  25. package/dist/client/assets/{dist-D5u1uPmZ.js → dist-Dvb0SqcK.js} +2 -2
  26. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  27. package/dist/client/assets/{dist-CQncCwUc.js → dist-QzbOCAU6.js} +1 -1
  28. package/dist/client/assets/{dist-DjI7p99D.js → dist-moiMRpw_.js} +1 -1
  29. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  30. package/dist/client/assets/index-BL9o4WZN.js +350 -0
  31. package/dist/client/assets/index-D1qJmoVY.css +1 -0
  32. package/dist/client/index.html +2 -2
  33. package/dist/server/application/conversation-service.d.ts +1 -1
  34. package/dist/server/application/conversation-service.js +3 -2
  35. package/dist/server/application/group-chat-service.d.ts +17 -0
  36. package/dist/server/application/group-chat-service.js +168 -3
  37. package/dist/server/application/group-rsi.d.ts +13 -0
  38. package/dist/server/application/group-rsi.js +69 -0
  39. package/dist/server/application/worktree-service.js +6 -2
  40. package/dist/server/http-server.js +61 -8
  41. package/dist/server/index.js +15 -2
  42. package/dist/server/managed-http.js +38 -2
  43. package/dist/server/managed-model-adapter.d.ts +4 -0
  44. package/dist/server/managed-model-adapter.js +2 -2
  45. package/dist/server/managed-model-relay.d.ts +12 -0
  46. package/dist/server/managed-model-relay.js +185 -0
  47. package/dist/server/managed-servers.d.ts +13 -1
  48. package/dist/server/managed-servers.js +140 -8
  49. package/dist/server/remote-bootstrap.d.ts +11 -0
  50. package/dist/server/remote-bootstrap.js +105 -29
  51. package/dist/server/update.d.ts +6 -0
  52. package/dist/server/update.js +16 -1
  53. package/dist/server/ws-server.js +14 -0
  54. package/dist/shared/group-chat.d.ts +40 -0
  55. package/dist/shared/managed-servers.d.ts +1 -0
  56. package/dist/shared/update-status.d.ts +1 -0
  57. package/package.json +2 -1
  58. package/dist/client/assets/CodeMirrorEditor-BOfFOmcv.js +0 -2
  59. package/dist/client/assets/GitDiffEditor-DaN0Ye4q.js +0 -29
  60. package/dist/client/assets/dist-3qQVP6l8.js +0 -6
  61. package/dist/client/assets/dist-CZ4PyxQu.js +0 -9
  62. package/dist/client/assets/dist-CfTFp0AF.js +0 -2
  63. package/dist/client/assets/dist-CxmJXjJI.js +0 -1
  64. package/dist/client/assets/dist-D8HpMxmZ.js +0 -1
  65. package/dist/client/assets/dist-DRBIy9A1.js +0 -1
  66. package/dist/client/assets/dist-Dcww9FSw.js +0 -1
  67. package/dist/client/assets/dist-DlPa5gNa.js +0 -7
  68. package/dist/client/assets/dist-DxPJ1PN-.js +0 -1
  69. package/dist/client/assets/dist-HXD8sSA4.js +0 -23
  70. package/dist/client/assets/dist-LbeLCeoq.js +0 -1
  71. package/dist/client/assets/dist-ONdtnupI.js +0 -1
  72. package/dist/client/assets/dist-YqmXusLA.js +0 -11
  73. package/dist/client/assets/dist-ZAR1Tu2c.js +0 -3
  74. package/dist/client/assets/index-BsfNx6DV.js +0 -350
  75. package/dist/client/assets/index-DV3qc1Hh.css +0 -1
@@ -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,38 @@ 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, entryIntegrations: catalog.entryIntegrations, endpoint: `http://127.0.0.1:${request.socket.localPort}/api/managed-model/invoke` }), { mode: 0o600 });
48
+ await rename(temp, path);
49
+ process.env.SUPER_PI_WEB_ENABLED = catalog.entryIntegrations?.web === true ? "1" : "0";
50
+ }
51
+ finally {
52
+ await rm(temp, { force: true });
53
+ }
54
+ }
19
55
  context.runtime.invalidateCatalog?.();
20
56
  context.runtime.bumpModelEpoch?.();
21
57
  await context.catalogService.broadcastAllCatalog();
@@ -1,5 +1,9 @@
1
1
  import type { Model } from "@earendil-works/pi-ai";
2
2
  export interface ManagedModelConfig {
3
+ entryIntegrations?: {
4
+ web: boolean;
5
+ feishu: boolean;
6
+ };
3
7
  endpoint: string;
4
8
  token: string;
5
9
  models: Model<string>[];
@@ -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, path?: string, payload?: string): 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,185 @@
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, contentType } = 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": contentType === "application/json" ? contentType : "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, path = "/model", payload) {
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
+ if (payload !== undefined)
91
+ parts.push(Buffer.from(payload));
92
+ else
93
+ for await (const chunk of request) {
94
+ size += chunk.length;
95
+ if (size > maxRequest) {
96
+ response.writeHead(413).end();
97
+ return;
98
+ }
99
+ parts.push(chunk);
100
+ }
101
+ if (this.socket !== socket || socket.readyState !== WebSocket.OPEN || this.requests.size >= maxConcurrent || socket.bufferedAmount > maxRequest) {
102
+ response.writeHead(503).end();
103
+ return;
104
+ }
105
+ const id = randomUUID();
106
+ this.requests.set(id, response);
107
+ response.once("close", () => {
108
+ if (this.requests.delete(id) && socket.readyState === WebSocket.OPEN)
109
+ socket.send(JSON.stringify({ type: "cancel", id }));
110
+ });
111
+ socket.send(JSON.stringify({ id, type: "request", path, body: Buffer.concat(parts).toString("base64") }), error => { if (error)
112
+ response.destroy(); });
113
+ }
114
+ }
115
+ export const remoteModelRelay = new ModelRelay();
116
+ export function connectModelRelay(origin, key, gatewayPort, modelToken) {
117
+ const url = new URL("/api/managed-model/channel", origin);
118
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
119
+ const socket = new WebSocket(url, { headers: { authorization: `Bearer ${key}` }, handshakeTimeout: 5000, maxPayload: 48 * 1024 * 1024 });
120
+ const active = new Map();
121
+ let alive = true;
122
+ const heartbeat = setInterval(() => {
123
+ if (socket.readyState !== WebSocket.OPEN)
124
+ return;
125
+ if (!alive) {
126
+ socket.terminate();
127
+ return;
128
+ }
129
+ alive = false;
130
+ socket.ping();
131
+ }, 15000);
132
+ heartbeat.unref();
133
+ socket.on("pong", () => { alive = true; });
134
+ socket.on("error", () => socket.terminate());
135
+ socket.on("close", () => { clearInterval(heartbeat); for (const controller of active.values())
136
+ controller.abort(); });
137
+ const send = (value) => new Promise((resolve, reject) => socket.send(JSON.stringify(value), error => error ? reject(error) : resolve()));
138
+ socket.on("message", async (raw) => {
139
+ let message;
140
+ try {
141
+ message = JSON.parse(raw.toString());
142
+ }
143
+ catch {
144
+ socket.terminate();
145
+ return;
146
+ }
147
+ if (!message || typeof message !== "object") {
148
+ socket.terminate();
149
+ return;
150
+ }
151
+ const { id, type, body, path = "/model" } = message;
152
+ if (type === "cancel") {
153
+ active.get(id)?.abort();
154
+ return;
155
+ }
156
+ if (type !== "request" || typeof id !== "string" || typeof body !== "string" || !["/model", "/integration/web", "/integration/feishu"].includes(path) || active.has(id) || active.size >= maxConcurrent) {
157
+ socket.terminate();
158
+ return;
159
+ }
160
+ const controller = new AbortController();
161
+ active.set(id, controller);
162
+ try {
163
+ const result = await fetch(`http://127.0.0.1:${gatewayPort}${path}`, { method: "POST", redirect: "error", headers: { authorization: `Bearer ${modelToken}`, "content-type": "application/json" }, body: Buffer.from(body, "base64"), signal: controller.signal });
164
+ await send({ id, type: "start", status: result.status, contentType: result.headers.get("content-type") });
165
+ const reader = result.body?.getReader();
166
+ if (reader)
167
+ for (;;) {
168
+ const { value, done } = await reader.read();
169
+ if (done)
170
+ break;
171
+ await send({ id, type: "data", data: Buffer.from(value).toString("base64") });
172
+ }
173
+ await send({ id, type: "end" });
174
+ }
175
+ catch {
176
+ if (socket.readyState === WebSocket.OPEN)
177
+ await send({ id, type: "error" }).catch(() => { });
178
+ }
179
+ finally {
180
+ controller.abort();
181
+ active.delete(id);
182
+ }
183
+ });
184
+ return socket;
185
+ }
@@ -2,10 +2,18 @@ import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import type { Duplex } from "node:stream";
3
3
  import type { Client } from "ssh2";
4
4
  import type { ManagedServerInput, ManagedServerProfile, SshVerification } from "../shared/managed-servers.js";
5
+ interface EntryIntegrations {
6
+ available(): {
7
+ web: boolean;
8
+ feishu: boolean;
9
+ };
10
+ invoke(kind: "web" | "feishu", body: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;
11
+ }
5
12
  export declare class ManagedServers {
6
13
  private readonly directory;
7
14
  private readonly packageRoot;
8
15
  private readonly defaultModel;
16
+ private readonly integrations?;
9
17
  private readonly records;
10
18
  private readonly clients;
11
19
  private readonly secrets;
@@ -18,6 +26,8 @@ export declare class ManagedServers {
18
26
  private readonly recoveries;
19
27
  private readonly vault;
20
28
  private readonly gateway;
29
+ private readonly relays;
30
+ private readonly syncedRelays;
21
31
  private gatewayServer?;
22
32
  private gatewayPort;
23
33
  private timer?;
@@ -28,7 +38,7 @@ export declare class ManagedServers {
28
38
  constructor(directory: string, packageRoot: string, defaultModel: () => {
29
39
  provider: string;
30
40
  modelId: string;
31
- } | undefined);
41
+ } | undefined, integrations?: EntryIntegrations | undefined);
32
42
  initialize(): Promise<void>;
33
43
  list(): {
34
44
  id: string;
@@ -56,6 +66,7 @@ export declare class ManagedServers {
56
66
  ssh: "offline" | "connecting" | "online" | "needsTrust" | "awaitingVerification";
57
67
  service: "unknown" | "offline" | "online";
58
68
  modelChannel: "offline" | "online";
69
+ modelTransport?: "direct";
59
70
  modelChannelPaused?: boolean;
60
71
  phase: "idle" | "connecting" | "needsTrust" | "awaitingVerification" | "deploying" | "ready" | "failed";
61
72
  existingService?: {
@@ -126,3 +137,4 @@ export declare class ManagedServers {
126
137
  upgrade(id: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): Promise<void>;
127
138
  close(): Promise<void>;
128
139
  }
140
+ export {};
@@ -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";
@@ -17,6 +19,7 @@ export class ManagedServers {
17
19
  directory;
18
20
  packageRoot;
19
21
  defaultModel;
22
+ integrations;
20
23
  records = new Map();
21
24
  clients = new Map();
22
25
  secrets = new Map();
@@ -29,6 +32,8 @@ export class ManagedServers {
29
32
  recoveries = new Map();
30
33
  vault;
31
34
  gateway = new ManagedModelGateway();
35
+ relays = new Map();
36
+ syncedRelays = new Map();
32
37
  gatewayServer;
33
38
  gatewayPort = 0;
34
39
  timer;
@@ -36,10 +41,11 @@ export class ManagedServers {
36
41
  maintaining = false;
37
42
  persistence = Promise.resolve();
38
43
  artifact;
39
- constructor(directory, packageRoot, defaultModel) {
44
+ constructor(directory, packageRoot, defaultModel, integrations) {
40
45
  this.directory = directory;
41
46
  this.packageRoot = packageRoot;
42
47
  this.defaultModel = defaultModel;
48
+ this.integrations = integrations;
43
49
  this.vault = new ManagerVault(join(directory, "credentials"));
44
50
  }
45
51
  async initialize() {
@@ -79,7 +85,45 @@ export class ManagedServers {
79
85
  const expected = Buffer.from(token);
80
86
  return supplied.length === expected.length && timingSafeEqual(supplied, expected);
81
87
  });
82
- if (request.url !== "/model" || !valid) {
88
+ if (!valid) {
89
+ response.writeHead(403).end();
90
+ return;
91
+ }
92
+ if (["/integration/web", "/integration/feishu"].includes(request.url ?? "") && this.integrations) {
93
+ const kind = request.url === "/integration/web" ? "web" : "feishu";
94
+ const controller = new AbortController();
95
+ response.once("close", () => { if (!response.writableEnded)
96
+ controller.abort(); });
97
+ void (async () => {
98
+ try {
99
+ if (request.method !== "POST" || !this.integrations.available()[kind]) {
100
+ response.writeHead(503).end();
101
+ return;
102
+ }
103
+ const parts = [];
104
+ let size = 0;
105
+ for await (const part of request) {
106
+ size += part.length;
107
+ if (size > 4 * 1024 * 1024) {
108
+ response.writeHead(413).end();
109
+ return;
110
+ }
111
+ parts.push(part);
112
+ }
113
+ const body = JSON.parse(Buffer.concat(parts).toString("utf8"));
114
+ if (!body || typeof body !== "object" || Array.isArray(body))
115
+ throw new Error("入口服务请求格式无效");
116
+ const result = await this.integrations.invoke(kind, body, controller.signal);
117
+ response.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(result));
118
+ }
119
+ catch (cause) {
120
+ if (!response.headersSent)
121
+ response.writeHead(400, { "content-type": "application/json" }).end(JSON.stringify({ error: cause instanceof Error ? cause.message : "入口服务调用失败" }));
122
+ }
123
+ })();
124
+ return;
125
+ }
126
+ if (request.url !== "/model") {
83
127
  response.writeHead(403).end();
84
128
  return;
85
129
  }
@@ -180,6 +224,7 @@ export class ManagedServers {
180
224
  profile.serviceError = undefined;
181
225
  profile.sshError = undefined;
182
226
  profile.modelError = undefined;
227
+ this.relays.get(id)?.terminate();
183
228
  this.clients.get(id)?.end();
184
229
  this.clients.delete(id);
185
230
  await this.vault.write(id, secret);
@@ -323,6 +368,8 @@ export class ManagedServers {
323
368
  entry.profile.modelChannel = "online";
324
369
  }
325
370
  async restoreModelChannel(entry, client) {
371
+ if (this.relays.has(entry.profile.id))
372
+ return;
326
373
  if (entry.profile.modelChannelPaused)
327
374
  return;
328
375
  try {
@@ -347,10 +394,31 @@ export class ManagedServers {
347
394
  }
348
395
  async syncModels(id, force = false, reload = true) {
349
396
  const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
350
- if (!entry.installation || !entry.reversePort || !client || !secret)
397
+ const relay = this.relays.get(id);
398
+ if (reload && entry.profile.modelTransport === "direct" && relay?.readyState !== WebSocket.OPEN)
399
+ throw new Error("服务端口的模型通道正在连接,请稍后重试");
400
+ if (reload && entry.installation && secret && relay?.readyState === WebSocket.OPEN && entry.profile.serviceUrl) {
401
+ const body = JSON.stringify({ models: await this.gateway.catalog(force), defaultModel: this.defaultModel(), entryIntegrations: this.integrations?.available() });
402
+ const hash = createHash("sha256").update(body).digest("hex");
403
+ if (!force && this.syncedRelays.get(relay) === hash)
404
+ return;
405
+ 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) });
406
+ if (!res.ok)
407
+ throw new Error(`通过服务端口同步模型目录失败(HTTP ${res.status})`);
408
+ await res.arrayBuffer();
409
+ if (this.relays.get(id) === relay) {
410
+ this.syncedRelays.set(relay, hash);
411
+ entry.profile.modelChannel = "online";
412
+ delete entry.profile.modelError;
413
+ }
414
+ return;
415
+ }
416
+ const directBootstrap = !reload && entry.profile.modelTransport === "direct";
417
+ if (!entry.installation || (!entry.reversePort && !directBootstrap) || !client || !secret)
351
418
  throw new Error("请先部署并连接此服务器");
352
419
  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() });
420
+ const endpoint = directBootstrap ? `http://127.0.0.1:${entry.profile.servicePort}/api/managed-model/invoke` : `http://127.0.0.1:${entry.reversePort}/model`;
421
+ const content = JSON.stringify({ endpoint, token: secret.modelToken, models, defaultModel: this.defaultModel() });
354
422
  const hash = createHash("sha256").update(content).digest("hex");
355
423
  if (hash === entry.modelHash)
356
424
  return;
@@ -427,6 +495,34 @@ export class ManagedServers {
427
495
  profile.transport = "direct";
428
496
  profile.service = "online";
429
497
  delete profile.serviceError;
498
+ if (entry.installation && health.modelRelay === true && !this.stopped) {
499
+ profile.modelTransport = "direct";
500
+ delete profile.modelChannelPaused;
501
+ let relay = this.relays.get(id);
502
+ if (!relay) {
503
+ profile.modelChannel = "offline";
504
+ relay = connectModelRelay(profile.serviceUrl, key, this.gatewayPort, secret.modelToken);
505
+ this.relays.set(id, relay);
506
+ const current = relay;
507
+ relay.once("close", () => {
508
+ this.syncedRelays.delete(current);
509
+ if (this.relays.get(id) !== current)
510
+ return;
511
+ this.relays.delete(id);
512
+ profile.modelChannel = "offline";
513
+ });
514
+ relay.once("open", () => { void this.syncModels(id).catch(error => { profile.modelError = String(error.message); }); });
515
+ }
516
+ else if (relay.readyState === WebSocket.OPEN) {
517
+ await this.syncModels(id).catch(error => { profile.modelError = String(error.message); });
518
+ if (this.syncedRelays.has(relay))
519
+ profile.modelChannel = "online";
520
+ }
521
+ }
522
+ else {
523
+ delete profile.modelTransport;
524
+ this.relays.get(id)?.terminate();
525
+ }
430
526
  if (!this.jobs.has(id) && !this.connecting.has(id))
431
527
  profile.phase = "ready";
432
528
  return true;
@@ -434,6 +530,8 @@ export class ManagedServers {
434
530
  catch (error) {
435
531
  if (!profile.enabled || this.records.get(id) !== entry)
436
532
  return false;
533
+ if (!this.relays.has(id) && profile.allowServiceTunnel)
534
+ delete profile.modelTransport;
437
535
  if (profile.transport === "ssh" && profile.allowServiceTunnel && this.clients.has(id))
438
536
  return false;
439
537
  profile.serviceError = error instanceof Error && error.message !== "fetch failed" ? error.message : "直连服务端口不可达,请检查 IP、端口和服务监听地址。";
@@ -601,14 +699,45 @@ export class ManagedServers {
601
699
  if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
602
700
  throw new Error("远端仍有进行中的任务,请完成后再重新部署");
603
701
  }
604
- const installation = await installRemote({ client, id, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
702
+ let installation = entry.installation;
703
+ let reusable = false;
704
+ if (installation && installation.archiveHash && installation.archiveHash === artifact.shasum) {
705
+ try {
706
+ const files = [posix.join(installation.packageRoot, "dist/server/index.js"), posix.join(installation.packageRoot, "dist/client/index.html"), posix.join(installation.packageRoot, "agents/super-pi-managed-model/index.ts"), installation.piCommand];
707
+ const probe = `import{readFileSync,accessSync}from'node:fs';import{fileURLToPath}from'node:url';const[v,m]=process.versions.node.split('.').map(Number);if(!(v>22||(v===22&&m>=19)))throw Error('Unsupported Node runtime');const pkg=JSON.parse(readFileSync(${JSON.stringify(posix.join(installation.packageRoot, "package.json"))},'utf8'));if(pkg.name!=='@evandu/super-pi-server'||pkg.version!==${JSON.stringify(artifact.version)})throw Error('Unexpected installation');for(const file of ${JSON.stringify(files)})accessSync(file);accessSync(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent')));`;
708
+ await sshExec(client, `cd ${sh(installation.packageRoot)} && ${sh(installation.node)} --input-type=module -e ${sh(probe)}`);
709
+ reusable = true;
710
+ this.progress(entry, "复用已完成的同版本远端安装");
711
+ }
712
+ catch {
713
+ delete installation.archiveHash;
714
+ this.progress(entry, "已有安装不完整,正在修复");
715
+ await this.persist();
716
+ }
717
+ }
718
+ if (!reusable)
719
+ installation = await installRemote({ client, id, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
720
+ if (!installation)
721
+ throw new Error("远端安装未完成");
605
722
  entry.installation = installation;
606
723
  entry.profile.remoteRoot = installation.root;
607
724
  entry.profile.identity ??= randomUUID();
608
725
  const secret = this.secrets.get(id);
609
726
  await sshWrite(client, posix.join(installation.root, "data", "browser-access.json"), JSON.stringify({ id: entry.profile.identity, key: secret.browserKey }));
610
727
  this.progress(entry, "建立模型通道并同步本地模型目录");
611
- await this.reverseModelChannel(entry, client);
728
+ 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";
729
+ this.relays.get(id)?.terminate();
730
+ this.relays.delete(id);
731
+ if (directBootstrap) {
732
+ entry.profile.modelChannel = "offline";
733
+ entry.profile.modelTransport = "direct";
734
+ }
735
+ else {
736
+ if (entry.profile.modelTransport === "direct")
737
+ entry.profile.modelChannel = "offline";
738
+ delete entry.profile.modelTransport;
739
+ await this.reverseModelChannel(entry, client);
740
+ }
612
741
  entry.modelHash = undefined;
613
742
  await this.syncModels(id, false, false);
614
743
  this.progress(entry, "启动远端 Super Pi 服务");
@@ -697,6 +826,8 @@ export class ManagedServers {
697
826
  }
698
827
  async action(id, action) {
699
828
  const entry = this.entry(id);
829
+ if (action === "disconnect" || action === "remove")
830
+ this.relays.get(id)?.terminate();
700
831
  if (action === "disconnect") {
701
832
  entry.profile.enabled = false;
702
833
  await this.cancelConnection(id);
@@ -792,7 +923,7 @@ export class ManagedServers {
792
923
  return;
793
924
  const client = this.clients.get(entry.profile.id);
794
925
  if (await this.checkDirect(entry.profile.id)) {
795
- if (entry.installation && !entry.profile.modelChannelPaused) {
926
+ if (entry.installation && entry.profile.modelTransport !== "direct" && !entry.profile.modelChannelPaused) {
796
927
  if (client)
797
928
  await this.restoreModelChannel(entry, client);
798
929
  else if (!this.connecting.has(entry.profile.id) && !this.authBlocked.has(entry.profile.id) && entry.profile.fingerprint && entry.profile.ssh !== "needsTrust")
@@ -876,7 +1007,8 @@ export class ManagedServers {
876
1007
  await proxyWebSocketThroughSsh(tunnel, entry.profile.servicePort, key, path, request, socket, head, Boolean(entry.compatibility));
877
1008
  }
878
1009
  }
879
- async close() { this.stopped = true; clearInterval(this.timer); for (const id of [...this.pendingConnections.keys()])
1010
+ async close() { this.stopped = true; clearInterval(this.timer); for (const relay of this.relays.values())
1011
+ relay.terminate(); for (const id of [...this.pendingConnections.keys()])
880
1012
  await this.cancelConnection(id, "本地管理服务已停止"); for (const client of this.clients.values())
881
1013
  client.end(); this.clients.clear(); this.gatewayServer?.closeAllConnections(); await new Promise(resolve => this.gatewayServer ? this.gatewayServer.close(() => resolve()) : resolve()); await this.persistence; }
882
1014
  }
@@ -5,8 +5,18 @@ export interface RemoteInstallation {
5
5
  packageRoot: string;
6
6
  node: string;
7
7
  piCommand: string;
8
+ archiveHash?: string;
8
9
  }
9
10
  export declare function uploadFile(client: Client, local: string, remote: string): Promise<void>;
11
+ interface NodeDownloadOptions {
12
+ fetch?: typeof fetch;
13
+ fallbackDelayMs?: number;
14
+ progress?: (step: string) => void;
15
+ }
16
+ export declare const NODE_RUNTIME_VERSION = "v22.20.0";
17
+ export declare const NODE_RUNTIME_CHECKSUMS: Readonly<Record<string, string>>;
18
+ export declare function nodeArchive(platform: string, arch: string, directory: string, options?: NodeDownloadOptions): Promise<string>;
19
+ export declare function downloadVerifiedNodeArchive(filename: string, expected: string, directory: string, options?: NodeDownloadOptions): Promise<string>;
10
20
  export declare function installRemote(options: {
11
21
  client: Client;
12
22
  id: string;
@@ -17,3 +27,4 @@ export declare function installRemote(options: {
17
27
  }): Promise<RemoteInstallation>;
18
28
  export declare function remoteStartScript(installation: RemoteInstallation, port: number, host?: ServiceListenHost): string;
19
29
  export declare function startRemote(client: Client, installation: RemoteInstallation, port: number, host?: ServiceListenHost): Promise<void>;
30
+ export {};