@evandu/super-pi 0.1.290 → 0.1.292
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/.super-pi-check-inputs.json +4 -0
- package/dist/client/.super-pi-client-sources.json +5 -4
- package/dist/client/assets/{CodeMirrorEditor-CC6Mf3yd.js → CodeMirrorEditor-BItIClMY.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-AhSKDGru.js → GitDiffEditor-CgWWgUsi.js} +1 -1
- package/dist/client/assets/index-C3aSjjM8.css +1 -0
- package/dist/client/assets/{index-D-sud3i3.js → index-Cwt3-oUx.js} +6 -6
- package/dist/client/index.html +2 -2
- package/dist/server/managed-http.js +1 -1
- package/dist/server/managed-recovery.d.ts +10 -0
- package/dist/server/managed-recovery.js +113 -0
- package/dist/server/managed-servers.d.ts +10 -2
- package/dist/server/managed-servers.js +134 -9
- package/dist/server/remote-bootstrap.d.ts +3 -0
- package/dist/server/remote-bootstrap.js +11 -1
- package/dist/shared/managed-servers.d.ts +16 -0
- package/package.json +3 -1
- package/dist/client/assets/index-dkbN-Swt.css +0 -1
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,9 @@
|
|
|
8
8
|
<link rel="alternate icon" href="/favicon.ico" />
|
|
9
9
|
<link rel="apple-touch-icon" href="/favicon.svg" />
|
|
10
10
|
<title>Super Pi</title>
|
|
11
|
-
<script type="module" crossorigin src="/assets/index-
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-Cwt3-oUx.js"></script>
|
|
12
12
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-XKyaHtl9.js">
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-C3aSjjM8.css">
|
|
14
14
|
</head>
|
|
15
15
|
<body>
|
|
16
16
|
<div id="root"></div>
|
|
@@ -133,7 +133,7 @@ export async function handleManagedHttp(context, request, response, url) {
|
|
|
133
133
|
else {
|
|
134
134
|
if (typeof body.id !== "string")
|
|
135
135
|
throw new Error("请选择服务器");
|
|
136
|
-
await context.managedServers.action(body.id, body.action);
|
|
136
|
+
await context.managedServers.action(body.id, body.action, body.instanceId);
|
|
137
137
|
}
|
|
138
138
|
json(200, status());
|
|
139
139
|
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Client } from "ssh2";
|
|
2
|
+
import type { RemoteInstallation } from "./remote-bootstrap.js";
|
|
3
|
+
import type { RecoverableManagedInstance } from "../shared/managed-servers.js";
|
|
4
|
+
export type ManagedRecoveryCandidate = RecoverableManagedInstance & {
|
|
5
|
+
installation?: RemoteInstallation;
|
|
6
|
+
identity?: string;
|
|
7
|
+
};
|
|
8
|
+
export declare function managedRecoveryProbeScript(): string;
|
|
9
|
+
export declare function discoverManagedInstallations(client: Client): Promise<ManagedRecoveryCandidate[]>;
|
|
10
|
+
export declare function recoverySummary(value: ManagedRecoveryCandidate): RecoverableManagedInstance;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { sh, sshExec } from "./managed-ssh.js";
|
|
3
|
+
/** Runs remotely using Node, and only reads instance metadata and history counts. */
|
|
4
|
+
function recoveryProbe() {
|
|
5
|
+
const fs = require("node:fs"), path = require("node:path"), os = require("node:os");
|
|
6
|
+
const base = path.join(os.homedir(), ".super-pi", "managed");
|
|
7
|
+
const read = (file) => { try {
|
|
8
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
} };
|
|
13
|
+
const regular = (file) => { try {
|
|
14
|
+
const stat = fs.lstatSync(file);
|
|
15
|
+
return stat.isFile() && !stat.isSymbolicLink();
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return false;
|
|
19
|
+
} };
|
|
20
|
+
const result = [];
|
|
21
|
+
let directories = [];
|
|
22
|
+
try {
|
|
23
|
+
directories = fs.readdirSync(base);
|
|
24
|
+
}
|
|
25
|
+
catch { /* A first installation has no managed directory. */ }
|
|
26
|
+
for (const id of directories) {
|
|
27
|
+
if (!/^[a-zA-Z0-9_-]{1,128}$/.test(id))
|
|
28
|
+
continue;
|
|
29
|
+
const root = path.join(base, id), dataDirectory = path.join(root, "data");
|
|
30
|
+
try {
|
|
31
|
+
if (!fs.lstatSync(root).isDirectory() || fs.lstatSync(root).isSymbolicLink() || fs.lstatSync(dataDirectory).isSymbolicLink())
|
|
32
|
+
continue;
|
|
33
|
+
const descriptor = read(path.join(root, "instance.json"));
|
|
34
|
+
let launcher = "";
|
|
35
|
+
try {
|
|
36
|
+
launcher = fs.readFileSync(path.join(root, "start-service.sh"), "utf8");
|
|
37
|
+
}
|
|
38
|
+
catch { /* Metadata can survive missing runtime files. */ }
|
|
39
|
+
const port = descriptor?.port ?? Number(launcher.match(/^export SUPER_PI_PORT=(\d+)$/m)?.[1]);
|
|
40
|
+
const host = descriptor?.host ?? launcher.match(/^export SUPER_PI_HOST='(127\.0\.0\.1|0\.0\.0\.0|::)'$/m)?.[1];
|
|
41
|
+
const stateFile = path.join(dataDirectory, "state.json"), hasData = regular(stateFile);
|
|
42
|
+
const stat = hasData ? fs.statSync(stateFile) : fs.statSync(dataDirectory);
|
|
43
|
+
const state = hasData && stat.size <= 32 * 1024 * 1024 ? read(stateFile) : undefined;
|
|
44
|
+
const access = read(path.join(dataDirectory, "browser-access.json"));
|
|
45
|
+
const modified = (name) => { try {
|
|
46
|
+
return fs.statSync(path.join(root, name)).mtimeMs;
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return 0;
|
|
50
|
+
} };
|
|
51
|
+
const runtimeRoots = fs.readdirSync(root).filter((name) => /^runtime-[a-zA-Z0-9_-]+$/.test(name))
|
|
52
|
+
.sort((a, b) => modified(b) - modified(a));
|
|
53
|
+
let installation, version;
|
|
54
|
+
for (const runtime of runtimeRoots) {
|
|
55
|
+
const packageRoot = path.join(root, runtime, "node_modules", "@evandu", "super-pi-server");
|
|
56
|
+
const pkg = read(path.join(packageRoot, "package.json"));
|
|
57
|
+
if (pkg?.name !== "@evandu/super-pi-server" || !regular(path.join(packageRoot, "dist", "server", "index.js")))
|
|
58
|
+
continue;
|
|
59
|
+
if (!fs.realpathSync(packageRoot).startsWith(fs.realpathSync(root) + path.sep))
|
|
60
|
+
continue;
|
|
61
|
+
version = String(pkg.version);
|
|
62
|
+
const privateNode = path.join(root, "node", "bin", "node");
|
|
63
|
+
const launchNode = launcher.match(/^nohup '([^'\r\n]+)' /m)?.[1];
|
|
64
|
+
const node = regular(privateNode) ? privateNode : launchNode && regular(launchNode) ? launchNode : process.execPath;
|
|
65
|
+
installation = { root, packageRoot, node, piCommand: path.join(root, "pi-managed") };
|
|
66
|
+
break;
|
|
67
|
+
}
|
|
68
|
+
if (!hasData && !installation)
|
|
69
|
+
continue;
|
|
70
|
+
result.push({ id, root, dataDirectory, hasData, canRestart: Boolean(installation), version,
|
|
71
|
+
port: Number.isInteger(port) && port > 0 && port < 65536 ? port : undefined,
|
|
72
|
+
host: ["0.0.0.0", "127.0.0.1", "::"].includes(host) ? host : undefined,
|
|
73
|
+
conversationCount: Array.isArray(state?.conversations) ? state.conversations.length : undefined,
|
|
74
|
+
workspaceCount: Array.isArray(state?.workspaces) ? state.workspaces.length : undefined,
|
|
75
|
+
modifiedAt: stat.mtime.toISOString(), installation,
|
|
76
|
+
identity: typeof access?.id === "string" ? access.id : undefined });
|
|
77
|
+
}
|
|
78
|
+
catch { /* A broken directory must not hide the other recoverable instances. */ }
|
|
79
|
+
}
|
|
80
|
+
process.stdout.write(JSON.stringify(result));
|
|
81
|
+
}
|
|
82
|
+
export function managedRecoveryProbeScript() { return `(${recoveryProbe.toString()})()`; }
|
|
83
|
+
export async function discoverManagedInstallations(client) {
|
|
84
|
+
const script = managedRecoveryProbeScript();
|
|
85
|
+
const command = `if [ ! -d "$HOME/.super-pi/managed" ]; then printf '[]'; exit; fi; for candidate in "$(command -v node 2>/dev/null || true)" "$HOME"/.super-pi/managed/*/node/bin/node /opt/homebrew/bin/node /usr/local/bin/node "$HOME"/.nvm/versions/node/*/bin/node; do if [ -n "$candidate" ] && [ -x "$candidate" ]; then if "$candidate" -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 16 ? 0 : 1)' >/dev/null 2>&1; then "$candidate" -e ${sh(script)}; exit; fi; fi; done; for state in "$HOME"/.super-pi/managed/*/data/state.json; do if [ -f "$state" ]; then echo 'Cannot inspect existing managed data without Node.js' >&2; exit 1; fi; done; printf '[]'`;
|
|
86
|
+
const text = (await sshExec(client, command, { timeout: 15_000 })).trim();
|
|
87
|
+
if (!text)
|
|
88
|
+
throw new Error("未能读取远端托管实例目录;请检查 SSH 的 Node.js 环境,未创建新实例。");
|
|
89
|
+
let values;
|
|
90
|
+
try {
|
|
91
|
+
values = JSON.parse(text);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
throw new Error("远端实例探测未返回有效结果,未创建新实例。");
|
|
95
|
+
}
|
|
96
|
+
if (!Array.isArray(values))
|
|
97
|
+
throw new Error("远端实例探测结果无效,未创建新实例。");
|
|
98
|
+
const home = (await sshExec(client, "printf '%s' \"$HOME\"")).trim();
|
|
99
|
+
if (!home.startsWith("/") || /[\r\n\0]/.test(home))
|
|
100
|
+
throw new Error("未能确认 SSH 用户的数据目录,已停止恢复。");
|
|
101
|
+
return values.filter((value) => value && typeof value.id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(value.id)
|
|
102
|
+
&& typeof value.root === "string" && value.root === posix.join(home, ".super-pi", "managed", value.id)
|
|
103
|
+
&& !/[\r\n\0]/.test(value.root) && value.dataDirectory === `${value.root}/data`
|
|
104
|
+
&& (!value.installation || (value.installation.root === value.root && value.installation.piCommand === `${value.root}/pi-managed`
|
|
105
|
+
&& typeof value.installation.node === "string" && value.installation.node.startsWith("/") && !/[\r\n\0]/.test(value.installation.node)
|
|
106
|
+
&& typeof value.installation.packageRoot === "string" && value.installation.packageRoot === posix.normalize(value.installation.packageRoot)
|
|
107
|
+
&& /^runtime-[a-zA-Z0-9_-]+\/node_modules\/@evandu\/super-pi-server$/.test(posix.relative(value.root, value.installation.packageRoot)))));
|
|
108
|
+
}
|
|
109
|
+
export function recoverySummary(value) {
|
|
110
|
+
return { id: value.id, root: value.root, dataDirectory: value.dataDirectory, hasData: value.hasData, canRestart: value.canRestart,
|
|
111
|
+
version: value.version, port: value.port, host: value.host, conversationCount: value.conversationCount,
|
|
112
|
+
workspaceCount: value.workspaceCount, modifiedAt: value.modifiedAt };
|
|
113
|
+
}
|
|
@@ -82,6 +82,9 @@ export declare class ManagedServers {
|
|
|
82
82
|
error?: string;
|
|
83
83
|
log?: string[];
|
|
84
84
|
updateOperation?: import("../shared/update-status.js").UpdateOperation;
|
|
85
|
+
recoverableInstances?: import("../shared/managed-servers.js").RecoverableManagedInstance[];
|
|
86
|
+
maintenance?: "scan" | "restart" | "repair" | "recover";
|
|
87
|
+
canRestart: boolean;
|
|
85
88
|
verification: SshVerification | undefined;
|
|
86
89
|
}[];
|
|
87
90
|
probeService(input: Partial<ManagedServerInput>): Promise<import("../shared/managed-servers.js").ServiceProbe>;
|
|
@@ -107,7 +110,12 @@ export declare class ManagedServers {
|
|
|
107
110
|
private ensureService;
|
|
108
111
|
private progress;
|
|
109
112
|
preparePackage(): Promise<any>;
|
|
110
|
-
|
|
113
|
+
private maintenance;
|
|
114
|
+
deploy(id: string, updateVersion?: string, recovery?: {
|
|
115
|
+
instanceId?: string;
|
|
116
|
+
repair?: boolean;
|
|
117
|
+
newInstance?: boolean;
|
|
118
|
+
}): ManagedServerProfile;
|
|
111
119
|
updateSelected(updates: {
|
|
112
120
|
id: string;
|
|
113
121
|
version: string;
|
|
@@ -117,7 +125,7 @@ export declare class ManagedServers {
|
|
|
117
125
|
};
|
|
118
126
|
waitForUpdates(ids: string[]): Promise<void>;
|
|
119
127
|
applyListener(id: string, host: unknown): Promise<ManagedServerProfile>;
|
|
120
|
-
action(id: string, action: string): Promise<ManagedServerProfile | undefined>;
|
|
128
|
+
action(id: string, action: string, instanceId?: string): Promise<ManagedServerProfile | undefined>;
|
|
121
129
|
private maintain;
|
|
122
130
|
connectionProfiles(): {
|
|
123
131
|
id: string;
|
|
@@ -10,7 +10,8 @@ import { WebSocket } from "ws";
|
|
|
10
10
|
import { connectModelRelay } from "./managed-model-relay.js";
|
|
11
11
|
import { connectSsh, HostTrustRequired, sshWrite, sshExec, sh } from "./managed-ssh.js";
|
|
12
12
|
import { proxyThroughSsh, proxyWebSocketThroughSsh, tunnelJson } from "./managed-http-tunnel.js";
|
|
13
|
-
import { installRemote, startRemote } from "./remote-bootstrap.js";
|
|
13
|
+
import { installRemote, startRemote, stopRemote } from "./remote-bootstrap.js";
|
|
14
|
+
import { discoverManagedInstallations, recoverySummary } from "./managed-recovery.js";
|
|
14
15
|
import { isServiceListenHost } from "../shared/managed-servers.js";
|
|
15
16
|
import { discoverExistingInstallation } from "./existing-service.js";
|
|
16
17
|
import { publishedServerUpdate } from "./published-server-update.js";
|
|
@@ -56,7 +57,8 @@ export class ManagedServers {
|
|
|
56
57
|
if (!/^[a-f0-9-]+$/.test(entry.profile?.id))
|
|
57
58
|
continue;
|
|
58
59
|
entry.profile.serviceUrl ??= defaultServiceOrigin(entry.profile.host, entry.profile.servicePort);
|
|
59
|
-
|
|
60
|
+
const maintenanceInterrupted = Boolean(entry.profile.maintenance);
|
|
61
|
+
entry.profile = { ...entry.profile, maintenance: undefined, ssh: "offline", service: "unknown", modelChannel: "offline", transport: undefined, serviceError: undefined, sshError: undefined, modelError: undefined, phase: maintenanceInterrupted || entry.profile.phase === "deploying" ? "failed" : "idle", error: maintenanceInterrupted ? "本地入口在维护期间重启,请重新检查实例状态后重试。" : entry.profile.phase === "deploying" ? "本地管理服务在部署期间重启,请检查后重试部署" : undefined };
|
|
60
62
|
if (entry.profile.updateOperation && ["waiting", "installing", "restarting"].includes(entry.profile.updateOperation.phase)) {
|
|
61
63
|
const operation = entry.profile.updateOperation;
|
|
62
64
|
operation.failure = { step: operation.phase === "restarting" ? "restarting" : "installing", message: "本地管理服务在远端更新期间退出,请检测远端版本后重试。" };
|
|
@@ -135,7 +137,7 @@ export class ManagedServers {
|
|
|
135
137
|
this.timer.unref();
|
|
136
138
|
void this.maintain();
|
|
137
139
|
}
|
|
138
|
-
list() { return [...this.records.values()].map(entry => structuredClone({ ...entry.profile, verification: this.verifications.get(entry.profile.id)?.challenge })); }
|
|
140
|
+
list() { return [...this.records.values()].map(entry => structuredClone({ ...entry.profile, canRestart: Boolean(entry.installation), verification: this.verifications.get(entry.profile.id)?.challenge })); }
|
|
139
141
|
async probeService(input) {
|
|
140
142
|
const stored = input.id ? this.entry(input.id) : undefined;
|
|
141
143
|
const host = input.host ?? stored?.profile.host, port = input.servicePort ?? stored?.profile.servicePort;
|
|
@@ -311,7 +313,7 @@ export class ManagedServers {
|
|
|
311
313
|
delete profile.transport;
|
|
312
314
|
} profile.modelChannel = "offline"; if (profile.phase !== "deploying")
|
|
313
315
|
profile.phase = profile.service === "online" ? "ready" : "idle"; void this.checkDirect(id); void this.persist(); });
|
|
314
|
-
if (entry.installation) {
|
|
316
|
+
if (entry.installation && !profile.maintenance) {
|
|
315
317
|
try {
|
|
316
318
|
await this.ensureService(id);
|
|
317
319
|
}
|
|
@@ -321,7 +323,7 @@ export class ManagedServers {
|
|
|
321
323
|
}
|
|
322
324
|
await this.restoreModelChannel(entry, client);
|
|
323
325
|
}
|
|
324
|
-
else {
|
|
326
|
+
else if (!entry.installation) {
|
|
325
327
|
if (!(await this.checkDirect(id)))
|
|
326
328
|
await this.detectExisting(id);
|
|
327
329
|
profile.phase = profile.existingService?.attached ? "ready" : "idle";
|
|
@@ -660,12 +662,66 @@ export class ManagedServers {
|
|
|
660
662
|
preparePackage() {
|
|
661
663
|
return this.artifact ??= import(pathToFileURL(join(this.packageRoot, "scripts", "pack-server.mjs")).href).then(module => module.packServer(this.packageRoot, join(this.directory, "packages"))).catch(error => { this.artifact = undefined; throw error; });
|
|
662
664
|
}
|
|
663
|
-
|
|
665
|
+
maintenance(id, kind) {
|
|
666
|
+
const entry = this.entry(id), profile = entry.profile;
|
|
667
|
+
if (this.jobs.has(id))
|
|
668
|
+
throw new Error("此服务器已有操作进行中");
|
|
669
|
+
if (!profile.fingerprint)
|
|
670
|
+
throw new Error("请先连接 SSH 并确认主机指纹");
|
|
671
|
+
if (kind === "restart" && !entry.installation)
|
|
672
|
+
throw new Error("尚未绑定托管实例,请先查找并接管原实例。");
|
|
673
|
+
profile.enabled = true;
|
|
674
|
+
profile.phase = "deploying";
|
|
675
|
+
profile.maintenance = kind;
|
|
676
|
+
delete profile.error;
|
|
677
|
+
const job = (async () => {
|
|
678
|
+
try {
|
|
679
|
+
this.progress(entry, kind === "scan" ? "通过 SSH 查找历史托管实例" : "通过 SSH 重启原实例,保留数据和会话");
|
|
680
|
+
const client = await this.connect(id);
|
|
681
|
+
profile.phase = "deploying";
|
|
682
|
+
if (kind === "scan") {
|
|
683
|
+
const values = await discoverManagedInstallations(client);
|
|
684
|
+
profile.recoverableInstances = values.filter(value => value.root !== entry.installation?.root).map(recoverySummary);
|
|
685
|
+
profile.phase = profile.service === "online" ? "ready" : "idle";
|
|
686
|
+
this.progress(entry, `已找到 ${profile.recoverableInstances.length} 个其他托管实例;未修改远端数据`);
|
|
687
|
+
}
|
|
688
|
+
else {
|
|
689
|
+
await stopRemote(client, entry.installation);
|
|
690
|
+
await startRemote(client, entry.installation, profile.servicePort, profile.deployedServiceHost ?? profile.serviceHost ?? "0.0.0.0");
|
|
691
|
+
for (let attempt = 0; attempt < 10; attempt++) {
|
|
692
|
+
await this.health(id);
|
|
693
|
+
if (profile.service === "online")
|
|
694
|
+
break;
|
|
695
|
+
await new Promise(done => setTimeout(done, 1000));
|
|
696
|
+
}
|
|
697
|
+
if (profile.service !== "online")
|
|
698
|
+
throw new Error("已通过 SSH 执行重启,但服务端口仍不可达。请查看服务日志与端口监听;可继续使用修复部署,原数据未删除。");
|
|
699
|
+
profile.phase = "ready";
|
|
700
|
+
this.progress(entry, "原实例已重启,数据和会话保持原样");
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
catch (cause) {
|
|
704
|
+
profile.phase = profile.ssh === "needsTrust" ? "needsTrust" : "failed";
|
|
705
|
+
profile.error = cause instanceof Error ? cause.message : "SSH 维护未完成";
|
|
706
|
+
}
|
|
707
|
+
finally {
|
|
708
|
+
delete profile.maintenance;
|
|
709
|
+
this.jobs.delete(id);
|
|
710
|
+
await this.persist();
|
|
711
|
+
}
|
|
712
|
+
})();
|
|
713
|
+
this.jobs.set(id, job);
|
|
714
|
+
void this.persist();
|
|
715
|
+
return profile;
|
|
716
|
+
}
|
|
717
|
+
deploy(id, updateVersion, recovery) {
|
|
664
718
|
const entry = this.entry(id);
|
|
665
719
|
if (this.jobs.has(id))
|
|
666
720
|
throw new Error("此服务器已有部署进行中");
|
|
667
721
|
if (!entry.profile.fingerprint)
|
|
668
722
|
throw new Error("请先测试 SSH 并确认主机指纹");
|
|
723
|
+
if (recovery?.newInstance && (entry.installation || entry.recoveryRoot))
|
|
724
|
+
throw new Error("已绑定的实例不能作为空实例重建;请使用修复部署以保留原数据。");
|
|
669
725
|
if (entry.profile.serviceHost === "127.0.0.1" && !entry.profile.allowServiceTunnel)
|
|
670
726
|
throw new Error("仅本机回环部署需要先启用 SSH 隧道访问,或选择可直连的监听方式。");
|
|
671
727
|
if (updateVersion) {
|
|
@@ -678,13 +734,57 @@ export class ManagedServers {
|
|
|
678
734
|
const at = new Date().toISOString();
|
|
679
735
|
entry.profile.updateOperation = { id: randomUUID(), action: "update", phase: "installing", fromVersion: "", targetVersion: updateVersion, startedAt: at, changedAt: at };
|
|
680
736
|
}
|
|
737
|
+
entry.profile.enabled = true;
|
|
681
738
|
entry.profile.phase = "deploying";
|
|
682
739
|
entry.profile.log = [];
|
|
683
740
|
delete entry.profile.error;
|
|
741
|
+
if (recovery?.instanceId)
|
|
742
|
+
entry.profile.maintenance = "recover";
|
|
743
|
+
else if (recovery?.repair)
|
|
744
|
+
entry.profile.maintenance = "repair";
|
|
684
745
|
const job = (async () => {
|
|
685
746
|
try {
|
|
686
747
|
const client = await this.connect(id);
|
|
687
748
|
entry.profile.phase = "deploying";
|
|
749
|
+
if (recovery?.instanceId) {
|
|
750
|
+
const values = await discoverManagedInstallations(client);
|
|
751
|
+
const selected = values.find(value => value.id === recovery.instanceId);
|
|
752
|
+
if (!selected?.hasData)
|
|
753
|
+
throw new Error("未能重新确认所选旧实例及数据目录,未创建新实例或删除任何数据。");
|
|
754
|
+
if (entry.compatibility && entry.profile.service === "online")
|
|
755
|
+
throw new Error("当前连接是正在运行的原有服务,请使用独立连接接管旧托管实例,避免中断未知启动方式。");
|
|
756
|
+
if (entry.installation && entry.installation.root !== selected.root) {
|
|
757
|
+
await this.health(id);
|
|
758
|
+
if (entry.profile.service === "online") {
|
|
759
|
+
const state = await this.serviceJson(entry, "/api/conversations");
|
|
760
|
+
if ((state.conversations ?? []).some((conversation) => ["running", "waiting", "awaiting_background"].includes(conversation.status)))
|
|
761
|
+
throw new Error("远端仍有进行中的任务,请完成后再重新接管");
|
|
762
|
+
}
|
|
763
|
+
await stopRemote(client, entry.installation);
|
|
764
|
+
}
|
|
765
|
+
const previousRelay = this.relays.get(id);
|
|
766
|
+
this.relays.delete(id);
|
|
767
|
+
previousRelay?.terminate();
|
|
768
|
+
this.closeServiceTunnel(id);
|
|
769
|
+
entry.profile.service = "unknown";
|
|
770
|
+
entry.profile.modelChannel = "offline";
|
|
771
|
+
delete entry.profile.transport;
|
|
772
|
+
delete entry.profile.modelTransport;
|
|
773
|
+
delete entry.profile.serviceError;
|
|
774
|
+
delete entry.profile.modelError;
|
|
775
|
+
entry.modelHash = undefined;
|
|
776
|
+
entry.recoveryRoot = selected.root;
|
|
777
|
+
entry.installation = selected.installation;
|
|
778
|
+
entry.instanceId = selected.id;
|
|
779
|
+
entry.profile.remoteRoot = selected.root;
|
|
780
|
+
entry.profile.identity = selected.identity ?? entry.profile.identity;
|
|
781
|
+
entry.compatibility = false;
|
|
782
|
+
delete entry.existingInstallation;
|
|
783
|
+
delete entry.profile.existingService;
|
|
784
|
+
entry.profile.recoverableInstances = values.filter(value => value.root !== selected.root).map(recoverySummary);
|
|
785
|
+
await this.persist();
|
|
786
|
+
this.progress(entry, "已确认原数据目录,正在重新绑定入口并修复原实例");
|
|
787
|
+
}
|
|
688
788
|
if (entry.profile.existingService?.running && entry.compatibility) {
|
|
689
789
|
entry.profile.phase = "ready";
|
|
690
790
|
this.progress(entry, "已接入已有服务,原端口、工作区、会话和模型配置保持可用");
|
|
@@ -692,6 +792,12 @@ export class ManagedServers {
|
|
|
692
792
|
}
|
|
693
793
|
if (entry.existingInstallation)
|
|
694
794
|
throw new Error("检测到原有 Super Pi 安装,请先启动并接入已有服务,不会另建空实例覆盖原来的工作区和会话");
|
|
795
|
+
if (!entry.installation && !entry.recoveryRoot && !recovery?.newInstance) {
|
|
796
|
+
const values = await discoverManagedInstallations(client);
|
|
797
|
+
entry.profile.recoverableInstances = values.map(recoverySummary);
|
|
798
|
+
if (values.some(value => value.hasData && (value.port === undefined || value.port === entry.profile.servicePort)))
|
|
799
|
+
throw new Error("发现此端口的旧托管实例及数据。请先选择重新接管,避免启动空白实例而看不到历史会话。");
|
|
800
|
+
}
|
|
695
801
|
this.progress(entry, updateVersion ? "下载并校验目标版本的纯服务安装包" : "生成与本地版本一致的纯服务安装包");
|
|
696
802
|
const artifact = updateVersion ? await publishedServerUpdate(updateVersion, join(this.directory, "packages")) : await this.preparePackage();
|
|
697
803
|
if (entry.profile.service === "online") {
|
|
@@ -715,12 +821,19 @@ export class ManagedServers {
|
|
|
715
821
|
await this.persist();
|
|
716
822
|
}
|
|
717
823
|
}
|
|
718
|
-
if (!reusable)
|
|
719
|
-
|
|
824
|
+
if (!reusable) {
|
|
825
|
+
if (!installation && !entry.recoveryRoot) {
|
|
826
|
+
if (!entry.instanceId || recovery?.newInstance)
|
|
827
|
+
entry.instanceId = randomUUID();
|
|
828
|
+
await this.persist();
|
|
829
|
+
}
|
|
830
|
+
installation = await installRemote({ client, id: entry.instanceId ?? id, root: entry.recoveryRoot ?? installation?.root, archive: artifact.path, archiveHash: artifact.shasum, cacheDir: join(this.directory, "cache"), progress: (step, output) => this.progress(entry, step, output) });
|
|
831
|
+
}
|
|
720
832
|
if (!installation)
|
|
721
833
|
throw new Error("远端安装未完成");
|
|
722
834
|
entry.installation = installation;
|
|
723
835
|
entry.profile.remoteRoot = installation.root;
|
|
836
|
+
delete entry.recoveryRoot;
|
|
724
837
|
entry.profile.identity ??= randomUUID();
|
|
725
838
|
const secret = this.secrets.get(id);
|
|
726
839
|
await sshWrite(client, posix.join(installation.root, "data", "browser-access.json"), JSON.stringify({ id: entry.profile.identity, key: secret.browserKey }));
|
|
@@ -781,6 +894,7 @@ export class ManagedServers {
|
|
|
781
894
|
}
|
|
782
895
|
}
|
|
783
896
|
finally {
|
|
897
|
+
delete entry.profile.maintenance;
|
|
784
898
|
this.jobs.delete(id);
|
|
785
899
|
await this.persist();
|
|
786
900
|
}
|
|
@@ -824,7 +938,7 @@ export class ManagedServers {
|
|
|
824
938
|
await this.persist();
|
|
825
939
|
return deployment;
|
|
826
940
|
}
|
|
827
|
-
async action(id, action) {
|
|
941
|
+
async action(id, action, instanceId) {
|
|
828
942
|
const entry = this.entry(id);
|
|
829
943
|
if (action === "disconnect" || action === "remove")
|
|
830
944
|
this.relays.get(id)?.terminate();
|
|
@@ -897,6 +1011,17 @@ export class ManagedServers {
|
|
|
897
1011
|
return this.startExisting(id);
|
|
898
1012
|
else if (action === "deploy")
|
|
899
1013
|
return this.deploy(id);
|
|
1014
|
+
else if (action === "repair")
|
|
1015
|
+
return this.deploy(id, undefined, { repair: true });
|
|
1016
|
+
else if (action === "deployNew")
|
|
1017
|
+
return this.deploy(id, undefined, { newInstance: true });
|
|
1018
|
+
else if (action === "scanInstances" || action === "restart")
|
|
1019
|
+
return this.maintenance(id, action === "restart" ? "restart" : "scan");
|
|
1020
|
+
else if (action === "recover") {
|
|
1021
|
+
if (typeof instanceId !== "string" || !/^[a-zA-Z0-9_-]{1,128}$/.test(instanceId))
|
|
1022
|
+
throw new Error("请选择已探测到的旧托管实例");
|
|
1023
|
+
return this.deploy(id, undefined, { instanceId });
|
|
1024
|
+
}
|
|
900
1025
|
else if (action === "remove") {
|
|
901
1026
|
if (this.jobs.has(id))
|
|
902
1027
|
throw new Error("部署期间不能移除服务器");
|
|
@@ -23,8 +23,11 @@ export declare function installRemote(options: {
|
|
|
23
23
|
archive: string;
|
|
24
24
|
archiveHash: string;
|
|
25
25
|
cacheDir: string;
|
|
26
|
+
root?: string;
|
|
26
27
|
progress(step: string, output?: string): void;
|
|
27
28
|
}): Promise<RemoteInstallation>;
|
|
28
29
|
export declare function remoteStartScript(installation: RemoteInstallation, port: number, host?: ServiceListenHost): string;
|
|
29
30
|
export declare function startRemote(client: Client, installation: RemoteInstallation, port: number, host?: ServiceListenHost): Promise<void>;
|
|
31
|
+
/** Only stop a PID whose command still belongs to this exact managed runtime. */
|
|
32
|
+
export declare function stopRemote(client: Client, installation: RemoteInstallation): Promise<void>;
|
|
30
33
|
export {};
|
|
@@ -113,7 +113,11 @@ export async function installRemote(options) {
|
|
|
113
113
|
const arch = ["x86_64", "amd64"].includes(architecture) ? "x64" : ["aarch64", "arm64"].includes(architecture) ? "arm64" : "";
|
|
114
114
|
if (!platform || !arch)
|
|
115
115
|
throw new Error("远端自动安装当前支持 Linux/macOS 的 x64、arm64 平台");
|
|
116
|
-
const
|
|
116
|
+
const base = posix.join(home, ".super-pi", "managed");
|
|
117
|
+
const root = options.root ?? posix.join(base, options.id);
|
|
118
|
+
if (posix.dirname(root) !== base || !/^[a-zA-Z0-9_-]{1,128}$/.test(posix.basename(root)))
|
|
119
|
+
throw new Error("远端实例目录不属于当前 SSH 用户的托管目录,已停止部署。");
|
|
120
|
+
await sshExec(client, `if [ -L ${sh(root)} ] || [ -L ${sh(posix.join(root, "data"))} ]; then echo 'Managed instance directories cannot be symbolic links' >&2; exit 1; fi`);
|
|
117
121
|
await sshExec(client, `umask 077; mkdir -p ${sh(root)} ${sh(posix.join(root, "data"))} ${sh(posix.join(root, "agent"))}`);
|
|
118
122
|
let node = "", npm = "";
|
|
119
123
|
for (const executable of [sh(posix.join(root, "node", "bin", "node")), "node"]) {
|
|
@@ -201,6 +205,12 @@ export async function startRemote(client, installation, port, host = "127.0.0.1"
|
|
|
201
205
|
const script = remoteStartScript(installation, port, host);
|
|
202
206
|
const { root } = installation;
|
|
203
207
|
const launcher = posix.join(root, "start-service.sh");
|
|
208
|
+
await sshWrite(client, posix.join(root, "instance.json"), JSON.stringify({ schema: 1, installation, port, host, updatedAt: new Date().toISOString() }));
|
|
204
209
|
await sshWrite(client, launcher, script, 0o700);
|
|
205
210
|
await sshExec(client, `sh ${sh(launcher)}`, { timeout: 30_000 });
|
|
206
211
|
}
|
|
212
|
+
/** Only stop a PID whose command still belongs to this exact managed runtime. */
|
|
213
|
+
export async function stopRemote(client, installation) {
|
|
214
|
+
const { root } = installation, pid = posix.join(root, "service.pid");
|
|
215
|
+
await sshExec(client, `if [ -f ${sh(pid)} ]; then p=$(cat ${sh(pid)}); case "$p" in *[!0-9]*|"") ;; *) if ps -p "$p" -o args= 2>/dev/null | grep -F ${sh(`${root}/runtime-`)} >/dev/null; then kill "$p" 2>/dev/null || true; for n in 1 2 3 4 5; do kill -0 "$p" 2>/dev/null || break; sleep 1; done; if ps -p "$p" -o args= 2>/dev/null | grep -F ${sh(`${root}/runtime-`)} >/dev/null; then echo 'Previous managed process did not stop' >&2; exit 1; fi; fi ;; esac; fi`, { timeout: 15_000 });
|
|
216
|
+
}
|
|
@@ -19,6 +19,19 @@ export type ServiceProbe = {
|
|
|
19
19
|
};
|
|
20
20
|
export type ServiceListenHost = "127.0.0.1" | "0.0.0.0" | "::";
|
|
21
21
|
export declare const isServiceListenHost: (value: unknown) => value is ServiceListenHost;
|
|
22
|
+
export interface RecoverableManagedInstance {
|
|
23
|
+
id: string;
|
|
24
|
+
root: string;
|
|
25
|
+
dataDirectory: string;
|
|
26
|
+
hasData: boolean;
|
|
27
|
+
canRestart: boolean;
|
|
28
|
+
version?: string;
|
|
29
|
+
port?: number;
|
|
30
|
+
host?: ServiceListenHost;
|
|
31
|
+
conversationCount?: number;
|
|
32
|
+
workspaceCount?: number;
|
|
33
|
+
modifiedAt?: string;
|
|
34
|
+
}
|
|
22
35
|
export declare function defaultServiceUrl(host: string, port: number): string;
|
|
23
36
|
export interface ManagedServerProfile {
|
|
24
37
|
id: string;
|
|
@@ -63,6 +76,9 @@ export interface ManagedServerProfile {
|
|
|
63
76
|
error?: string;
|
|
64
77
|
log?: string[];
|
|
65
78
|
updateOperation?: import("./update-status.js").UpdateOperation;
|
|
79
|
+
recoverableInstances?: RecoverableManagedInstance[];
|
|
80
|
+
maintenance?: "scan" | "restart" | "repair" | "recover";
|
|
81
|
+
canRestart?: boolean;
|
|
66
82
|
}
|
|
67
83
|
export interface ManagedServerInput {
|
|
68
84
|
id?: string;
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"superPi": {
|
|
4
4
|
"managedDirectListener": true
|
|
5
5
|
},
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.292",
|
|
7
7
|
"description": "Web control plane and companion for Pi",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"type": "module",
|
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"scripts/managed-ssh.test.mjs",
|
|
85
85
|
"scripts/managed-model.test.mjs",
|
|
86
86
|
"scripts/managed-model-flow.test.mjs",
|
|
87
|
+
"scripts/managed-offline-recovery.test.mjs",
|
|
87
88
|
"scripts/multi-server.test.mjs",
|
|
88
89
|
"scripts/native-tools.test.mjs",
|
|
89
90
|
"scripts/markdown-syntax.test.mjs",
|
|
@@ -338,6 +339,7 @@
|
|
|
338
339
|
],
|
|
339
340
|
"check:browser": [
|
|
340
341
|
"scripts/managed-model-errors-browser.test.mjs",
|
|
342
|
+
"scripts/managed-offline-recovery-browser.test.mjs",
|
|
341
343
|
"scripts/git-panel-upgrade-browser.test.mjs",
|
|
342
344
|
"scripts/welcome-workspace-git-browser.test.mjs",
|
|
343
345
|
"scripts/editor-search-design-browser.test.mjs",
|