@evandu/super-pi 0.1.258 → 0.1.259
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/README.md +40 -0
- package/agents/super-pi-managed-model/index.ts +9 -0
- package/bin/npm-prefix.js +1 -1
- package/bin/super-pi.js +4 -3
- package/desktop/icon.png +0 -0
- package/desktop/launch.cjs +14 -0
- package/desktop/main.cjs +96 -0
- package/desktop/preload.cjs +9 -0
- package/dist/client/.super-pi-client-sources.json +33 -28
- package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
- package/dist/client/assets/{GitDiffEditor-BOtWl74Z.js → GitDiffEditor-FQBfGxOY.js} +3 -3
- package/dist/client/assets/index-Cn7hdrDw.js +350 -0
- package/dist/client/assets/{index-JchFQmlF.css → index-UfzqdECL.css} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/server/browser-access.d.ts +34 -0
- package/dist/server/browser-access.js +89 -0
- package/dist/server/command-handler.d.ts +1 -1
- package/dist/server/command-handler.js +3 -3
- package/dist/server/http-server.js +90 -36
- package/dist/server/index.js +9 -0
- package/dist/server/managed-http-tunnel.d.ts +6 -0
- package/dist/server/managed-http-tunnel.js +85 -0
- package/dist/server/managed-http.d.ts +4 -0
- package/dist/server/managed-http.js +85 -0
- package/dist/server/managed-model-adapter.d.ts +17 -0
- package/dist/server/managed-model-adapter.js +75 -0
- package/dist/server/managed-model-gateway.d.ts +49 -0
- package/dist/server/managed-model-gateway.js +73 -0
- package/dist/server/managed-servers.d.ts +55 -0
- package/dist/server/managed-servers.js +392 -0
- package/dist/server/managed-ssh.d.ts +26 -0
- package/dist/server/managed-ssh.js +73 -0
- package/dist/server/manager-vault.d.ts +11 -0
- package/dist/server/manager-vault.js +67 -0
- package/dist/server/provider-proxy.js +2 -0
- package/dist/server/remote-bootstrap.d.ts +17 -0
- package/dist/server/remote-bootstrap.js +119 -0
- package/dist/server/server-context.d.ts +2 -0
- package/dist/server/terminal.d.ts +2 -2
- package/dist/server/terminal.js +6 -6
- package/dist/server/update.d.ts +1 -0
- package/dist/server/update.js +13 -2
- package/dist/server/ws-server.d.ts +5 -0
- package/dist/server/ws-server.js +29 -4
- package/dist/shared/managed-servers.d.ts +36 -0
- package/dist/shared/managed-servers.js +1 -0
- package/package.json +19 -4
- package/scripts/pack-server.mjs +44 -0
- package/dist/client/assets/CodeMirrorEditor-CyVU-MC_.js +0 -2
- package/dist/client/assets/index-Ba79LA0t.js +0 -349
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
3
|
+
import { join, basename, posix } from "node:path";
|
|
4
|
+
import { sh, sshExec, sshSftp, sshWrite } from "./managed-ssh.js";
|
|
5
|
+
export async function uploadFile(client, local, remote) {
|
|
6
|
+
const sftp = await sshSftp(client);
|
|
7
|
+
try {
|
|
8
|
+
await new Promise((resolve, reject) => sftp.fastPut(local, remote, { mode: 0o600 }, error => error ? reject(new Error("上传远端安装文件失败")) : resolve()));
|
|
9
|
+
}
|
|
10
|
+
finally {
|
|
11
|
+
sftp.end();
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
async function nodeArchive(platform, arch, directory) {
|
|
15
|
+
const version = "v22.20.0", filename = `node-${version}-${platform}-${arch}.tar.gz`;
|
|
16
|
+
const path = join(directory, filename);
|
|
17
|
+
await mkdir(directory, { recursive: true });
|
|
18
|
+
const sums = await fetch(`https://nodejs.org/dist/${version}/SHASUMS256.txt`, { signal: AbortSignal.timeout(30_000) });
|
|
19
|
+
if (!sums.ok)
|
|
20
|
+
throw new Error("无法下载 Node.js 校验信息,请检查本地网络");
|
|
21
|
+
const expected = (await sums.text()).split("\n").find(line => line.endsWith(` ${filename}`))?.trim().split(/\s+/)[0];
|
|
22
|
+
if (!expected)
|
|
23
|
+
throw new Error("Node.js 官方未提供该平台的安装包");
|
|
24
|
+
try {
|
|
25
|
+
const bytes = await readFile(path);
|
|
26
|
+
if (createHash("sha256").update(bytes).digest("hex") === expected)
|
|
27
|
+
return path;
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
const result = await fetch(`https://nodejs.org/dist/${version}/${filename}`, { signal: AbortSignal.timeout(10 * 60_000) });
|
|
31
|
+
if (!result.ok)
|
|
32
|
+
throw new Error("下载 Node.js 失败");
|
|
33
|
+
const data = Buffer.from(await result.arrayBuffer());
|
|
34
|
+
if (data.length > 150 * 1024 * 1024 || createHash("sha256").update(data).digest("hex") !== expected)
|
|
35
|
+
throw new Error("Node.js 安装包校验失败");
|
|
36
|
+
await writeFile(path, data);
|
|
37
|
+
return path;
|
|
38
|
+
}
|
|
39
|
+
export async function installRemote(options) {
|
|
40
|
+
const { client, progress } = options;
|
|
41
|
+
progress("检查远端系统与运行环境");
|
|
42
|
+
const home = (await sshExec(client, "printf '%s' \"$HOME\"")).trim();
|
|
43
|
+
if (!home.startsWith("/") || /[\r\n\0]/.test(home))
|
|
44
|
+
throw new Error("远端没有有效的 POSIX 用户目录;当前支持 Linux 和 macOS 服务端");
|
|
45
|
+
const platformName = (await sshExec(client, "uname -s")).trim();
|
|
46
|
+
const platform = platformName === "Linux" ? "linux" : platformName === "Darwin" ? "darwin" : "";
|
|
47
|
+
const architecture = (await sshExec(client, "uname -m")).trim();
|
|
48
|
+
const arch = ["x86_64", "amd64"].includes(architecture) ? "x64" : ["aarch64", "arm64"].includes(architecture) ? "arm64" : "";
|
|
49
|
+
if (!platform || !arch)
|
|
50
|
+
throw new Error("远端自动安装当前支持 Linux/macOS 的 x64、arm64 平台");
|
|
51
|
+
const root = posix.join(home, ".super-pi", "managed", options.id);
|
|
52
|
+
await sshExec(client, `umask 077; mkdir -p ${sh(root)} ${sh(posix.join(root, "data"))} ${sh(posix.join(root, "agent"))}`);
|
|
53
|
+
let node = "", npm = "";
|
|
54
|
+
try {
|
|
55
|
+
const found = JSON.parse((await sshExec(client, "node -p 'JSON.stringify({version:process.versions.node,path:process.execPath})'")).trim());
|
|
56
|
+
const [major, minor] = String(found.version).split(".").map(Number);
|
|
57
|
+
npm = (await sshExec(client, "command -v npm")).trim();
|
|
58
|
+
if (major > 22 || (major === 22 && minor >= 19))
|
|
59
|
+
node = found.path;
|
|
60
|
+
}
|
|
61
|
+
catch { /* A private Node runtime is installed when the login environment lacks a usable one. */ }
|
|
62
|
+
if (!node || !npm) {
|
|
63
|
+
progress("下载并校验 Node.js(仅首次需要)");
|
|
64
|
+
const local = await nodeArchive(platform, arch, options.cacheDir), remote = posix.join(root, basename(local));
|
|
65
|
+
await uploadFile(client, local, remote);
|
|
66
|
+
const nodeRoot = posix.join(root, "node");
|
|
67
|
+
progress("安装用户目录内的 Node.js,无需管理员权限");
|
|
68
|
+
await sshExec(client, `mkdir -p ${sh(nodeRoot)}; tar -xzf ${sh(remote)} --strip-components=1 -C ${sh(nodeRoot)}`, { timeout: 120_000 });
|
|
69
|
+
node = posix.join(nodeRoot, "bin", "node");
|
|
70
|
+
npm = posix.join(nodeRoot, "bin", "npm");
|
|
71
|
+
await sshExec(client, `${sh(node)} --version`);
|
|
72
|
+
}
|
|
73
|
+
progress("上传纯服务安装包");
|
|
74
|
+
const remoteArchive = posix.join(root, "server.tgz");
|
|
75
|
+
await uploadFile(client, options.archive, remoteArchive);
|
|
76
|
+
const runtime = posix.join(root, `runtime-${options.archiveHash.slice(0, 16)}`);
|
|
77
|
+
const packageRoot = posix.join(runtime, "node_modules", "@evandu", "super-pi-server");
|
|
78
|
+
progress("安装远端服务依赖");
|
|
79
|
+
await sshExec(client, `umask 077; export PATH=${sh(posix.dirname(node))}:"$PATH"; ${sh(npm)} install --prefix ${sh(runtime)} --omit=dev --no-audit --no-fund --fetch-timeout=900000 --fetch-retries=3 ${sh(remoteArchive)}`, { timeout: 20 * 60_000, onOutput: output => progress("安装远端服务依赖", output) });
|
|
80
|
+
const piCommand = posix.join(root, "pi-managed");
|
|
81
|
+
progress("配置远端 Pi 启动器");
|
|
82
|
+
const resolvePi = `import{fileURLToPath}from'node:url';import{dirname,resolve,join}from'node:path';import{readFileSync,accessSync}from'node:fs';const root=resolve(dirname(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent'))),'..');const bin=JSON.parse(readFileSync(join(root,'package.json'),'utf8')).bin.pi;const cli=resolve(root,bin);accessSync(cli);process.stdout.write(cli);`;
|
|
83
|
+
const piCli = (await sshExec(client, `cd ${sh(packageRoot)} && ${sh(node)} --input-type=module -e ${sh(resolvePi)}`, { onOutput: output => progress("配置远端 Pi 启动器", output) })).trim();
|
|
84
|
+
if (!piCli || !piCli.endsWith("/cli.js"))
|
|
85
|
+
throw new Error("远端 Pi 安装不完整,请重试部署");
|
|
86
|
+
const extension = posix.join(packageRoot, "agents", "super-pi-managed-model", "index.ts");
|
|
87
|
+
await sshWrite(client, piCommand, `#!/bin/sh\nexec ${sh(node)} ${sh(piCli)} --extension ${sh(extension)} "$@"\n`, 0o700);
|
|
88
|
+
return { root, packageRoot, node, piCommand };
|
|
89
|
+
}
|
|
90
|
+
export async function startRemote(client, installation, port) {
|
|
91
|
+
const { root, packageRoot, node, piCommand } = installation;
|
|
92
|
+
const pidFile = posix.join(root, "service.pid");
|
|
93
|
+
const entry = posix.join(packageRoot, "dist", "server", "index.js");
|
|
94
|
+
const script = `#!/bin/sh
|
|
95
|
+
set -eu
|
|
96
|
+
umask 077
|
|
97
|
+
if [ -f ${sh(pidFile)} ]; then
|
|
98
|
+
pid=$(cat ${sh(pidFile)})
|
|
99
|
+
case "$pid" in *[!0-9]*|"") ;; *)
|
|
100
|
+
if ps -p "$pid" -o args= 2>/dev/null | grep -F ${sh(`${root}/runtime-`)} >/dev/null; then
|
|
101
|
+
kill "$pid" 2>/dev/null || true
|
|
102
|
+
for n in 1 2 3 4 5; do kill -0 "$pid" 2>/dev/null || break; sleep 1; done
|
|
103
|
+
fi ;;
|
|
104
|
+
esac
|
|
105
|
+
fi
|
|
106
|
+
export SUPER_PI_DATA_DIR=${sh(posix.join(root, "data"))}
|
|
107
|
+
export PI_CODING_AGENT_DIR=${sh(posix.join(root, "agent"))}
|
|
108
|
+
export SUPER_PI_MANAGED_CONFIG=${sh(posix.join(root, "models.json"))}
|
|
109
|
+
export SUPER_PI_PI_COMMAND=${sh(piCommand)}
|
|
110
|
+
export SUPER_PI_HOST=127.0.0.1
|
|
111
|
+
export SUPER_PI_PORT=${port}
|
|
112
|
+
export PATH=${sh(posix.dirname(node))}:"$PATH"
|
|
113
|
+
nohup ${sh(node)} ${sh(entry)} >>${sh(posix.join(root, "service.log"))} 2>&1 </dev/null &
|
|
114
|
+
echo $! >${sh(pidFile)}
|
|
115
|
+
`;
|
|
116
|
+
const launcher = posix.join(root, "start-service.sh");
|
|
117
|
+
await sshWrite(client, launcher, script, 0o700);
|
|
118
|
+
await sshExec(client, `sh ${sh(launcher)}`, { timeout: 30_000 });
|
|
119
|
+
}
|
|
@@ -37,6 +37,8 @@ export interface EventBroadcaster {
|
|
|
37
37
|
* Central server context containing infrastructure dependencies and application services.
|
|
38
38
|
*/
|
|
39
39
|
export interface ServerContext {
|
|
40
|
+
managedServers?: import("./managed-servers.js").ManagedServers;
|
|
41
|
+
browserAccess?: import("./browser-access.js").BrowserAccess;
|
|
40
42
|
memory?: import("./active-memory.js").ActiveMemory;
|
|
41
43
|
knowledge?: import("./knowledge.js").KnowledgeBase;
|
|
42
44
|
web?: import("./web.js").WebService;
|
|
@@ -141,9 +141,9 @@ export declare class TerminalService {
|
|
|
141
141
|
enabled?: boolean;
|
|
142
142
|
});
|
|
143
143
|
readonly enabled: boolean;
|
|
144
|
-
setShell(command: string | null, remoteAddress: string | undefined): Promise<boolean>;
|
|
144
|
+
setShell(command: string | null, remoteAddress: string | undefined, browserAuthorized?: boolean): Promise<boolean>;
|
|
145
145
|
private assertUsable;
|
|
146
|
-
handle(command: TerminalCommand, remoteAddress: string | undefined, send: TerminalSender): Promise<void>;
|
|
146
|
+
handle(command: TerminalCommand, remoteAddress: string | undefined, send: TerminalSender, browserAuthorized?: boolean): Promise<void>;
|
|
147
147
|
private sync;
|
|
148
148
|
private open;
|
|
149
149
|
private spawn;
|
package/dist/server/terminal.js
CHANGED
|
@@ -265,8 +265,8 @@ export class TerminalService {
|
|
|
265
265
|
this.enabled = options.enabled ?? isTerminalEnabled();
|
|
266
266
|
}
|
|
267
267
|
enabled;
|
|
268
|
-
async setShell(command, remoteAddress) {
|
|
269
|
-
if (!this.enabled || !this.isTrustedPeer(remoteAddress))
|
|
268
|
+
async setShell(command, remoteAddress, browserAuthorized = false) {
|
|
269
|
+
if (!this.enabled || (!browserAuthorized && !this.isTrustedPeer(remoteAddress)))
|
|
270
270
|
return false;
|
|
271
271
|
if (command === null) {
|
|
272
272
|
await this.saveConfiguredShell(undefined);
|
|
@@ -281,8 +281,8 @@ export class TerminalService {
|
|
|
281
281
|
await this.saveConfiguredShell(shell);
|
|
282
282
|
return true;
|
|
283
283
|
}
|
|
284
|
-
assertUsable(remoteAddress, send) {
|
|
285
|
-
if (!this.isTrustedPeer(remoteAddress)) {
|
|
284
|
+
assertUsable(remoteAddress, send, browserAuthorized) {
|
|
285
|
+
if (!browserAuthorized && !this.isTrustedPeer(remoteAddress)) {
|
|
286
286
|
send({ type: "terminal.error", message: "终端只接受来自本机或局域网地址的连接。" });
|
|
287
287
|
return false;
|
|
288
288
|
}
|
|
@@ -292,12 +292,12 @@ export class TerminalService {
|
|
|
292
292
|
}
|
|
293
293
|
return true;
|
|
294
294
|
}
|
|
295
|
-
async handle(command, remoteAddress, send) {
|
|
295
|
+
async handle(command, remoteAddress, send, browserAuthorized = false) {
|
|
296
296
|
if (command.type === "terminal.detach") {
|
|
297
297
|
this.detach(send);
|
|
298
298
|
return;
|
|
299
299
|
}
|
|
300
|
-
if (!this.assertUsable(remoteAddress, send))
|
|
300
|
+
if (!this.assertUsable(remoteAddress, send, browserAuthorized))
|
|
301
301
|
return;
|
|
302
302
|
if (command.type === "terminal.sync") {
|
|
303
303
|
await this.sync(command, send);
|
package/dist/server/update.d.ts
CHANGED
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
export declare function quoteForShell(value: string): string;
|
|
15
15
|
/** The arguments to hand to npm, quoted for the shell when the shell is what runs them. */
|
|
16
16
|
export declare function shellArgs(args: string[]): string[];
|
|
17
|
+
export declare function installedPackageName(rootDir?: string): "@evandu/super-pi" | "@evandu/super-pi-server";
|
|
17
18
|
/** Check the release registry with a package-sized timeout and bounded retries for transient failures. */
|
|
18
19
|
export declare function fetchLatestPackageVersion(): Promise<string>;
|
|
19
20
|
/**
|
package/dist/server/update.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
1
3
|
import { npmInstallPrefix } from "../../bin/npm-prefix.js";
|
|
2
4
|
/**
|
|
3
5
|
* Quote an argument for a shell on Windows.
|
|
@@ -19,12 +21,20 @@ export function quoteForShell(value) {
|
|
|
19
21
|
export function shellArgs(args) {
|
|
20
22
|
return process.platform === "win32" ? args.map(quoteForShell) : args;
|
|
21
23
|
}
|
|
24
|
+
export function installedPackageName(rootDir = resolve(import.meta.dirname, "../..")) {
|
|
25
|
+
try {
|
|
26
|
+
if (JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8")).name === "@evandu/super-pi-server")
|
|
27
|
+
return "@evandu/super-pi-server";
|
|
28
|
+
}
|
|
29
|
+
catch { }
|
|
30
|
+
return /[\\/]super-pi-server[\\/]?$/.test(rootDir) ? "@evandu/super-pi-server" : "@evandu/super-pi";
|
|
31
|
+
}
|
|
22
32
|
/** Check the release registry with a package-sized timeout and bounded retries for transient failures. */
|
|
23
33
|
export async function fetchLatestPackageVersion() {
|
|
24
34
|
let lastError;
|
|
25
35
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
26
36
|
try {
|
|
27
|
-
const response = await fetch(
|
|
37
|
+
const response = await fetch(`https://registry.npmjs.org/${installedPackageName()}/latest`, { signal: AbortSignal.timeout(20_000) });
|
|
28
38
|
if (!response.ok)
|
|
29
39
|
throw new Error(`npm registry HTTP ${response.status}`);
|
|
30
40
|
const payload = await response.json();
|
|
@@ -65,7 +75,8 @@ export function packageUpdateArgs(rootDir, version, platform = process.platform)
|
|
|
65
75
|
// THE VERSION THE USER CONFIRMED. The check reads the registry directly while npm resolves
|
|
66
76
|
// "latest" from its own cache, so the two can disagree: the dialog promises vX and the
|
|
67
77
|
// install silently lands on vY. Pinning the version the dialog showed removes that gap.
|
|
68
|
-
const
|
|
78
|
+
const name = installedPackageName(rootDir);
|
|
79
|
+
const target = version ? `${name}@${version}` : name;
|
|
69
80
|
if (prefix !== undefined) {
|
|
70
81
|
return { prefix, args: ["install", "-g", "--prefix", prefix, "--fetch-timeout=900000", "--fetch-retries=8", "--fetch-retry-maxtimeout=120000", target] };
|
|
71
82
|
}
|
|
@@ -4,6 +4,7 @@ import type { AppState, ServerEvent } from "./types.js";
|
|
|
4
4
|
import type { EventBroadcaster } from "./server-context.js";
|
|
5
5
|
import type { CommandHandler, SocketSender } from "./command-handler.js";
|
|
6
6
|
import type { CatalogService } from "./application/catalog-service.js";
|
|
7
|
+
import type { BrowserAccess } from "./browser-access.js";
|
|
7
8
|
/**
|
|
8
9
|
* A WebSocket is a live transport, not an unbounded queue. `ws.send()` only
|
|
9
10
|
* copies bytes into the socket's userland buffer; a browser that is frozen or
|
|
@@ -114,6 +115,8 @@ export declare class WsBroadcaster implements EventBroadcaster {
|
|
|
114
115
|
}): AppState;
|
|
115
116
|
}
|
|
116
117
|
export interface WsServerOptions {
|
|
118
|
+
browserAccess?: BrowserAccess;
|
|
119
|
+
managedServers?: import("./managed-servers.js").ManagedServers;
|
|
117
120
|
httpServer: NodeHttpServer;
|
|
118
121
|
broadcaster: WsBroadcaster;
|
|
119
122
|
commandHandler: CommandHandler;
|
|
@@ -127,6 +130,8 @@ export interface WsServerOptions {
|
|
|
127
130
|
* WebSocket transport manager handling upgrade, connection lifecycles, and command dispatch.
|
|
128
131
|
*/
|
|
129
132
|
export declare class WsServer {
|
|
133
|
+
private readonly browserAccess?;
|
|
134
|
+
private readonly managedServers?;
|
|
130
135
|
private readonly websocketServer;
|
|
131
136
|
private readonly broadcaster;
|
|
132
137
|
private readonly commandHandler;
|
package/dist/server/ws-server.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { isBrowserAuthorized } from "./browser-access.js";
|
|
1
2
|
import { WebSocket, WebSocketServer } from "ws";
|
|
2
|
-
import { isAuthorized } from "./http-server.js";
|
|
3
|
+
import { isAuthorized, isLoopbackAddress } from "./http-server.js";
|
|
3
4
|
import { describeThrown, describeThrownWithStack } from "./failure-text.js";
|
|
4
5
|
/**
|
|
5
6
|
* A WebSocket is a live transport, not an unbounded queue. `ws.send()` only
|
|
@@ -354,6 +355,8 @@ import { checkDiskVersion } from "./version.js";
|
|
|
354
355
|
* WebSocket transport manager handling upgrade, connection lifecycles, and command dispatch.
|
|
355
356
|
*/
|
|
356
357
|
export class WsServer {
|
|
358
|
+
browserAccess;
|
|
359
|
+
managedServers;
|
|
357
360
|
websocketServer;
|
|
358
361
|
broadcaster;
|
|
359
362
|
commandHandler;
|
|
@@ -362,6 +365,8 @@ export class WsServer {
|
|
|
362
365
|
rootDir;
|
|
363
366
|
onSocketClose;
|
|
364
367
|
constructor(options) {
|
|
368
|
+
this.browserAccess = options.browserAccess;
|
|
369
|
+
this.managedServers = options.managedServers;
|
|
365
370
|
this.broadcaster = options.broadcaster;
|
|
366
371
|
this.commandHandler = options.commandHandler;
|
|
367
372
|
this.catalogService = options.catalogService;
|
|
@@ -372,12 +377,24 @@ export class WsServer {
|
|
|
372
377
|
// contain a long transcript, so sending them uncompressed turns every lifecycle event into a multi-MB
|
|
373
378
|
// transfer. Per-message deflate keeps the protocol unchanged while making the wire cost proportional
|
|
374
379
|
// to the actual information in the snapshot. The threshold avoids spending CPU on token-sized events.
|
|
375
|
-
this.websocketServer = new WebSocketServer({ noServer: true, maxPayload: MAX_WS_PAYLOAD_BYTES, perMessageDeflate: { threshold: 1024, serverNoContextTakeover: true } });
|
|
380
|
+
this.websocketServer = new WebSocketServer({ noServer: true, handleProtocols: protocols => protocols.has("super-pi") ? "super-pi" : false, maxPayload: MAX_WS_PAYLOAD_BYTES, perMessageDeflate: { threshold: 1024, serverNoContextTakeover: true } });
|
|
376
381
|
this.setupUpgrade(options.httpServer);
|
|
377
382
|
this.setupConnectionHandling();
|
|
378
383
|
}
|
|
379
384
|
setupUpgrade(httpServer) {
|
|
380
385
|
httpServer.on("upgrade", (request, socket, head) => {
|
|
386
|
+
const browserAuthorized = this.browserAccess?.authorize(request, true) ?? false;
|
|
387
|
+
const url = new URL(request.url ?? "/", `http://${request.headers.host ?? "localhost"}`);
|
|
388
|
+
const managed = /^\/managed\/([a-f0-9-]+)(\/ws)$/.exec(url.pathname);
|
|
389
|
+
if (managed) {
|
|
390
|
+
if (!this.managedServers || !isAuthorized(request, this.accessToken)
|
|
391
|
+
|| (!browserAuthorized && (!isLoopbackAddress(request.socket.remoteAddress) || (request.headers.origin && request.headers.origin !== url.origin)))) {
|
|
392
|
+
socket.destroy();
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
void this.managedServers.upgrade(managed[1], managed[2] + url.search, request, socket, head).catch(() => socket.destroy());
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
381
398
|
if (!isAuthorized(request, this.accessToken) || new URL(request.url ?? "/", "http://localhost").pathname !== "/ws") {
|
|
382
399
|
socket.destroy();
|
|
383
400
|
return;
|
|
@@ -387,7 +404,7 @@ export class WsServer {
|
|
|
387
404
|
try {
|
|
388
405
|
const parsed = new URL(origin);
|
|
389
406
|
const host = request.headers.host;
|
|
390
|
-
if (!host || parsed.host !== host || !["http:", "https:"].includes(parsed.protocol)) {
|
|
407
|
+
if ((!browserAuthorized && (!host || parsed.host !== host)) || !["http:", "https:"].includes(parsed.protocol)) {
|
|
391
408
|
socket.destroy();
|
|
392
409
|
return;
|
|
393
410
|
}
|
|
@@ -398,6 +415,10 @@ export class WsServer {
|
|
|
398
415
|
}
|
|
399
416
|
}
|
|
400
417
|
this.websocketServer.handleUpgrade(request, socket, head, (ws) => {
|
|
418
|
+
if (browserAuthorized) {
|
|
419
|
+
const release = this.browserAccess.onRevoke(() => ws.close(4003, "Browser authorization revoked"));
|
|
420
|
+
ws.once("close", release);
|
|
421
|
+
}
|
|
401
422
|
this.websocketServer.emit("connection", ws, request);
|
|
402
423
|
});
|
|
403
424
|
});
|
|
@@ -510,6 +531,10 @@ export class WsServer {
|
|
|
510
531
|
*/
|
|
511
532
|
let commandQueue = Promise.resolve();
|
|
512
533
|
socket.on("message", (raw) => {
|
|
534
|
+
if (isBrowserAuthorized(request) && !this.browserAccess?.authorize(request, true)) {
|
|
535
|
+
socket.close(4003, "Browser authorization revoked");
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
513
538
|
let parsed;
|
|
514
539
|
try {
|
|
515
540
|
parsed = JSON.parse(raw.toString());
|
|
@@ -557,7 +582,7 @@ export class WsServer {
|
|
|
557
582
|
command = parsed;
|
|
558
583
|
if (command.type.startsWith("terminal.") && socket.readyState !== WebSocket.OPEN)
|
|
559
584
|
return;
|
|
560
|
-
const entityId = await this.commandHandler.handleCommand(command, send, remoteAddress);
|
|
585
|
+
const entityId = await this.commandHandler.handleCommand(command, send, remoteAddress, isBrowserAuthorized(request));
|
|
561
586
|
// Void-returning configuration commands also need an ack to release optimistic UI state.
|
|
562
587
|
if (command.operationRequestId)
|
|
563
588
|
safeSend(socket, JSON.stringify({ type: "operation.result", requestId: command.operationRequestId, ok: true, entityId }));
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export interface ManagedServerProfile {
|
|
2
|
+
id: string;
|
|
3
|
+
name: string;
|
|
4
|
+
host: string;
|
|
5
|
+
sshPort: number;
|
|
6
|
+
username: string;
|
|
7
|
+
servicePort: number;
|
|
8
|
+
authentication: "agent" | "password" | "privateKey";
|
|
9
|
+
identityFile?: string;
|
|
10
|
+
fingerprint?: string;
|
|
11
|
+
observedFingerprint?: string;
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
identity?: string;
|
|
14
|
+
deployedAt?: string;
|
|
15
|
+
remoteRoot?: string;
|
|
16
|
+
ssh: "offline" | "connecting" | "online" | "needsTrust";
|
|
17
|
+
service: "unknown" | "offline" | "online";
|
|
18
|
+
modelChannel: "offline" | "online";
|
|
19
|
+
phase: "idle" | "connecting" | "needsTrust" | "deploying" | "ready" | "failed";
|
|
20
|
+
step?: string;
|
|
21
|
+
error?: string;
|
|
22
|
+
log?: string[];
|
|
23
|
+
}
|
|
24
|
+
export interface ManagedServerInput {
|
|
25
|
+
id?: string;
|
|
26
|
+
name: string;
|
|
27
|
+
host: string;
|
|
28
|
+
sshPort: number;
|
|
29
|
+
username: string;
|
|
30
|
+
servicePort: number;
|
|
31
|
+
authentication: ManagedServerProfile["authentication"];
|
|
32
|
+
identityFile?: string;
|
|
33
|
+
password?: string;
|
|
34
|
+
privateKey?: string;
|
|
35
|
+
passphrase?: string;
|
|
36
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@evandu/super-pi",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.259",
|
|
4
4
|
"description": "Web control plane and companion for Pi",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"bin": {
|
|
8
8
|
"super-pi": "bin/super-pi.js",
|
|
9
|
-
"super_pi": "bin/super-pi.js"
|
|
9
|
+
"super_pi": "bin/super-pi.js",
|
|
10
|
+
"super-pi-desktop": "desktop/launch.cjs"
|
|
10
11
|
},
|
|
11
12
|
"pi": {
|
|
12
13
|
"extensions": [
|
|
@@ -23,7 +24,9 @@
|
|
|
23
24
|
"assets/knowledge-model",
|
|
24
25
|
"scripts/patch-brace-expansion.mjs",
|
|
25
26
|
"scripts/diagnose.mjs",
|
|
26
|
-
"assets/fonts"
|
|
27
|
+
"assets/fonts",
|
|
28
|
+
"desktop",
|
|
29
|
+
"scripts/pack-server.mjs"
|
|
27
30
|
],
|
|
28
31
|
"engines": {
|
|
29
32
|
"node": ">=22.19.0"
|
|
@@ -40,9 +43,14 @@
|
|
|
40
43
|
"restart:server": "node scripts/restart-server.mjs",
|
|
41
44
|
"smoke": "npm run build && node scripts/smoke.mjs",
|
|
42
45
|
"check": "node scripts/run-check.mjs",
|
|
43
|
-
"test": "node scripts/test.mjs"
|
|
46
|
+
"test": "node scripts/test.mjs",
|
|
47
|
+
"desktop": "node desktop/launch.cjs",
|
|
48
|
+
"pack:server": "npm run build && node scripts/pack-server.mjs"
|
|
44
49
|
},
|
|
45
50
|
"check:logic": [
|
|
51
|
+
"scripts/managed-ssh.test.mjs",
|
|
52
|
+
"scripts/managed-model.test.mjs",
|
|
53
|
+
"scripts/multi-server.test.mjs",
|
|
46
54
|
"scripts/native-tools.test.mjs",
|
|
47
55
|
"scripts/markdown-syntax.test.mjs",
|
|
48
56
|
"scripts/file-mentions.test.mjs",
|
|
@@ -294,6 +302,9 @@
|
|
|
294
302
|
"scripts/session-reminder-pmo-rights.test.mjs"
|
|
295
303
|
],
|
|
296
304
|
"check:browser": [
|
|
305
|
+
"scripts/desktop-browser.test.mjs",
|
|
306
|
+
"scripts/managed-remote-install.test.mjs",
|
|
307
|
+
"scripts/multi-server-browser.test.mjs",
|
|
297
308
|
"scripts/native-tools-browser.test.mjs",
|
|
298
309
|
"scripts/markdown-syntax-browser.test.mjs",
|
|
299
310
|
"scripts/file-mentions-browser.test.mjs",
|
|
@@ -431,14 +442,17 @@
|
|
|
431
442
|
"@codemirror/search": "^6.7.2",
|
|
432
443
|
"@codemirror/state": "^6.7.6",
|
|
433
444
|
"@codemirror/view": "^6.43.15",
|
|
445
|
+
"@earendil-works/pi-ai": "1.5.2",
|
|
434
446
|
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
435
447
|
"@git-diff-view/react": "^0.1.8",
|
|
436
448
|
"@types/diff": "^5.2.3",
|
|
437
449
|
"@xterm/addon-fit": "^0.11.0",
|
|
438
450
|
"@xterm/xterm": "^6.0.0",
|
|
439
451
|
"diff": "^5.2.2",
|
|
452
|
+
"electron": "45.4.1",
|
|
440
453
|
"fuse.js": "^7.5.0",
|
|
441
454
|
"node-pty": "^1.2.0-beta.15",
|
|
455
|
+
"ssh2": "1.17.0",
|
|
442
456
|
"undici": "^7.30.2",
|
|
443
457
|
"ws": "latest"
|
|
444
458
|
},
|
|
@@ -447,6 +461,7 @@
|
|
|
447
461
|
"@types/pdfkit": "^0.17.7",
|
|
448
462
|
"@types/react": "latest",
|
|
449
463
|
"@types/react-dom": "latest",
|
|
464
|
+
"@types/ssh2": "1.15.6",
|
|
450
465
|
"@types/ws": "latest",
|
|
451
466
|
"@vitejs/plugin-react": "latest",
|
|
452
467
|
"concurrently": "latest",
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { cp, mkdir, mkdtemp, readFile, rm, writeFile, realpath, access } from "node:fs/promises";
|
|
2
|
+
import { spawn, execFile } from "node:child_process";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { dirname, join, resolve } from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
const execFileAsync = promisify(execFile);
|
|
9
|
+
async function npmCli() {
|
|
10
|
+
const candidates = [process.env.npm_execpath, join(dirname(process.execPath), "node_modules/npm/bin/npm-cli.js"), resolve(dirname(process.execPath), "../lib/node_modules/npm/bin/npm-cli.js"), "/usr/share/nodejs/npm/bin/npm-cli.js"];
|
|
11
|
+
try {
|
|
12
|
+
const found = (await execFileAsync(process.platform === "win32" ? "where.exe" : "which", [process.platform === "win32" ? "npm.cmd" : "npm"], { windowsHide: true })).stdout.trim().split(/\r?\n/)[0];
|
|
13
|
+
candidates.push(process.platform === "win32" ? join(dirname(found), "node_modules/npm/bin/npm-cli.js") : await realpath(found));
|
|
14
|
+
} catch { /* Report one actionable error after all supported locations are checked. */ }
|
|
15
|
+
for (const candidate of candidates) if (candidate) { try { await access(candidate); return candidate; } catch {} }
|
|
16
|
+
throw new Error("找不到 npm,请安装 Node.js 后重试远端部署");
|
|
17
|
+
}
|
|
18
|
+
export async function packServer(root, destination) {
|
|
19
|
+
for (const required of ["dist/server/index.js", "dist/client/index.html", "dist/server/managed-model-adapter.js", "agents/super-pi-managed-model/index.ts", "bin/super-pi.js"]) {
|
|
20
|
+
try { await access(join(root, required)); } catch { throw new Error(`纯服务安装包缺少 ${required},请先完成构建或重新安装完整包`); }
|
|
21
|
+
}
|
|
22
|
+
const staging = await mkdtemp(join(tmpdir(), "super-pi-server-pack-"));
|
|
23
|
+
try {
|
|
24
|
+
const manifest = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
|
|
25
|
+
const files = (manifest.files ?? []).filter(file => file !== "desktop" && file !== "scripts/pack-server.mjs");
|
|
26
|
+
for (const file of files) { try { await cp(join(root, file), join(staging, file), { recursive: true }); } catch (error) { if (error.code !== "ENOENT") throw error; } }
|
|
27
|
+
const dependencies = Object.fromEntries(Object.entries(manifest.dependencies ?? {}).filter(([name]) => !["electron", "ssh2"].includes(name)));
|
|
28
|
+
const server = { ...manifest, name: "@evandu/super-pi-server", description: "Super Pi remote execution service, without the desktop runtime", files, dependencies, devDependencies: undefined, scripts: undefined, bin: { "super-pi": "bin/super-pi.js", super_pi: "bin/super-pi.js", "super-pi-server": "bin/super-pi.js" } };
|
|
29
|
+
await writeFile(join(staging, "package.json"), `${JSON.stringify(server, null, 2)}\n`);
|
|
30
|
+
await mkdir(destination, { recursive: true });
|
|
31
|
+
const cli = await npmCli();
|
|
32
|
+
const output = await new Promise((resolveOutput, reject) => {
|
|
33
|
+
const child = spawn(process.execPath, [cli, "pack", "--ignore-scripts", "--json", "--pack-destination", resolve(destination)], { cwd: staging, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
|
|
34
|
+
let output = ""; child.stdout.on("data", chunk => { output += chunk; });
|
|
35
|
+
child.once("error", reject); child.once("exit", code => code === 0 ? resolveOutput(output) : reject(new Error("纯服务安装包生成失败,请检查 npm 和安装目录")));
|
|
36
|
+
});
|
|
37
|
+
const metadata = JSON.parse(output)[0];
|
|
38
|
+
return { path: join(resolve(destination), metadata.filename), version: server.version, shasum: metadata.shasum, files: metadata.entryCount };
|
|
39
|
+
} finally { await rm(staging, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); }
|
|
40
|
+
}
|
|
41
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
42
|
+
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
43
|
+
console.log(JSON.stringify(await packServer(root, resolve(process.argv[2] || join(root, "output")))));
|
|
44
|
+
}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-J6XWqRpB.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-D978o95T.js","assets/dist-B3-a6uF0.js","assets/dist-Cus6_oaF.js","assets/dist-Dc1MBGAG.js","assets/dist-BXAOrsjq.js","assets/dist-Cx00EZKR.js","assets/dist-moiMRpw_.js","assets/dist-Dds-qLxY.js","assets/dist-AW5lyI3I.js","assets/dist-BGxkyh6e.js","assets/dist-CKF2Jksy.js","assets/dist-BV64A9Ji.js","assets/dist-Dvb0SqcK.js","assets/dist-D71y2EI1.js","assets/dist-DeD9copn.js","assets/dist-QzbOCAU6.js","assets/dist-DuvGReu-.js","assets/dist-BRVQKlcp.js","assets/dist-BJxfd7yb.js","assets/dist-CX_Hm4GS.js","assets/dist-scBkrwv-.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{l as t,n,o as r,r as i,t as a}from"./index-Ba79LA0t.js";var o=e(t(),1);async function s(e,t){let[{StreamLanguage:n},r]=await Promise.all([i(()=>import(`./dist-J6XWqRpB.js`).then(e=>e.d),__vite__mapDeps([0,1,2,3,4])),e()]),a=r[t]??r.default??r;return n.define(a)}var c={cpp:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),cc:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),cxx:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),hpp:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),hh:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),hxx:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),c:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),h:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),cu:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),cuh:()=>i(()=>import(`./dist-Dc1MBGAG.js`).then(e=>e.cpp()),__vite__mapDeps([5,4,1,0,2,3,6])),js:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,2,3,4,0,6,8])),jsx:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript({jsx:!0})),__vite__mapDeps([7,1,2,3,4,0,6,8])),mjs:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,2,3,4,0,6,8])),cjs:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript()),__vite__mapDeps([7,1,2,3,4,0,6,8])),ts:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,2,3,4,0,6,8])),tsx:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0,jsx:!0})),__vite__mapDeps([7,1,2,3,4,0,6,8])),mts:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,2,3,4,0,6,8])),cts:()=>i(()=>import(`./dist-Cx00EZKR.js`).then(e=>e.t).then(e=>e.javascript({typescript:!0})),__vite__mapDeps([7,1,2,3,4,0,6,8])),py:()=>i(()=>import(`./dist-Dds-qLxY.js`).then(e=>e.python()),__vite__mapDeps([9,4,1,0,2,3,6,8])),pyi:()=>i(()=>import(`./dist-Dds-qLxY.js`).then(e=>e.python()),__vite__mapDeps([9,4,1,0,2,3,6,8])),java:()=>i(()=>import(`./dist-AW5lyI3I.js`).then(e=>e.java()),__vite__mapDeps([10,4,1,0,2,3,6])),php:()=>i(()=>import(`./dist-BGxkyh6e.js`).then(e=>e.php()),__vite__mapDeps([11,4,1,0,2,3,6,12,13,7,8])),sql:()=>i(()=>import(`./dist-Dvb0SqcK.js`).then(e=>e.sql()),__vite__mapDeps([14,4,1,0,2,3,6,8])),yaml:()=>i(()=>import(`./dist-D71y2EI1.js`).then(e=>e.yaml()),__vite__mapDeps([15,4,1,0,2,3,6])),yml:()=>i(()=>import(`./dist-D71y2EI1.js`).then(e=>e.yaml()),__vite__mapDeps([15,4,1,0,2,3,6])),xml:()=>i(()=>import(`./dist-DeD9copn.js`).then(e=>e.xml()),__vite__mapDeps([16,2,1,3,4,0,6])),json:()=>i(()=>import(`./dist-QzbOCAU6.js`).then(e=>e.json()),__vite__mapDeps([17,4,1,0,2,3,6])),jsonc:()=>i(()=>import(`./dist-QzbOCAU6.js`).then(e=>e.json()),__vite__mapDeps([17,4,1,0,2,3,6])),json5:()=>i(()=>import(`./dist-QzbOCAU6.js`).then(e=>e.json()),__vite__mapDeps([17,4,1,0,2,3,6])),html:()=>i(()=>import(`./dist-CKF2Jksy.js`).then(e=>e.html()),__vite__mapDeps([12,2,1,3,4,0,6,13,7,8])),htm:()=>i(()=>import(`./dist-CKF2Jksy.js`).then(e=>e.html()),__vite__mapDeps([12,2,1,3,4,0,6,13,7,8])),vue:()=>i(()=>import(`./dist-CKF2Jksy.js`).then(e=>e.html()),__vite__mapDeps([12,2,1,3,4,0,6,13,7,8])),svelte:()=>i(()=>import(`./dist-CKF2Jksy.js`).then(e=>e.html()),__vite__mapDeps([12,2,1,3,4,0,6,13,7,8])),css:()=>i(()=>import(`./dist-BV64A9Ji.js`).then(e=>e.r).then(e=>e.css()),__vite__mapDeps([13,1,4,0,2,3,6])),md:()=>i(()=>import(`./dist-DuvGReu-.js`).then(e=>e.markdown()),__vite__mapDeps([18,2,1,3,4,0,8,12,6,13,7])),markdown:()=>i(()=>import(`./dist-DuvGReu-.js`).then(e=>e.markdown()),__vite__mapDeps([18,2,1,3,4,0,8,12,6,13,7])),mdx:()=>i(()=>import(`./dist-DuvGReu-.js`).then(e=>e.markdown()),__vite__mapDeps([18,2,1,3,4,0,8,12,6,13,7])),rs:()=>i(()=>import(`./dist-BRVQKlcp.js`).then(e=>e.rust()),__vite__mapDeps([19,4,1,0,2,3,6])),go:()=>i(()=>import(`./dist-BJxfd7yb.js`).then(e=>e.go()),__vite__mapDeps([20,4,1,0,2,3,6,8])),sh:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),bash:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),zsh:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),fish:()=>s(()=>i(()=>import(`./shell-DwuoZtxw.js`),[]),`shell`),ps1:()=>s(()=>i(()=>import(`./powershell-D8WpQPaX.js`),[]),`powershell`),psm1:()=>s(()=>i(()=>import(`./powershell-D8WpQPaX.js`),[]),`powershell`),rb:()=>s(()=>i(()=>import(`./ruby-ChfNwlCY.js`),[]),`ruby`),swift:()=>s(()=>i(()=>import(`./swift-DKB6_1j6.js`),[]),`swift`),toml:()=>s(()=>i(()=>import(`./toml-BPTmHmyx.js`),[]),`toml`),ini:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),cfg:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),conf:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),properties:()=>s(()=>i(()=>import(`./properties-C357ku5U.js`),[]),`properties`),dockerfile:()=>s(()=>i(()=>import(`./dockerfile-BDePf5PZ.js`),[]),`dockerfile`),diff:()=>s(()=>i(()=>import(`./diff-ChtP43wD.js`),[]),`diff`),patch:()=>s(()=>i(()=>import(`./diff-ChtP43wD.js`),[]),`diff`)},l={cpp:`C++`,cc:`C++`,cxx:`C++`,hpp:`C++`,hh:`C++`,hxx:`C++`,cu:`CUDA C++`,cuh:`CUDA C++`,c:`C`,h:`C/C++ Header`,js:`JavaScript`,jsx:`JSX`,mjs:`JavaScript`,cjs:`JavaScript`,ts:`TypeScript`,tsx:`TSX`,mts:`TypeScript`,cts:`TypeScript`,py:`Python`,pyi:`Python Stub`,java:`Java`,php:`PHP`,sql:`SQL`,yaml:`YAML`,yml:`YAML`,xml:`XML`,json:`JSON`,jsonc:`JSON with Comments`,json5:`JSON5`,css:`CSS`,md:`Markdown`,markdown:`Markdown`,mdx:`MDX`,rs:`Rust`,go:`Go`,html:`HTML`,htm:`HTML`,vue:`Vue`,svelte:`Svelte`,sh:`Shell`,bash:`Bash`,zsh:`Zsh`,fish:`Fish`,ps1:`PowerShell`,psm1:`PowerShell`,rb:`Ruby`,swift:`Swift`,toml:`TOML`,ini:`INI`,cfg:`Config`,conf:`Config`,properties:`Properties`,dockerfile:`Dockerfile`,diff:`Diff`,patch:`Patch`};function u(e){return c[e.toLowerCase()]}function d(e){return l[e.toLowerCase()]}var f=r(),p=262144,m=131072;function h(e){return e.split(`.`).pop()?.toLowerCase()??``}function g(e){return getComputedStyle(document.documentElement).getPropertyValue(e).trim()}function _(e,t){return e.HighlightStyle.define([{tag:t.tags.keyword,color:g(`--cm-keyword`)},{tag:t.tags.string,color:g(`--cm-string`)},{tag:t.tags.number,color:g(`--cm-number`)},{tag:t.tags.comment,color:g(`--cm-comment`),fontStyle:`italic`},{tag:t.tags.function(t.tags.variableName),color:g(`--cm-function`)},{tag:t.tags.typeName,color:g(`--cm-type`)},{tag:t.tags.className,color:g(`--cm-type`)},{tag:t.tags.propertyName,color:g(`--cm-property`)},{tag:t.tags.operator,color:g(`--cm-operator`)},{tag:t.tags.variableName,color:g(`--cm-variable`)}])}function v({path:e,value:t,onChange:r,jumpToLine:s,onSave:c,workspaceId:l,blame:g,onPosition:v,readOnly:y=!1}){let b=(0,o.useRef)(null),x=(0,o.useRef)(null),S=(0,o.useRef)(null),C=(0,o.useRef)(null),w=(0,o.useRef)(null),T=(0,o.useRef)(null),E=(0,o.useRef)(null),D=(0,o.useRef)(null),O=(0,o.useRef)(r),k=(0,o.useRef)(c);O.current=r,k.current=c;let[A,j]=(0,o.useState)(!1),[M,N]=(0,o.useState)(!1),[P,F]=(0,o.useState)(`0,0`),[I,L]=(0,o.useState)(0);(0,o.useEffect)(()=>{let r=!1,a,o,s,c,l;return(async()=>{try{let d=h(e),f=u(d),[m,g,v,A,M,P,I,R]=await Promise.all([i(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([2,1])),i(()=>import(`./dist-B3-a6uF0.js`).then(e=>e.s),__vite__mapDeps([3,1,2])),i(()=>import(`./dist-CX_Hm4GS.js`),__vite__mapDeps([21,2,1,3,4,0])),i(()=>import(`./dist-scBkrwv-.js`),__vite__mapDeps([22,2,1,3])),i(()=>import(`./dist-J6XWqRpB.js`).then(e=>e.d),__vite__mapDeps([0,1,2,3,4])),i(()=>import(`./dist-Cus6_oaF.js`).then(e=>e.n),__vite__mapDeps([4,1])),f?f().catch(e=>(console.warn(`[CodeMirror] Failed to load language for .${d}:`,e),null)):Promise.resolve(null),n().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null))]);if(r||!b.current)return;c=M,l=P,C.current=m.Annotation.define(),w.current=m.Transaction.addToHistory;let z=t.length<=p&&I!==null;o=new m.Compartment;let B=[g.lineNumbers(),g.highlightActiveLine(),g.drawSelection(),v.history(),g.keymap.of([v.indentWithTab,...v.defaultKeymap,...v.historyKeymap,...A.searchKeymap,{key:`Mod-s`,run:()=>(k.current(),!0)}]),g.EditorView.updateListener.of(e=>{e.docChanged&&!(C.current&&e.transactions.some(e=>e.annotation(C.current)===!0))&&O.current(e.state.doc.toString()),e.selectionSet&&F(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),g.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(y&&B.push(m.EditorState.readOnly.of(!0),g.EditorView.editable.of(!1)),R&&!y&&(s=new m.Compartment,B.splice(1,0,s.of([])),B.push(R.base)),I)try{B.push(I)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${d}:`,e),z=!1}if(z&&o&&c&&l)try{B.push(o.of(c.syntaxHighlighting(_(c,l))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${d}:`,e),z=!1}if(a=new g.EditorView({state:m.EditorState.create({doc:t,extensions:B}),parent:b.current}),r){a.destroy();return}x.current=a,j(z),N(!0),T.current=R,E.current=s??null,D.current=null,L(e=>e+1);let V=new MutationObserver(()=>{let e=x.current;if(e&&z&&o&&c&&l)try{e.dispatch({effects:o.reconfigure(c.syntaxHighlighting(_(c,l)))})}catch{}});S.current=V,V.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),r||N(!0)}})(),()=>{r=!0,S.current?.disconnect(),S.current=null,a?.destroy(),x.current=null,N(!1),b.current&&(b.current.textContent=``)}},[e,y]),(0,o.useEffect)(()=>{let e=x.current;if(!e)return;let n=e.state.doc.toString();n!==t&&e.dispatch({changes:{from:0,to:n.length,insert:t},annotations:C.current?C.current.of(!0):void 0})},[t]),(0,o.useEffect)(()=>{let e=x.current;if(!e||!s)return;let t=e.state.doc.line(Math.min(Math.max(1,s.line),e.state.doc.lines)),n=Math.min(t.to,t.from+(s.column??1)-1);e.dispatch({selection:{anchor:t.to,head:n},scrollIntoView:!0}),e.focus()},[s,M]);let R=!!(g&&g.state===`ready`&&g.response&&g.path===e&&g.workspaceId===l);(0,o.useEffect)(()=>{let t=x.current,n=T.current,r=E.current;if(!t||!n||!r)return;let i=g&&g.state===`ready`&&g.response&&g.path===e&&g.workspaceId===l?g.response:null,o=i?a(i):null;D.current!==o&&(D.current=o,t.dispatch({effects:[n.setBlame.of(o),r.reconfigure(o?n.gutter:[])]}))},[g?.state,g?.response,g?.path,g?.workspaceId,e,l,I]);let z=x.current?.state.doc.toString()??t,B=z.length<=m?z:z.slice(0,m),V=h(e),H=d(V),U=x.current?.state,W=U?.selection.main.head,G=W===void 0?void 0:U?.doc.lineAt(W),K=G?.number,q=W!==void 0&&G?W-G.from+1:void 0;return(0,o.useEffect)(()=>{M&&K!==void 0&&q!==void 0&&v?.({line:K,column:q,language:A&&H||`纯文本`,highlight:A?V:`plain`})},[M,K,q,A,H,V,v]),(0,o.useEffect)(()=>()=>v?.(),[v]),(0,f.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":B,"data-file-content-truncated":z.length>m?`1`:`0`,"data-file-selection":P,"data-file-editor-ready":M?`1`:`0`,"data-file-blame-gutter":R?`1`:void 0,onMouseDown:()=>x.current?.focus(),children:[(0,f.jsx)(`div`,{className:`file-cm`,ref:b,"aria-label":`${y?`查看`:`编辑`} ${e}`}),(!M||!v)&&(0,f.jsxs)(`div`,{className:`file-editor-status`,children:[!M&&(0,f.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),M&&W!==void 0&&G&&(0,f.jsxs)(`span`,{children:[`第 `,G.number,` 行,第 `,W-G.from+1,` 列`]}),M&&!A&&(0,f.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),M&&A&&H&&(0,f.jsx)(`span`,{"data-file-highlight-status":V,children:H})]})]})}export{v as CodeMirrorEditor,u as t,_ as themeHighlightStyle};
|