@evandu/super-pi 0.1.324 → 0.1.326
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/desktop/main.cjs +23 -3
- package/desktop/preload.cjs +7 -0
- package/dist/client/.super-pi-client-sources.json +41 -36
- package/dist/client/assets/CodeMirrorEditor-GWeu0OUL.js +2 -0
- package/dist/client/assets/GitDiffEditor-sc09J8B7.js +31 -0
- package/dist/client/assets/GitHistoricalFile-BwlKi5UX.js +1 -0
- package/dist/client/assets/{dist-D978o95T.js → dist-1rD0ihl2.js} +1 -1
- package/dist/client/assets/{dist-Dfhu-vbV.js → dist-36Vke2EH.js} +1 -1
- package/dist/client/assets/dist-56GF8ANx.js +1 -0
- package/dist/client/assets/{dist-X4BHLQqs.js → dist-BCNE0i_L.js} +1 -1
- package/dist/client/assets/{dist-Qjm1p8SR.js → dist-BWav58GK.js} +1 -1
- package/dist/client/assets/{dist-699T9mBC.js → dist-Bkr3xgoh.js} +1 -1
- package/dist/client/assets/{dist-dybF9Ag8.js → dist-C3S630Ts.js} +1 -1
- package/dist/client/assets/{dist-BXAOrsjq.js → dist-CACYWoKG.js} +1 -1
- package/dist/client/assets/{dist-BqSTJyq9.js → dist-CAM5m6VB.js} +1 -1
- package/dist/client/assets/{dist-BX5MJasK.js → dist-CB-n6qyW.js} +1 -1
- package/dist/client/assets/{dist-DTIPfQj7.js → dist-CD0jGv9h.js} +1 -1
- package/dist/client/assets/{dist-S5ntGzJB.js → dist-Ch-BrJW7.js} +1 -1
- package/dist/client/assets/{dist-BXqtlD7O.js → dist-CjVRUfws.js} +1 -1
- package/dist/client/assets/{dist-gDvn1xVj.js → dist-D5K62raW.js} +1 -1
- package/dist/client/assets/{dist-CVPY8uK1.js → dist-DESLeVIi.js} +1 -1
- package/dist/client/assets/dist-DKp0_dx5.js +23 -0
- package/dist/client/assets/dist-DTem9o2m.js +2 -0
- package/dist/client/assets/dist-DcAKBmUm.js +1 -0
- package/dist/client/assets/{dist-DLNOWOmk.js → dist-DexiWS0i.js} +1 -1
- package/dist/client/assets/dist-Dk-yOCN3.js +3 -0
- package/dist/client/assets/{dist-CAlPBcem.js → dist-IQ81OBbu.js} +1 -1
- package/dist/client/assets/{dist-B2l9cUU9.js → dist-JLvZm5Mv.js} +1 -1
- package/dist/client/assets/editor-blame-DcMUzRBK.js +15 -0
- package/dist/client/assets/editor-blame-PLncD0eu.css +1 -0
- package/dist/client/assets/index-BpMJTeh4.css +1 -0
- package/dist/client/assets/index-Cevzgr74.js +350 -0
- package/dist/client/index.html +4 -3
- package/dist/server/application/provider-service.d.ts +6 -0
- package/dist/server/application/provider-service.js +31 -2
- package/dist/server/git.d.ts +5 -0
- package/dist/server/git.js +21 -1
- package/dist/server/http-server.js +5 -3
- package/dist/server/managed-http-direct.d.ts +1 -1
- package/dist/server/managed-http-direct.js +2 -2
- package/dist/server/managed-http-tunnel.d.ts +1 -1
- package/dist/server/managed-http-tunnel.js +4 -4
- package/dist/server/managed-http.js +51 -2
- package/dist/server/managed-key-sync.d.ts +6 -0
- package/dist/server/managed-key-sync.js +59 -0
- package/dist/server/managed-servers.d.ts +5 -0
- package/dist/server/managed-servers.js +20 -3
- package/dist/server/providers.d.ts +2 -0
- package/dist/server/providers.js +20 -0
- package/dist/shared/model-configuration.d.ts +1 -0
- package/package.json +1 -1
- package/dist/.super-pi-check-inputs.json +0 -4
- package/dist/client/assets/CodeMirrorEditor-eVHUQY8Y.js +0 -2
- package/dist/client/assets/GitDiffEditor-Cebgkg-9.js +0 -31
- package/dist/client/assets/dist-BJHpSQV1.js +0 -1
- package/dist/client/assets/dist-BUY8ZNeZ.js +0 -23
- package/dist/client/assets/dist-Cus6_oaF.js +0 -2
- package/dist/client/assets/dist-DP4hrTBF.js +0 -3
- package/dist/client/assets/dist-Jg3fJuzH.js +0 -1
- package/dist/client/assets/index-A2acEU1u.css +0 -1
- package/dist/client/assets/index-D9r6d2wH.js +0 -363
- package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +0 -1
package/dist/client/index.html
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
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-
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-Cevzgr74.js"></script>
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/editor-blame-DcMUzRBK.js">
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/editor-blame-PLncD0eu.css">
|
|
14
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BpMJTeh4.css">
|
|
14
15
|
</head>
|
|
15
16
|
<body>
|
|
16
17
|
<div id="root"></div>
|
|
17
18
|
|
|
@@ -6,6 +6,7 @@ import type { EventBroadcaster } from "../server-context.js";
|
|
|
6
6
|
import type { CatalogService } from "./catalog-service.js";
|
|
7
7
|
import { ModelDiscovery } from "../model-discovery.js";
|
|
8
8
|
import { discoverPiProviderModels } from "../pi-session.js";
|
|
9
|
+
import type { ProviderKey } from "../managed-key-sync.js";
|
|
9
10
|
/**
|
|
10
11
|
* THE PROVIDERS A PERSON ADDED, as a service.
|
|
11
12
|
*
|
|
@@ -52,6 +53,11 @@ export declare class ProviderService {
|
|
|
52
53
|
remove(providerId: string): Promise<PublicProvider[]>;
|
|
53
54
|
removeModel(providerId: string, modelId: string): Promise<PublicProvider[]>;
|
|
54
55
|
refreshConfiguration(): Promise<void>;
|
|
56
|
+
storedApiKeys(): Promise<ProviderKey[]>;
|
|
57
|
+
importSharedCatalogKeys(entries: ProviderKey[]): Promise<{
|
|
58
|
+
imported: number;
|
|
59
|
+
skipped: number;
|
|
60
|
+
}>;
|
|
55
61
|
setSharedCatalogKey(providerId: string, key: string): Promise<void>;
|
|
56
62
|
private readonly oauthJobs;
|
|
57
63
|
constructor(registry: ProviderRegistry, runtime: AgentRuntime, broadcaster: EventBroadcaster, catalogService: CatalogService, store: Store, discoverModels?: typeof discoverPiProviderModels);
|
|
@@ -6,8 +6,8 @@ import { thinkingLevelsEndpoint } from "../../shared/thinking-levels.js";
|
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import { ModelDiscovery } from "../model-discovery.js";
|
|
8
8
|
import { discoverPiProviderModels } from "../pi-session.js";
|
|
9
|
-
import { activeSharedCatalog } from "../managed-model-adapter.js";
|
|
10
|
-
import { sharedProviderModels } from "../shared-model-catalog.js";
|
|
9
|
+
import { activeSharedCatalog, modelConfigurationMode } from "../managed-model-adapter.js";
|
|
10
|
+
import { sharedProviderModels, validSharedProviderId } from "../shared-model-catalog.js";
|
|
11
11
|
import { piAuthPath } from "../providers.js";
|
|
12
12
|
/**
|
|
13
13
|
* THE PROVIDERS A PERSON ADDED, as a service.
|
|
@@ -92,6 +92,35 @@ export class ProviderService {
|
|
|
92
92
|
async remove(providerId) { return this.mutate(() => this.removeNow(providerId)); }
|
|
93
93
|
async removeModel(providerId, modelId) { return this.mutate(() => this.removeModelNow(providerId, modelId)); }
|
|
94
94
|
async refreshConfiguration() { return this.mutate(() => this.afterChange([], false)); }
|
|
95
|
+
async storedApiKeys() {
|
|
96
|
+
return (await this.registry.storedApiKeys()).filter(([id]) => validSharedProviderId(id));
|
|
97
|
+
}
|
|
98
|
+
async importSharedCatalogKeys(entries) {
|
|
99
|
+
return this.mutate(async () => {
|
|
100
|
+
if (await modelConfigurationMode() !== "shared-catalog")
|
|
101
|
+
throw new Error("请先开启独立鉴权与代理模式。");
|
|
102
|
+
const catalog = sharedProviderModels(await activeSharedCatalog());
|
|
103
|
+
const [configured, disabled] = await Promise.all([this.registry.load(), this.registry.loadDisabled()]);
|
|
104
|
+
const protectedIds = new Set([...configured.filter(item => item.hasAuthKey || item.keyInModelsJson), ...disabled].map(item => item.id));
|
|
105
|
+
const url = new URL("./core/auth-storage.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href;
|
|
106
|
+
const { AuthStorage } = await import(url);
|
|
107
|
+
const storage = AuthStorage.create(piAuthPath(this.registry.agentDir));
|
|
108
|
+
let imported = 0;
|
|
109
|
+
for (const [id, key] of entries) {
|
|
110
|
+
if (!catalog.has(id) || protectedIds.has(id))
|
|
111
|
+
continue;
|
|
112
|
+
await storage.modify(id, async (previous) => {
|
|
113
|
+
if (previous?.type === "oauth" || previous?.key || (previous?.type && previous.type !== "api_key"))
|
|
114
|
+
return previous;
|
|
115
|
+
imported++;
|
|
116
|
+
return { type: "api_key", key, ...(previous?.env ? { env: previous.env } : {}) };
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
if (imported)
|
|
120
|
+
await this.afterChange([], false);
|
|
121
|
+
return { imported, skipped: entries.length - imported };
|
|
122
|
+
});
|
|
123
|
+
}
|
|
95
124
|
async setSharedCatalogKey(providerId, key) {
|
|
96
125
|
return this.mutate(async () => {
|
|
97
126
|
const url = new URL("./core/auth-storage.js", import.meta.resolve("@earendil-works/pi-coding-agent")).href;
|
package/dist/server/git.d.ts
CHANGED
|
@@ -29,6 +29,11 @@ export declare function gitLog(root: string, limit: number, cwd?: string, query?
|
|
|
29
29
|
}>;
|
|
30
30
|
export declare function gitGraph(root: string, limit: number, offset: number, snapshot: string, after: string, knownSnapshot?: string): Promise<GitGraphResponse>;
|
|
31
31
|
export declare function gitCommit(root: string, cwd: string, hash: string): Promise<GitCommitDetail>;
|
|
32
|
+
export declare function gitCommitFile(root: string, cwd: string, hash: string, path: string): Promise<{
|
|
33
|
+
path: string;
|
|
34
|
+
revision: string;
|
|
35
|
+
content: string;
|
|
36
|
+
}>;
|
|
32
37
|
export declare function gitCommitDiff(root: string, cwd: string, hash: string, path: string, fullContext?: boolean): Promise<{
|
|
33
38
|
path: string;
|
|
34
39
|
staged: boolean;
|
package/dist/server/git.js
CHANGED
|
@@ -246,11 +246,31 @@ async function commitSnapshot(root, cwd, revision) {
|
|
|
246
246
|
files.push({ status, path: firstPath });
|
|
247
247
|
}
|
|
248
248
|
}
|
|
249
|
-
return { detail: { hash, parents, message, files }, scope, diff };
|
|
249
|
+
return { detail: { hash, parents, message, files }, repo, scope, diff };
|
|
250
250
|
}
|
|
251
251
|
export async function gitCommit(root, cwd, hash) {
|
|
252
252
|
return (await commitSnapshot(root, cwd, hash)).detail;
|
|
253
253
|
}
|
|
254
|
+
export async function gitCommitFile(root, cwd, hash, path) {
|
|
255
|
+
const { detail, repo, scope } = await commitSnapshot(root, cwd, hash);
|
|
256
|
+
const file = detail.files.find(entry => entry.path === path);
|
|
257
|
+
if (!file)
|
|
258
|
+
throw gitFailure("这个提交没有该文件的改动。", "not_found");
|
|
259
|
+
const revision = file.status.startsWith("D") ? detail.parents[0] : detail.hash;
|
|
260
|
+
if (!revision)
|
|
261
|
+
throw gitFailure("找不到该文件版本。", "not_found");
|
|
262
|
+
const object = `${revision}:${[scope, path].filter(Boolean).join("/")}`;
|
|
263
|
+
const { stdout: metadata } = await git(repo, ["cat-file", "-t", object], { timeout: 12_000 });
|
|
264
|
+
if (metadata.trim() !== "blob")
|
|
265
|
+
throw gitFailure("此 Git 条目无法作为文件打开。", "not_found");
|
|
266
|
+
const { stdout: bytes } = await git(repo, ["cat-file", "-s", object], { timeout: 12_000 });
|
|
267
|
+
if (Number(bytes.trim()) > MAX_FILE_BYTES)
|
|
268
|
+
throw gitFailure("历史文件过大,无法在编辑器中打开。", "file_too_large");
|
|
269
|
+
const { stdout: content } = await git(repo, ["cat-file", "blob", object], { timeout: 12_000, maxBuffer: MAX_FILE_BYTES * 2 });
|
|
270
|
+
if (content.includes("\0"))
|
|
271
|
+
throw gitFailure("此历史版本为二进制文件,无法作为文本打开。", "binary");
|
|
272
|
+
return { path, revision, content };
|
|
273
|
+
}
|
|
254
274
|
export async function gitCommitDiff(root, cwd, hash, path, fullContext = false) {
|
|
255
275
|
if (!path || path.includes("\0"))
|
|
256
276
|
throw gitFailure("请选择提交中的变更文件。", "path");
|
|
@@ -20,7 +20,7 @@ import { describe as describeFilesError, FilesError, fileMeta, listDirectory, MA
|
|
|
20
20
|
import { findUploadFile, MAX_UPLOAD_BODY_BYTES, saveUpload } from "./upload.js";
|
|
21
21
|
import { describeThrown } from "./failure-text.js";
|
|
22
22
|
import { checkDiskVersion, readPackageVersion } from "./version.js";
|
|
23
|
-
import { gitBlame, gitBranches, gitCommit, gitCommitDiff, gitDiff, gitIndexFileContent, gitGraph, gitLog, gitMutate, gitStagedDraftInput, gitStashes, gitStatus, gitWorktrees, resolveGitWorktree, inspectGitWorktree, gitWorktreeCommittedDiff } from "./git.js";
|
|
23
|
+
import { gitBlame, gitBranches, gitCommit, gitCommitDiff, gitCommitFile, gitDiff, gitIndexFileContent, gitGraph, gitLog, gitMutate, gitStagedDraftInput, gitStashes, gitStatus, gitWorktrees, resolveGitWorktree, inspectGitWorktree, gitWorktreeCommittedDiff } from "./git.js";
|
|
24
24
|
import { computeFileDiff } from "./file-diff.js";
|
|
25
25
|
import { verifyCapability } from "./capability.js";
|
|
26
26
|
import { FileReviewThreads } from "./file-review-threads.js";
|
|
@@ -2103,7 +2103,7 @@ export function createHttpServer(options) {
|
|
|
2103
2103
|
}
|
|
2104
2104
|
const sessionRoot = await resolveFileCwd(workspace.path, requestedCwd);
|
|
2105
2105
|
const cwd = relative(resolve(workspace.path), sessionRoot).replaceAll("\\", "/");
|
|
2106
|
-
if (op === "commit-detail" || op === "commit-diff") {
|
|
2106
|
+
if (op === "commit-detail" || op === "commit-diff" || op === "commit-file") {
|
|
2107
2107
|
if (request.method !== "GET") {
|
|
2108
2108
|
json(405, { error: "查看提交需要 GET 请求", code: "method" });
|
|
2109
2109
|
return;
|
|
@@ -2116,8 +2116,10 @@ export function createHttpServer(options) {
|
|
|
2116
2116
|
const root = worktreeId ? (await resolveGitWorktree(workspace.path, worktreeId)).path : workspace.path;
|
|
2117
2117
|
const directory = worktreeId ? "" : cwd;
|
|
2118
2118
|
const hash = url.searchParams.get("hash") ?? "";
|
|
2119
|
+
const path = url.searchParams.get("path") ?? "";
|
|
2119
2120
|
json(200, op === "commit-detail" ? await gitCommit(root, directory, hash)
|
|
2120
|
-
: await
|
|
2121
|
+
: op === "commit-file" ? await gitCommitFile(root, directory, hash, path)
|
|
2122
|
+
: await gitCommitDiff(root, directory, hash, path, fullDiff));
|
|
2121
2123
|
return;
|
|
2122
2124
|
}
|
|
2123
2125
|
// Blame is a read with a GET shape: every other verb is refused HERE, before the POST branch
|
|
@@ -4,6 +4,6 @@ import type { ServiceProbe } from "../shared/managed-servers.js";
|
|
|
4
4
|
export declare function serviceOrigin(value: string): string;
|
|
5
5
|
export declare function defaultServiceOrigin(host: string, port: number): string;
|
|
6
6
|
export declare function probeServiceEndpoint(origin: string, key?: string): Promise<ServiceProbe>;
|
|
7
|
-
export declare function directJson(origin: string, path: string, key: string, method?: string): Promise<Record<string, unknown>>;
|
|
7
|
+
export declare function directJson(origin: string, path: string, key: string, method?: string, body?: string): Promise<Record<string, unknown>>;
|
|
8
8
|
export declare function proxyThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath: string): void;
|
|
9
9
|
export declare function proxyWebSocketThroughDirect(origin: string, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer): void;
|
|
@@ -36,8 +36,8 @@ export async function probeServiceEndpoint(origin, key = "") {
|
|
|
36
36
|
return result({ reachable: false, service: false, authorized: false, message: "未能连接此服务端口。请检查 IP、端口、服务监听地址、防火墙或 TLS 配置;本次未尝试 SSH。" });
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
|
-
export async function directJson(origin, path, key, method = "GET") {
|
|
40
|
-
const response = await fetch(new URL(path, origin), { method, headers: { authorization: `Bearer ${key}
|
|
39
|
+
export async function directJson(origin, path, key, method = "GET", body) {
|
|
40
|
+
const response = await fetch(new URL(path, origin), { method, body, headers: { authorization: `Bearer ${key}`, ...(body ? { "content-type": "application/json" } : {}) }, signal: AbortSignal.timeout(body ? 30000 : 5000), redirect: "error" });
|
|
41
41
|
if (!response.ok || !response.headers.get("content-type")?.includes("application/json"))
|
|
42
42
|
throw new Error(`Super Pi 服务直连检测失败(HTTP ${response.status})`);
|
|
43
43
|
const value = await response.json();
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
2
|
import type { Duplex } from "node:stream";
|
|
3
3
|
import type { Client } from "ssh2";
|
|
4
|
-
export declare function tunnelJson(client: Client, port: number, path: string, key: string, method?: string): Promise<any>;
|
|
4
|
+
export declare function tunnelJson(client: Client, port: number, path: string, key: string, method?: string, body?: string): Promise<any>;
|
|
5
5
|
export declare function proxyThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, response: ServerResponse, basePath?: string, sameOrigin?: boolean): void;
|
|
6
6
|
export declare function proxyWebSocketThroughSsh(client: Client, port: number, key: string, path: string, request: IncomingMessage, socket: Duplex, head: Buffer, sameOrigin?: boolean): Promise<void>;
|
|
@@ -24,10 +24,10 @@ function agentFor(client, port) {
|
|
|
24
24
|
});
|
|
25
25
|
return agent;
|
|
26
26
|
}
|
|
27
|
-
export async function tunnelJson(client, port, path, key, method = "GET") {
|
|
27
|
+
export async function tunnelJson(client, port, path, key, method = "GET", body) {
|
|
28
28
|
return new Promise((resolve, reject) => {
|
|
29
29
|
const agent = agentFor(client, port);
|
|
30
|
-
const request = httpRequest({ hostname: "127.0.0.1", port, path, method, agent, headers: { authorization: `Bearer ${key}
|
|
30
|
+
const request = httpRequest({ hostname: "127.0.0.1", port, path, method, agent, headers: { authorization: `Bearer ${key}`, ...(body ? { "content-type": "application/json", "content-length": Buffer.byteLength(body) } : {}) } }, response => {
|
|
31
31
|
let text = "";
|
|
32
32
|
response.setEncoding("utf8");
|
|
33
33
|
response.on("data", chunk => { text += chunk; if (text.length > 8 * 1024 * 1024)
|
|
@@ -41,10 +41,10 @@ export async function tunnelJson(client, port, path, key, method = "GET") {
|
|
|
41
41
|
reject(new Error(`远端服务未返回有效状态(${response.statusCode})`));
|
|
42
42
|
} });
|
|
43
43
|
});
|
|
44
|
-
const timeout = setTimeout(() => request.destroy(new Error("远端服务响应超时")), 12_000);
|
|
44
|
+
const timeout = setTimeout(() => request.destroy(new Error("远端服务响应超时")), body ? 30_000 : 12_000);
|
|
45
45
|
request.once("close", () => clearTimeout(timeout));
|
|
46
46
|
request.once("error", () => { agent.destroy(); reject(new Error("SSH 隧道无法访问远端 Super Pi 端口")); });
|
|
47
|
-
request.end();
|
|
47
|
+
request.end(body);
|
|
48
48
|
});
|
|
49
49
|
}
|
|
50
50
|
export function proxyThroughSsh(client, port, key, path, request, response, basePath = "", sameOrigin = false) {
|
|
@@ -5,6 +5,7 @@ import { rename, writeFile, rm } from "node:fs/promises";
|
|
|
5
5
|
import { modelConfigurationMode, modelConfigurationModePath, readManagedModelConfig } from "./managed-model-adapter.js";
|
|
6
6
|
import { isModelConfigurationMode } from "../shared/model-configuration.js";
|
|
7
7
|
import { sharedCatalogModels, sharedProviderModels, validSharedProviderId } from "./shared-model-catalog.js";
|
|
8
|
+
import { createKeySyncChallenge, keySyncPayloadLimit, openProviderKeys } from "./managed-key-sync.js";
|
|
8
9
|
async function writeAtomic(path, content) {
|
|
9
10
|
const temp = path + "." + randomUUID() + ".tmp";
|
|
10
11
|
try {
|
|
@@ -21,14 +22,56 @@ export async function handleManagedHttp(context, request, response, url) {
|
|
|
21
22
|
const proxy = /^\/managed\/([a-f0-9-]+)(\/.*)$/.exec(url.pathname);
|
|
22
23
|
const syncCatalog = url.pathname === "/api/managed-model/catalog";
|
|
23
24
|
const modeRoute = url.pathname === "/api/managed-model/mode";
|
|
24
|
-
|
|
25
|
+
const keyRoute = url.pathname === "/api/managed-model/keys";
|
|
26
|
+
if (!route && !proxy && !syncCatalog && !modeRoute && !keyRoute && url.pathname !== "/api/managed-model/reload")
|
|
25
27
|
return false;
|
|
26
28
|
const json = (status, value) => { response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }).end(JSON.stringify(value)); };
|
|
29
|
+
if (keyRoute) {
|
|
30
|
+
if (!isBrowserAuthorized(request) || !modelConfigurationModePath()) {
|
|
31
|
+
json(403, { error: "API Key 同步需要配对服务器授权。" });
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
if (await modelConfigurationMode() !== "shared-catalog") {
|
|
35
|
+
json(409, { error: "请先开启独立鉴权与代理模式。" });
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
if (request.method === "GET") {
|
|
39
|
+
json(200, { challenge: createKeySyncChallenge() });
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
if (request.method !== "POST") {
|
|
43
|
+
json(405, { error: "仅支持 GET/POST" });
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
const parts = [];
|
|
48
|
+
let bytes = 0;
|
|
49
|
+
for await (const chunk of request) {
|
|
50
|
+
bytes += chunk.length;
|
|
51
|
+
if (bytes > keySyncPayloadLimit) {
|
|
52
|
+
json(413, { error: "API Key 同步数据过大。" });
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
parts.push(chunk);
|
|
56
|
+
}
|
|
57
|
+
const config = await readManagedModelConfig();
|
|
58
|
+
if (!config) {
|
|
59
|
+
json(409, { error: "缺少配对配置。" });
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
const entries = openProviderKeys(config.token, JSON.parse(Buffer.concat(parts).toString("utf8")));
|
|
63
|
+
json(200, await context.providerService.importSharedCatalogKeys(entries));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
json(400, { error: "API Key 同步未完成,请确认配对并重试。" });
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
27
70
|
if (modeRoute) {
|
|
28
71
|
const path = modelConfigurationModePath();
|
|
29
72
|
const status = async () => {
|
|
30
73
|
const config = await readManagedModelConfig();
|
|
31
|
-
return { paired: Boolean(path), mode: await modelConfigurationMode(), syncedAt: config?.sharedCatalogAt, skippedModels: config?.sharedCatalogSkipped,
|
|
74
|
+
return { paired: Boolean(path), mode: await modelConfigurationMode(), syncedAt: config?.sharedCatalogAt, skippedModels: config?.sharedCatalogSkipped, keySyncSupported: Boolean(config),
|
|
32
75
|
providers: [...sharedProviderModels(config?.sharedModels ?? [])].map(([id, models]) => ({ id, modelCount: models.length })) };
|
|
33
76
|
};
|
|
34
77
|
if (!path) {
|
|
@@ -173,6 +216,12 @@ export async function handleManagedHttp(context, request, response, url) {
|
|
|
173
216
|
json(200, { ...status(), probe: await context.managedServers.probeService(profile) });
|
|
174
217
|
return true;
|
|
175
218
|
}
|
|
219
|
+
if (body.action === "syncProviderKeys") {
|
|
220
|
+
if (typeof body.id !== "string")
|
|
221
|
+
throw new Error("请选择服务器");
|
|
222
|
+
json(200, { keySync: await context.managedServers.syncProviderKeys(body.id, await context.providerService.storedApiKeys()) });
|
|
223
|
+
return true;
|
|
224
|
+
}
|
|
176
225
|
if (body.action === "save") {
|
|
177
226
|
await context.managedServers.save(body.profile);
|
|
178
227
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export declare const keySyncPayloadLimit: number;
|
|
2
|
+
export type ProviderKey = [provider: string, key: string];
|
|
3
|
+
export declare const isStoredLiteralKey: (key: unknown) => key is string;
|
|
4
|
+
export declare function createKeySyncChallenge(): string;
|
|
5
|
+
export declare function sealProviderKeys(token: string, challenge: unknown, entries: ProviderKey[]): string;
|
|
6
|
+
export declare function openProviderKeys(token: string, body: unknown): ProviderKey[];
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from "node:crypto";
|
|
2
|
+
import { validSharedProviderId } from "./shared-model-catalog.js";
|
|
3
|
+
const actions = new Map();
|
|
4
|
+
const lifetime = 60_000;
|
|
5
|
+
export const keySyncPayloadLimit = 1024 * 1024;
|
|
6
|
+
export const isStoredLiteralKey = (key) => typeof key === "string" && key.trim().length > 0 &&
|
|
7
|
+
key.length <= 8192 && !key.includes("$") && !key.startsWith("!");
|
|
8
|
+
const isChallenge = (value) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value);
|
|
9
|
+
export function createKeySyncChallenge() {
|
|
10
|
+
const now = Date.now();
|
|
11
|
+
for (const [value, expiresAt] of actions)
|
|
12
|
+
if (expiresAt <= now)
|
|
13
|
+
actions.delete(value);
|
|
14
|
+
if (actions.size >= 32)
|
|
15
|
+
actions.delete(actions.keys().next().value);
|
|
16
|
+
const challenge = randomBytes(32).toString("hex");
|
|
17
|
+
actions.set(challenge, now + lifetime);
|
|
18
|
+
return challenge;
|
|
19
|
+
}
|
|
20
|
+
function encryptionKey(token, challenge) {
|
|
21
|
+
return Buffer.from(hkdfSync("sha256", token, Buffer.from(challenge, "hex"), "Super Pi paired provider key sync v1", 32));
|
|
22
|
+
}
|
|
23
|
+
export function sealProviderKeys(token, challenge, entries) {
|
|
24
|
+
if (!isChallenge(challenge))
|
|
25
|
+
throw new Error("远端没有返回有效的 API Key 同步验证。");
|
|
26
|
+
const iv = randomBytes(12);
|
|
27
|
+
const cipher = createCipheriv("aes-256-gcm", encryptionKey(token, challenge), iv);
|
|
28
|
+
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(entries), "utf8"), cipher.final()]);
|
|
29
|
+
const body = JSON.stringify({ challenge, iv: iv.toString("hex"), tag: cipher.getAuthTag().toString("hex"), ciphertext: ciphertext.toString("base64") });
|
|
30
|
+
if (Buffer.byteLength(body) > keySyncPayloadLimit)
|
|
31
|
+
throw new Error("本次 API Key 同步数据过大。");
|
|
32
|
+
return body;
|
|
33
|
+
}
|
|
34
|
+
export function openProviderKeys(token, body) {
|
|
35
|
+
const value = body;
|
|
36
|
+
if (!value || !isChallenge(value.challenge) || typeof value.iv !== "string" || !/^[0-9a-f]{24}$/.test(value.iv) ||
|
|
37
|
+
typeof value.tag !== "string" || !/^[0-9a-f]{32}$/.test(value.tag) || typeof value.ciphertext !== "string") {
|
|
38
|
+
throw new Error("无效的 API Key 同步数据。");
|
|
39
|
+
}
|
|
40
|
+
const expiresAt = actions.get(value.challenge) ?? 0;
|
|
41
|
+
actions.delete(value.challenge);
|
|
42
|
+
if (expiresAt <= Date.now())
|
|
43
|
+
throw new Error("API Key 同步验证已失效,请重试。");
|
|
44
|
+
let entries;
|
|
45
|
+
try {
|
|
46
|
+
const decipher = createDecipheriv("aes-256-gcm", encryptionKey(token, value.challenge), Buffer.from(value.iv, "hex"));
|
|
47
|
+
decipher.setAuthTag(Buffer.from(value.tag, "hex"));
|
|
48
|
+
const cleartext = Buffer.concat([decipher.update(Buffer.from(value.ciphertext, "base64")), decipher.final()]);
|
|
49
|
+
entries = JSON.parse(cleartext.toString("utf8"));
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
throw new Error("无法验证 API Key 同步数据,请检查服务器配对。");
|
|
53
|
+
}
|
|
54
|
+
if (!Array.isArray(entries) || entries.length > 512 || !entries.every(entry => Array.isArray(entry) && entry.length === 2 && validSharedProviderId(entry[0]) &&
|
|
55
|
+
isStoredLiteralKey(entry[1]))) {
|
|
56
|
+
throw new Error("无效的 API Key 同步数据。");
|
|
57
|
+
}
|
|
58
|
+
return entries;
|
|
59
|
+
}
|
|
@@ -2,6 +2,7 @@ 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
|
+
import { type ProviderKey } from "./managed-key-sync.js";
|
|
5
6
|
interface EntryIntegrations {
|
|
6
7
|
available(): {
|
|
7
8
|
web: boolean;
|
|
@@ -104,6 +105,10 @@ export declare class ManagedServers {
|
|
|
104
105
|
private reverseModelChannel;
|
|
105
106
|
private restoreModelChannel;
|
|
106
107
|
private serviceJson;
|
|
108
|
+
syncProviderKeys(id: string, entries: ProviderKey[]): Promise<{
|
|
109
|
+
imported: any;
|
|
110
|
+
skipped: any;
|
|
111
|
+
}>;
|
|
107
112
|
syncModels(id: string, force?: boolean, reload?: boolean): Promise<void>;
|
|
108
113
|
private health;
|
|
109
114
|
private checkDirect;
|
|
@@ -15,6 +15,7 @@ import { installRemote, startRemote, stopRemote } from "./remote-bootstrap.js";
|
|
|
15
15
|
import { discoverManagedInstallations, recoverySummary } from "./managed-recovery.js";
|
|
16
16
|
import { isServiceListenHost } from "../shared/managed-servers.js";
|
|
17
17
|
import { isModelConfigurationMode } from "../shared/model-configuration.js";
|
|
18
|
+
import { sealProviderKeys } from "./managed-key-sync.js";
|
|
18
19
|
import { discoverExistingInstallation } from "./existing-service.js";
|
|
19
20
|
import { publishedServerUpdate } from "./published-server-update.js";
|
|
20
21
|
import { directJson, serviceOrigin, defaultServiceOrigin, probeServiceEndpoint, proxyThroughDirect, proxyWebSocketThroughDirect } from "./managed-http-direct.js";
|
|
@@ -401,16 +402,32 @@ export class ManagedServers {
|
|
|
401
402
|
entry.profile.modelError = error instanceof Error ? error.message : "模型同步失败";
|
|
402
403
|
}
|
|
403
404
|
}
|
|
404
|
-
serviceJson(entry, path, method = "GET") {
|
|
405
|
+
serviceJson(entry, path, method = "GET", body) {
|
|
405
406
|
const profile = entry.profile, secret = this.secrets.get(profile.id);
|
|
406
407
|
if (!secret)
|
|
407
408
|
throw new Error("缺少服务访问配置");
|
|
408
409
|
if (profile.transport === "direct" && profile.serviceUrl)
|
|
409
|
-
return directJson(profile.serviceUrl, path, secret.browserKey, method);
|
|
410
|
+
return directJson(profile.serviceUrl, path, secret.browserKey, method, body);
|
|
410
411
|
const client = this.clients.get(profile.id);
|
|
411
412
|
if (!client || !profile.allowServiceTunnel || profile.transport !== "ssh")
|
|
412
413
|
throw new Error("没有可用的服务访问通道");
|
|
413
|
-
return tunnelJson(client, profile.servicePort, path, secret.browserKey, method);
|
|
414
|
+
return tunnelJson(client, profile.servicePort, path, secret.browserKey, method, body);
|
|
415
|
+
}
|
|
416
|
+
async syncProviderKeys(id, entries) {
|
|
417
|
+
const entry = this.entry(id);
|
|
418
|
+
const secret = this.secrets.get(id);
|
|
419
|
+
if (!secret || !entry.installation || !entry.profile.enabled)
|
|
420
|
+
throw new Error("请选择已配对且启用的服务器。");
|
|
421
|
+
if (entries.length === 0)
|
|
422
|
+
return { imported: 0, skipped: 0 };
|
|
423
|
+
if (entries.length > 512)
|
|
424
|
+
throw new Error("入口供应商数量超过本次同步上限。");
|
|
425
|
+
const path = "/api/managed-model/keys";
|
|
426
|
+
const { challenge } = await this.serviceJson(entry, path);
|
|
427
|
+
const result = await this.serviceJson(entry, path, "POST", sealProviderKeys(secret.modelToken, challenge, entries));
|
|
428
|
+
if (!Number.isSafeInteger(result.imported) || !Number.isSafeInteger(result.skipped))
|
|
429
|
+
throw new Error("远端没有确认 API Key 同步结果。");
|
|
430
|
+
return { imported: result.imported, skipped: result.skipped };
|
|
414
431
|
}
|
|
415
432
|
async syncModels(id, force = false, reload = true) {
|
|
416
433
|
const entry = this.entry(id), client = this.clients.get(id), secret = this.secrets.get(id);
|
|
@@ -179,6 +179,8 @@ export declare function stripJsonComments(text: string): string;
|
|
|
179
179
|
export declare class ProviderRegistry {
|
|
180
180
|
private readonly dataDir;
|
|
181
181
|
private readonly piDir;
|
|
182
|
+
/** Export stored API keys only. Config expressions and OAuth refresh material stay on their owner. */
|
|
183
|
+
storedApiKeys(): Promise<[string, string][]>;
|
|
182
184
|
/**
|
|
183
185
|
* `piDir` is Pi's own configuration directory, and it is a PARAMETER rather than a lookup at
|
|
184
186
|
* write time for one reason: a test that forgets to set `PI_CODING_AGENT_DIR` would then write to
|
package/dist/server/providers.js
CHANGED
|
@@ -8,6 +8,7 @@ import { hasStoredCredential, publicProviderNetwork, updateProviderNetwork, Prov
|
|
|
8
8
|
import { supportsProviderProxy } from "../shared/provider-network.js";
|
|
9
9
|
import { isThinkingLevel, readThinkingLevelMap } from "../shared/thinking-levels.js";
|
|
10
10
|
import { discoverThinkingLevels } from "./thinking-level-discovery.js";
|
|
11
|
+
import { isStoredLiteralKey } from "./managed-key-sync.js";
|
|
11
12
|
const unsupportedProxy = (provider) => !supportsProviderProxy(provider);
|
|
12
13
|
/**
|
|
13
14
|
* The API adapters Pi ships, as the ids a provider may name.
|
|
@@ -273,6 +274,25 @@ function toPiProvider(provider, existing) {
|
|
|
273
274
|
export class ProviderRegistry {
|
|
274
275
|
dataDir;
|
|
275
276
|
piDir;
|
|
277
|
+
/** Export stored API keys only. Config expressions and OAuth refresh material stay on their owner. */
|
|
278
|
+
async storedApiKeys() {
|
|
279
|
+
const [registry, auth, models] = await Promise.all([
|
|
280
|
+
this.readRegistry(), readJsonFile(piAuthPath(this.piDir)),
|
|
281
|
+
readJsonFile(piModelsPath(this.piDir)),
|
|
282
|
+
]);
|
|
283
|
+
const disabled = new Set(registry.disabled.map(item => item.id));
|
|
284
|
+
const keys = new Map();
|
|
285
|
+
for (const [id, config] of Object.entries(models?.providers ?? {})) {
|
|
286
|
+
const key = config?.apiKey;
|
|
287
|
+
if (!disabled.has(id) && !Object.hasOwn(auth ?? {}, id) && isStoredLiteralKey(key))
|
|
288
|
+
keys.set(id, key);
|
|
289
|
+
}
|
|
290
|
+
for (const [id, credential] of Object.entries(auth ?? {})) {
|
|
291
|
+
if (!disabled.has(id) && credential?.type === "api_key" && isStoredLiteralKey(credential.key))
|
|
292
|
+
keys.set(id, credential.key);
|
|
293
|
+
}
|
|
294
|
+
return [...keys];
|
|
295
|
+
}
|
|
276
296
|
/**
|
|
277
297
|
* `piDir` is Pi's own configuration directory, and it is a PARAMETER rather than a lookup at
|
|
278
298
|
* write time for one reason: a test that forgets to set `PI_CODING_AGENT_DIR` would then write to
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-D978o95T.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-DTIPfQj7.js","assets/dist-S5ntGzJB.js","assets/dist-Cus6_oaF.js","assets/dist-DP4hrTBF.js","assets/dist-Qjm1p8SR.js","assets/dist-BJHpSQV1.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{C as t,E as n,S as r,T as i,c as a,d as o,f as s,i as c,l,r as u,s as d,u as f,w as p}from"./index-D9r6d2wH.js";var m=e(n(),1);function ee(e,t,n,r){return[n.EditorView.decorations.compute([`selection`,`doc`],e=>n.Decoration.set(e.selection.ranges.filter(e=>!e.empty).map(e=>n.Decoration.mark({class:`cm-workbench-selectedText`}).range(e.from,e.to)),!0)),n.ViewPlugin.define(e=>{let n=null,i,a=!1,s=e=>{n&&(e===`expanded`?(a=!a,l()):n.querySelector(`input[name="${e===`caseSensitive`?`case`:e===`wholeWord`?`word`:`re`}"]`)?.click())},c=e=>{let t=f(e);t&&(e.preventDefault(),e.stopPropagation(),s(t))},l=()=>{if(!n||!i)return;let r=t.getSearchQuery(e.state);if(n.dataset.editorSearchExpanded=String(a),i.update({caseSensitive:r.caseSensitive,wholeWord:r.wholeWord,regexp:r.regexp,expanded:a}),n.querySelector(`[data-find-error]`)?.remove(),r.search&&!r.valid){let e=document.createElement(`output`);e.dataset.findError=``,e.setAttribute(`role`,`alert`),e.textContent=`正则表达式无效`,n.append(e)}},u=()=>{let u=r.querySelector(`.cm-panel.cm-search`);if(u===n)return;if(n?.removeEventListener(`keydown`,c,!0),i?.destroy(),n=u,!n){i=void 0;return}for(let[e,t,r]of[[`next`,`↓`,`下一处`],[`prev`,`↑`,`上一处`]]){let i=n.querySelector(`button[name="${e}"]`);i&&(i.textContent=t,i.setAttribute(`aria-label`,r),i.title=r)}let d=document.createElement(`span`);d.dataset.findControls=``,n.prepend(d);let f=t.getSearchQuery(e.state);a=!1,i=o(d,{...f,expanded:a},s),n.addEventListener(`keydown`,c,!0),l()},d=new MutationObserver(u);return d.observe(r,{childList:!0,subtree:!0}),u(),{update(){l()},destroy(){d.disconnect(),n?.removeEventListener(`keydown`,c,!0),i?.destroy()}}}),e.Prec.highest(n.keymap.of([{key:`Mod-Shift-l`,run:t.selectSelectionMatches},{key:`Mod-h`,scope:`editor search-panel`,run:e=>(t.searchPanelOpen(e.state)||t.openSearchPanel(e),requestAnimationFrame(()=>{e.dom.isConnected&&r.querySelector(`[data-editor-search-options][aria-expanded="false"]`)?.click()}),!0)},...[`c`,`w`,`r`].map(e=>({key:`Alt-${e}`,run:n=>{t.searchPanelOpen(n.state)||t.openSearchPanel(n);let r=t.getSearchQuery(n.state);return n.dispatch({effects:t.setSearchQuery.of(new t.SearchQuery({...r,...e===`c`?{caseSensitive:!r.caseSensitive}:e===`w`?{wholeWord:!r.wholeWord}:{regexp:!r.regexp}}))}),!0}}))])),n.panels({topContainer:r}),n.EditorView.scrollMargins.of(()=>({top:r.querySelector(`.cm-search`)?Math.min(r.getBoundingClientRect().height+8,Math.max(0,(r.parentElement?.clientHeight??0)-32)):0})),t.highlightSelectionMatches({wholeWords:!0,minSelectionLength:1,maxMatches:1e3}),t.search({top:!0}),e.EditorState.phrases.of({Find:`查找`,Replace:`替换为`,next:`下一处`,previous:`上一处`,all:`全部选中`,"match case":`区分大小写`,regexp:`正则表达式`,"by word":`全词匹配`,replace:`替换`,"replace all":`全部替换`,close:`关闭查找`,"current match":`当前匹配`,"on line":`所在行`})]}function te(e,t,n,r,i){let o=new e.Compartment,s=()=>{let r=d();return[e.EditorState.tabSize.of(r.tabSize),n.indentUnit.of(r.indent===`tabs`?` `:` `.repeat(r.tabSize)),r.wrap?t.EditorView.lineWrapping:[],r.whitespace?[t.highlightWhitespace(),t.highlightTrailingWhitespace()]:[]]};return[e.EditorState.allowMultipleSelections.of(!0),t.rectangularSelection(),t.crosshairCursor({key:`Alt`}),e.EditorState.phrases.of({"folded code":`已折叠代码`,unfold:`展开代码`,"Fold line":`折叠代码`,"Unfold line":`展开代码`}),t.highlightActiveLineGutter(),t.highlightSpecialChars(),t.dropCursor(),n.bracketMatching(),n.indentOnInput(),n.foldGutter(),r.closeBrackets(),e.Prec.highest(t.keymap.of([...r.closeBracketsKeymap,...n.foldKeymap,{key:`Alt-z`,run:()=>(a({wrap:!d().wrap}),!0)},{key:`Mod-Shift-z`,run:i.redo},{key:`Mod-y`,run:i.redo}])),o.of(s()),t.ViewPlugin.define(e=>({destroy:l(()=>{e.dispatch({effects:o.reconfigure(s())})})}))]}var h=new Map;function ne(e){let t=h.get(e);return t&&(h.delete(e),h.set(e,t)),t}function g(e,t){h.delete(e),h.set(e,t);let n=[...h.values()].reduce((e,t)=>e+t.state.doc.length,0);for(;h.size>32||n>16777216;){let e=h.keys().next().value;n-=h.get(e).state.doc.length,h.delete(e)}}var _=i(),re=262144,v=131072;function ie(e){return e.split(`.`).pop()?.toLowerCase()??``}function y(e,t,n=!1){let r=e=>n?`var(--git-diff-${e.slice(5)}, var(${e}))`:`var(${e})`;return e.HighlightStyle.define([{tag:t.tags.keyword,color:r(`--cm-keyword`)},{tag:t.tags.string,color:r(`--cm-string`)},{tag:t.tags.number,color:r(`--cm-number`)},{tag:t.tags.comment,color:r(`--cm-comment`),fontStyle:`italic`},{tag:t.tags.function(t.tags.variableName),color:r(`--cm-function`)},{tag:t.tags.typeName,color:r(`--cm-type`)},{tag:t.tags.className,color:r(`--cm-type`)},{tag:t.tags.propertyName,color:r(`--cm-property`)},{tag:t.tags.operator,color:r(`--cm-operator`)},{tag:t.tags.variableName,color:r(`--cm-variable`)}])}function b({path:e,value:n,onChange:i,jumpToLine:a,onSave:o,workspaceId:l,cwd:d=``,blame:f,onPosition:h,onView:b,readOnly:x=!1,languageOverride:S,onReviewLine:C}){let w=(0,m.useRef)(null),T=(0,m.useRef)(null),E=(0,m.useRef)(null),ae=(0,m.useRef)(null),D=JSON.stringify([l,d,e]),O=(0,m.useRef)(void 0),k=(0,m.useRef)(null),A=(0,m.useRef)(null),oe=(0,m.useRef)(null),j=(0,m.useRef)(null),M=(0,m.useRef)(null),N=(0,m.useRef)(null),P=(0,m.useRef)(i),F=(0,m.useRef)(o),I=(0,m.useRef)(n);I.current=n;let L=(0,m.useRef)(!1),R=(0,m.useRef)(b);R.current=b;let z=(0,m.useRef)(C);z.current=C;let B=!!C;P.current=i,F.current=o;let[V,se]=(0,m.useState)(!1),[H,U]=(0,m.useState)(!1),[W,ce]=(0,m.useState)(`0,0`),[G,le]=(0,m.useState)(0),[K,ue]=(0,m.useState)(1);(0,m.useEffect)(()=>{let r=!1,i,a,o,l,u;return(async()=>{try{let d=S??ie(e),f=t(d),[m,h,g,_,v,b,C,V,H]=await Promise.all([p(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([0,1])),p(()=>import(`./dist-DTIPfQj7.js`).then(e=>e.s),__vite__mapDeps([2,1,0])),p(()=>import(`./dist-S5ntGzJB.js`),__vite__mapDeps([3,0,1,2,4,5])),p(()=>import(`./dist-Qjm1p8SR.js`),__vite__mapDeps([6,0,1,2])),p(()=>import(`./dist-DP4hrTBF.js`).then(e=>e.d),__vite__mapDeps([5,1,0,2,4])),p(()=>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),c().catch(e=>(console.warn(`[CodeMirror] Failed to build the blame extension:`,e),null)),p(()=>import(`./dist-BJHpSQV1.js`).then(e=>e.r),__vite__mapDeps([7,1,0,2,5,4]))]);if(r||!w.current||!T.current)return;ae.current=h.EditorView,l=v,u=b,A.current=m.Annotation.define(),oe.current=m.Transaction.addToHistory;let W=n.length<=re&&C!==null;a=new m.Compartment;let G=[h.lineNumbers(),h.highlightActiveLine(),h.drawSelection(),g.history(),h.keymap.of([g.indentWithTab,...g.defaultKeymap,...g.historyKeymap,..._.searchKeymap,{key:`Mod-s`,run:()=>(F.current(),!0)}]),h.EditorView.updateListener.of(e=>{e.docChanged&&!(A.current&&e.transactions.some(e=>e.annotation(A.current)===!0))&&P.current(e.state.doc.toString()),e.selectionSet&&ce(`${e.state.selection.main.from},${e.state.selection.main.to}`)}),h.EditorView.domEventHandlers({mousedown:(e,t)=>(t.focus(),!1)})];if(B&&G.push(s(h,e=>z.current?.(e),`file`)),G.push(h.EditorView.updateListener.of(e=>{e.selectionSet&&ue(e.state.selection.ranges.length),e.docChanged?L.current=!1:e.selectionSet&&(L.current=e.transactions.some(e=>e.isUserEvent(`select.search`)||e.isUserEvent(`select.pointer`)))}),ee(m,_,h,T.current),te(m,h,v,H,g)),x&&G.push(m.EditorState.readOnly.of(!0),h.EditorView.editable.of(!1),h.EditorView.contentAttributes.of({tabindex:`0`})),V&&!x&&(o=new m.Compartment,G.splice(1,0,o.of([])),G.push(V.base)),C)try{G.push(C)}catch(e){console.warn(`[CodeMirror] Failed to apply language extension for .${d}:`,e),W=!1}if(W&&a&&l&&u)try{G.push(a.of(l.syntaxHighlighting(y(l,u))))}catch(e){console.warn(`[CodeMirror] Failed to attach syntaxHighlighting for .${d}:`,e),W=!1}let K=ne(D),q=K&&K.state.doc.toString()===I.current,J=q?K.state.update({effects:m.StateEffect.reconfigure.of(G)}).state:m.EditorState.create({doc:I.current,extensions:G});if(i=new h.EditorView({state:J,parent:w.current}),O.current=q?K.jump:void 0,ue(i.state.selection.ranges.length),ce(`${i.state.selection.main.from},${i.state.selection.main.to}`),q&&(i.scrollDOM.scrollTop=K.top,i.scrollDOM.scrollLeft=K.left,O.current=K.jump),r){i.destroy();return}E.current=i,R.current?.(i),se(W),U(!0),j.current=V,M.current=o??null,N.current=null,le(e=>e+1);let Y=new MutationObserver(()=>{let e=E.current;if(e&&W&&a&&l&&u)try{e.dispatch({effects:a.reconfigure(l.syntaxHighlighting(y(l,u)))})}catch{}});k.current=Y,Y.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]})}catch(e){console.error(`[CodeMirror] Fatal editor initialization error:`,e),r||U(!0)}})(),()=>{r=!0,k.current?.disconnect(),k.current=null,i&&g(D,{state:i.state,top:i.scrollDOM.scrollTop,left:i.scrollDOM.scrollLeft,jump:O.current}),i?.destroy(),E.current=null,R.current?.(),U(!1),w.current&&(w.current.textContent=``)}},[D,x,S,B]),(0,m.useEffect)(()=>{let e=E.current;if(!e)return;let t=e.state.doc.toString();t!==n&&e.dispatch({changes:{from:0,to:t.length,insert:n},annotations:A.current?A.current.of(!0):void 0})},[n,H]),(0,m.useEffect)(()=>{let e=E.current;if(!e||!a||O.current===a.request)return;O.current=a.request;let t=e.state.doc.line(Math.min(Math.max(1,a.line),e.state.doc.lines)),n=Math.min(t.to,t.from+(a.column??1)-1);e.dispatch({selection:{anchor:t.to,head:n},effects:ae.current?.scrollIntoView(n,{y:`start`,yMargin:Math.round(e.scrollDOM.clientHeight/3)})}),e.focus()},[a,H]);let q=!!(f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===l);(0,m.useEffect)(()=>{let t=E.current,n=j.current,r=M.current;if(!t||!n||!r)return;let i=f&&f.state===`ready`&&f.response&&f.path===e&&f.workspaceId===l?f.response:null,a=i?u(i):null;N.current!==a&&(N.current=a,t.dispatch({effects:[n.setBlame.of(a),r.reconfigure(a?n.gutter:[])]}))},[f?.state,f?.response,f?.path,f?.workspaceId,e,l,G]);let J=E.current?.state.doc.toString()??n,Y=J.length<=v?J:J.slice(0,v),X=S??ie(e),Z=r(X),de=E.current?.state,Q=de?.selection.main.head,$=Q===void 0?void 0:de?.doc.lineAt(Q),fe=$?.number,pe=Q!==void 0&&$?Q-$.from+1:void 0;return(0,m.useEffect)(()=>{let e=E.current;if(H&&e&&(!a||O.current===a.request)){let t=e.state.selection.main.head,n=e.state.doc.lineAt(t);h?.({line:n.number,column:t-n.from+1,language:V&&Z||`纯文本`,highlight:V?X:`plain`,navigation:L.current,selections:e.state.selection.ranges.length})}},[H,fe,pe,V,Z,X,h,K,a?.request]),(0,m.useEffect)(()=>()=>h?.(),[h]),(0,_.jsxs)(`div`,{className:`file-cm-wrap`,"data-file-text":e,"data-file-content":Y,"data-file-content-truncated":J.length>v?`1`:`0`,"data-file-selection":W,"data-editor-selection-count":K,"data-file-editor-ready":H?`1`:`0`,"data-file-blame-gutter":q?`1`:void 0,onMouseDown:e=>{e.target.closest(`.cm-panels`)||E.current?.focus()},children:[(0,_.jsx)(`div`,{className:`file-cm`,ref:w,"aria-label":`${x?`查看`:`编辑`} ${e}`}),(0,_.jsx)(`div`,{className:`workbench-editor-search`,ref:T,"data-editor-find-host":`file`}),(!H||!h)&&(0,_.jsxs)(`div`,{className:`file-editor-status`,children:[!H&&(0,_.jsx)(`span`,{"data-file-editor-loading":`1`,children:`正在加载编辑器…`}),H&&Q!==void 0&&$&&(0,_.jsxs)(`span`,{children:[`第 `,$.number,` 行,第 `,Q-$.from+1,` 列`]}),H&&!V&&(0,_.jsx)(`span`,{"data-file-highlight-status":`plain`,children:`纯文本`}),H&&V&&Z&&(0,_.jsx)(`span`,{"data-file-highlight-status":X,children:Z})]})]})}export{b as CodeMirrorEditor,ee as n,te as t,y as themeHighlightStyle};
|