@evandu/super-pi 0.1.325 → 0.1.327
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 +13 -0
- package/dist/client/.super-pi-client-sources.json +20 -16
- package/dist/client/assets/CodeMirrorEditor-BslZa6Te.js +2 -0
- package/dist/client/assets/FileWorkbenchChrome-opMS3cZ5.js +1 -0
- package/dist/client/assets/GitDiffEditor-DrWsJi0Q.js +31 -0
- package/dist/client/assets/GitHistoricalFile-B_GSmox7.js +1 -0
- package/dist/client/assets/{dist-roKXy-A5.js → dist-B01U6Kqm.js} +1 -1
- package/dist/client/assets/dist-B7BIlMIZ.js +1 -0
- package/dist/client/assets/{dist-DtR0Z34F.js → dist-BL4zqiB3.js} +1 -1
- package/dist/client/assets/{dist-DtL03oMV.js → dist-BcAL7bRJ.js} +1 -1
- package/dist/client/assets/{dist-Dy5baLB7.js → dist-BkSZy41B.js} +1 -1
- package/dist/client/assets/{dist-DGppcLCl.js → dist-BrKx1t7U.js} +1 -1
- package/dist/client/assets/dist-BywGDVPc.js +3 -0
- package/dist/client/assets/{dist-DtVj3pKW.js → dist-C3KFCuxF.js} +1 -1
- package/dist/client/assets/{dist-CKfkgouw.js → dist-CDLDZZr2.js} +1 -1
- package/dist/client/assets/{dist-Cb33yP2e.js → dist-CW2Zb9XN.js} +1 -1
- package/dist/client/assets/dist-CczD4z3C.js +1 -0
- package/dist/client/assets/{dist-BXu_3prg.js → dist-CmezYegB.js} +2 -2
- package/dist/client/assets/{dist-DV1tNG-p.js → dist-Cp5g1LCT.js} +1 -1
- package/dist/client/assets/{dist-erqcpmy2.js → dist-CsZ8KzbR.js} +1 -1
- package/dist/client/assets/{dist-DemGm2bb.js → dist-D5ttfXvN.js} +1 -1
- package/dist/client/assets/{dist-CFyI2sZh.js → dist-D9Tp0kLx.js} +1 -1
- package/dist/client/assets/dist-DEmZaMiQ.js +23 -0
- package/dist/client/assets/{dist-BNv34mUE.js → dist-DEwbAwCm.js} +1 -1
- package/dist/client/assets/dist-DKaZ9Fax.js +1 -0
- package/dist/client/assets/{dist-B-mG2iY2.js → dist-DWnCTx3S.js} +1 -1
- package/dist/client/assets/dist-DfZq6DlC.js +2 -0
- package/dist/client/assets/{dist-BdxRZGXx.js → dist-DvoNKyrD.js} +1 -1
- package/dist/client/assets/{dist-VqwcT4Z_.js → dist-UJRxKnWM.js} +2 -2
- package/dist/client/assets/editor-code-navigation-kyvwJimV.js +1 -0
- package/dist/client/assets/index-BI_W-Q7j.js +363 -0
- package/dist/client/assets/index-BRi_VDmX.css +1 -0
- package/dist/client/assets/protobuf-D1ij_kNL.js +1 -0
- package/dist/client/index.html +3 -4
- package/dist/server/application/provider-service.d.ts +6 -0
- package/dist/server/application/provider-service.js +31 -2
- package/dist/server/code-navigation.d.ts +36 -0
- package/dist/server/code-navigation.js +301 -0
- package/dist/server/http-server.d.ts +1 -0
- package/dist/server/http-server.js +67 -2
- package/dist/server/index.js +1 -0
- 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/code-navigation.d.ts +25 -0
- package/dist/shared/code-navigation.js +49 -0
- package/dist/shared/model-configuration.d.ts +1 -0
- package/package.json +5 -1
- package/dist/client/assets/CodeMirrorEditor-Dptza6ow.js +0 -2
- package/dist/client/assets/GitDiffEditor-BB3gQt45.js +0 -31
- package/dist/client/assets/GitHistoricalFile-DvMDll--.js +0 -1
- package/dist/client/assets/dist-BbaUXjJ-.js +0 -23
- package/dist/client/assets/dist-BrRbrWQ9.js +0 -2
- package/dist/client/assets/dist-BvUXYJ8T.js +0 -3
- package/dist/client/assets/dist-OQbeuazo.js +0 -1
- package/dist/client/assets/dist-hAqEmQDF.js +0 -1
- package/dist/client/assets/editor-blame-C7m05nPJ.js +0 -15
- package/dist/client/assets/editor-blame-PLncD0eu.css +0 -1
- package/dist/client/assets/index-CSO4Ah28.js +0 -350
- package/dist/client/assets/index-lnAcux4Q.css +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){return RegExp(`^((`+e.join(`)|(`)+`))\\b`,`i`)}var t=`package.message.import.syntax.required.optional.repeated.reserved.default.extensions.packed.bool.bytes.double.enum.float.string.int32.int64.uint32.uint64.sint32.sint64.fixed32.fixed64.sfixed32.sfixed64.option.service.rpc.returns`.split(`.`),n=e(t),r=RegExp(`^[_A-Za-z¡-][_A-Za-z0-9¡-]*`);function i(e){return e.eatSpace()?null:e.match(`//`)?(e.skipToEnd(),`comment`):e.match(/^[0-9\.+-]/,!1)&&(e.match(/^[+-]?0x[0-9a-fA-F]+/)||e.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/)||e.match(/^[+-]?\d+([EeDd][+-]?\d+)?/))?`number`:e.match(/^"([^"]|(""))*"/)||e.match(/^'([^']|(''))*'/)?`string`:e.match(n)?`keyword`:e.match(r)?`variable`:(e.next(),null)}var a={name:`protobuf`,token:i,languageData:{autocomplete:t}};export{a as protobuf};
|
package/dist/client/index.html
CHANGED
|
@@ -8,10 +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-
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/
|
|
13
|
-
<link rel="stylesheet" crossorigin href="/assets/
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/assets/index-lnAcux4Q.css">
|
|
11
|
+
<script type="module" crossorigin src="/assets/index-BI_W-Q7j.js"></script>
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/FileWorkbenchChrome-opMS3cZ5.js">
|
|
13
|
+
<link rel="stylesheet" crossorigin href="/assets/index-BRi_VDmX.css">
|
|
15
14
|
</head>
|
|
16
15
|
<body>
|
|
17
16
|
<div id="root"></div>
|
|
18
17
|
|
|
@@ -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;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type CodeDiagnostic, type CodeLocation, type CodeNavigationKind, type CodeTextEdit } from "../shared/code-navigation.js";
|
|
2
|
+
type NavigationErrorCode = "missing_server" | "unsupported" | "unavailable" | "timeout" | "busy";
|
|
3
|
+
export declare class CodeNavigationError extends Error {
|
|
4
|
+
readonly code: NavigationErrorCode;
|
|
5
|
+
constructor(code: NavigationErrorCode);
|
|
6
|
+
}
|
|
7
|
+
export type CodeNavigationRequest = {
|
|
8
|
+
path: string;
|
|
9
|
+
} & ({
|
|
10
|
+
kind: CodeNavigationKind;
|
|
11
|
+
line: number;
|
|
12
|
+
column: number;
|
|
13
|
+
} | {
|
|
14
|
+
kind: "diagnostics";
|
|
15
|
+
} | {
|
|
16
|
+
kind: "formatting";
|
|
17
|
+
});
|
|
18
|
+
export declare class CodeNavigation {
|
|
19
|
+
private projects;
|
|
20
|
+
private closed;
|
|
21
|
+
close(): void;
|
|
22
|
+
lookup(root: string, request: CodeNavigationRequest, content: string, signal?: AbortSignal): Promise<{
|
|
23
|
+
diagnostics: CodeDiagnostic[];
|
|
24
|
+
edits?: undefined;
|
|
25
|
+
locations?: undefined;
|
|
26
|
+
} | {
|
|
27
|
+
diagnostics?: undefined;
|
|
28
|
+
edits: CodeTextEdit[];
|
|
29
|
+
locations?: undefined;
|
|
30
|
+
} | {
|
|
31
|
+
diagnostics?: undefined;
|
|
32
|
+
edits?: undefined;
|
|
33
|
+
locations: CodeLocation[];
|
|
34
|
+
}>;
|
|
35
|
+
}
|
|
36
|
+
export {};
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { constants } from "node:fs";
|
|
3
|
+
import { access, stat } from "node:fs/promises";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { delimiter, isAbsolute, join, relative, sep } from "node:path";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
7
|
+
import { createMessageConnection, StreamMessageReader, StreamMessageWriter } from "vscode-jsonrpc/node.js";
|
|
8
|
+
import { codeLanguage } from "../shared/code-navigation.js";
|
|
9
|
+
export class CodeNavigationError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code) {
|
|
12
|
+
super(code);
|
|
13
|
+
this.code = code;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
const MAX_SERVERS = 6;
|
|
17
|
+
const IDLE_MS = 3 * 60_000;
|
|
18
|
+
const integer = (value) => typeof value === "number" && Number.isSafeInteger(value);
|
|
19
|
+
function uriKey(uri) {
|
|
20
|
+
try {
|
|
21
|
+
const path = fileURLToPath(uri);
|
|
22
|
+
return process.platform === "win32" ? path.toLowerCase() : path;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return uri;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function pathExecutable(command) {
|
|
29
|
+
const binary = process.platform === "win32" ? `${command}.exe` : command;
|
|
30
|
+
const pathValue = process.env.PATH ?? process.env.Path ?? "";
|
|
31
|
+
for (const candidate of pathValue.split(delimiter)) {
|
|
32
|
+
const directory = candidate.trim().replace(/^"(.*)"$/, "$1");
|
|
33
|
+
if (!isAbsolute(directory))
|
|
34
|
+
continue;
|
|
35
|
+
const executable = join(directory, binary);
|
|
36
|
+
try {
|
|
37
|
+
await access(executable, constants.X_OK);
|
|
38
|
+
if ((await stat(executable)).isFile())
|
|
39
|
+
return executable;
|
|
40
|
+
}
|
|
41
|
+
catch { /* Try the next entry on the server's PATH. */ }
|
|
42
|
+
}
|
|
43
|
+
throw new CodeNavigationError("missing_server");
|
|
44
|
+
}
|
|
45
|
+
const resolvePackage = createRequire(import.meta.url).resolve;
|
|
46
|
+
const commands = {
|
|
47
|
+
clangd: ["--background-index", "--clang-tidy", "--log=error", "-j=2"], typescript: ["--stdio"], pylsp: [], buf: ["lsp", "serve"],
|
|
48
|
+
};
|
|
49
|
+
function withDeadline(promise, ms, expire) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const timer = setTimeout(() => { reject(new CodeNavigationError("timeout")); expire(); }, ms);
|
|
52
|
+
promise.then(value => { clearTimeout(timer); resolve(value); }, error => { clearTimeout(timer); reject(error); });
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function locations(root, answer) {
|
|
56
|
+
const targets = new Map();
|
|
57
|
+
for (const item of (Array.isArray(answer) ? answer : answer ? [answer] : []).slice(0, 100)) {
|
|
58
|
+
const uri = item?.targetUri ?? item?.uri;
|
|
59
|
+
const start = item?.targetSelectionRange?.start ?? item?.range?.start;
|
|
60
|
+
if (typeof uri !== "string" || !start || !integer(start.line) || !integer(start.character)
|
|
61
|
+
|| start.line < 0 || start.character < 0)
|
|
62
|
+
continue;
|
|
63
|
+
try {
|
|
64
|
+
const absolute = fileURLToPath(uri);
|
|
65
|
+
const path = relative(root, absolute);
|
|
66
|
+
const inside = path && !isAbsolute(path) && path !== ".." && !path.startsWith(".." + sep);
|
|
67
|
+
const target = {
|
|
68
|
+
path: (inside ? path : absolute).split(sep).join("/"),
|
|
69
|
+
...(inside ? {} : { external: true }),
|
|
70
|
+
line: start.line + 1,
|
|
71
|
+
column: start.character + 1,
|
|
72
|
+
};
|
|
73
|
+
targets.set(JSON.stringify(target), target);
|
|
74
|
+
}
|
|
75
|
+
catch { /* The editor can only open real filesystem locations. */ }
|
|
76
|
+
}
|
|
77
|
+
return [...targets.values()];
|
|
78
|
+
}
|
|
79
|
+
function codeOffsets(content, clamp = false) {
|
|
80
|
+
const lines = content.split("\n");
|
|
81
|
+
let next = 0;
|
|
82
|
+
const starts = lines.map(line => { const offset = next; next += line.length + 1; return offset; });
|
|
83
|
+
return (position) => {
|
|
84
|
+
if (!position || !integer(position.line) || !integer(position.character))
|
|
85
|
+
return;
|
|
86
|
+
const line = lines[position.line];
|
|
87
|
+
if (line === undefined || position.character < 0)
|
|
88
|
+
return;
|
|
89
|
+
const width = line.endsWith("\r") ? line.length - 1 : line.length;
|
|
90
|
+
if (position.character <= width || clamp)
|
|
91
|
+
return starts[position.line] + Math.min(width, position.character);
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
function diagnosticsFor(content, diagnostics) {
|
|
95
|
+
const offset = codeOffsets(content, true);
|
|
96
|
+
return diagnostics.slice(0, 300).flatMap(item => {
|
|
97
|
+
if ((item.severity !== 1 && item.severity !== 2) || typeof item.message !== "string")
|
|
98
|
+
return [];
|
|
99
|
+
const from = offset(item.range?.start), to = offset(item.range?.end);
|
|
100
|
+
if (from === undefined || to === undefined || to < from)
|
|
101
|
+
return [];
|
|
102
|
+
const source = [item.source, item.code].filter(value => value !== undefined && value !== "").join(" · ");
|
|
103
|
+
return [{ from, to, severity: item.severity === 1 ? "error" : "warning", message: item.message, source }];
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
class LanguageProject {
|
|
107
|
+
root;
|
|
108
|
+
provider;
|
|
109
|
+
diagnosticsOnly;
|
|
110
|
+
onClose;
|
|
111
|
+
child;
|
|
112
|
+
connection;
|
|
113
|
+
initialization;
|
|
114
|
+
version = 0;
|
|
115
|
+
diagnostic;
|
|
116
|
+
diagnosticClear;
|
|
117
|
+
tail = Promise.resolve();
|
|
118
|
+
idle;
|
|
119
|
+
queued = 0;
|
|
120
|
+
closed = false;
|
|
121
|
+
constructor(root, provider, diagnosticsOnly, onClose) {
|
|
122
|
+
this.root = root;
|
|
123
|
+
this.provider = provider;
|
|
124
|
+
this.diagnosticsOnly = diagnosticsOnly;
|
|
125
|
+
this.onClose = onClose;
|
|
126
|
+
}
|
|
127
|
+
get canEvict() { return this.queued === 0; }
|
|
128
|
+
close() {
|
|
129
|
+
if (this.closed)
|
|
130
|
+
return;
|
|
131
|
+
this.closed = true;
|
|
132
|
+
clearTimeout(this.idle);
|
|
133
|
+
clearTimeout(this.diagnostic?.first);
|
|
134
|
+
this.diagnostic?.reject(new CodeNavigationError("unavailable"));
|
|
135
|
+
this.connection?.dispose();
|
|
136
|
+
this.child?.kill();
|
|
137
|
+
this.onClose();
|
|
138
|
+
}
|
|
139
|
+
async start() {
|
|
140
|
+
const provider = this.provider;
|
|
141
|
+
const binary = provider === "typescript" ? process.execPath : await pathExecutable(provider);
|
|
142
|
+
const args = provider === "typescript" ? [resolvePackage("typescript-language-server/lib/cli.mjs"), ...commands.typescript] : commands[provider];
|
|
143
|
+
if (this.closed)
|
|
144
|
+
throw new CodeNavigationError("unavailable");
|
|
145
|
+
const child = this.child = spawn(binary, args, { cwd: this.root, windowsHide: true });
|
|
146
|
+
child.on("error", () => this.close());
|
|
147
|
+
child.once("exit", () => this.close());
|
|
148
|
+
child.stderr.resume();
|
|
149
|
+
const rpc = this.connection = createMessageConnection(new StreamMessageReader(child.stdout), new StreamMessageWriter(child.stdin));
|
|
150
|
+
rpc.onError(() => this.close());
|
|
151
|
+
rpc.onClose(() => this.close());
|
|
152
|
+
rpc.onRequest("workspace/configuration", (params) => params.items?.map(item => item.section === "formattingOptions" ? { tabSize: 4, insertSpaces: true } : null) ?? []);
|
|
153
|
+
rpc.onRequest("workspace/workspaceFolders", () => [{ uri: pathToFileURL(this.root).href, name: "Workspace" }]);
|
|
154
|
+
rpc.onRequest("window/workDoneProgress/create", () => null);
|
|
155
|
+
rpc.onRequest("client/registerCapability", () => null);
|
|
156
|
+
rpc.onNotification("textDocument/publishDiagnostics", (params) => {
|
|
157
|
+
const uri = uriKey(params.uri);
|
|
158
|
+
if (this.diagnosticClear?.uri === uri && params.diagnostics?.length === 0)
|
|
159
|
+
this.diagnosticClear.done();
|
|
160
|
+
const pending = this.diagnostic;
|
|
161
|
+
if (!pending || pending.uri !== uri || (pending.version !== params.version && !(this.diagnosticsOnly && params.version === undefined))
|
|
162
|
+
|| !Array.isArray(params.diagnostics))
|
|
163
|
+
return;
|
|
164
|
+
if (provider === "buf" && !pending.first && !params.diagnostics.some(diagnostic => diagnostic.severity === 1)) {
|
|
165
|
+
// Buf publishes parse diagnostics before its independent lint pass.
|
|
166
|
+
pending.first = setTimeout(() => pending.resolve(params.diagnostics), 1500);
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
clearTimeout(pending.first);
|
|
170
|
+
pending.resolve(params.diagnostics);
|
|
171
|
+
});
|
|
172
|
+
rpc.listen();
|
|
173
|
+
const uri = pathToFileURL(this.root).href;
|
|
174
|
+
const initialized = await withDeadline(rpc.sendRequest("initialize", {
|
|
175
|
+
processId: process.pid, rootPath: this.root, rootUri: uri, workspaceFolders: [{ uri, name: "Workspace" }],
|
|
176
|
+
...(provider === "typescript" ? { initializationOptions: { disableAutomaticTypingAcquisition: true,
|
|
177
|
+
tsserver: { path: resolvePackage("typescript-lsp-runtime/lib/tsserver.js"), useSyntaxServer: "never" } } } : {}),
|
|
178
|
+
capabilities: { general: { positionEncodings: ["utf-16"] }, workspace: { configuration: true, workspaceFolders: true },
|
|
179
|
+
textDocument: { declaration: { linkSupport: true }, definition: { linkSupport: true }, publishDiagnostics: { versionSupport: true } } },
|
|
180
|
+
}), 12_000, () => this.close());
|
|
181
|
+
if (initialized.capabilities.positionEncoding && initialized.capabilities.positionEncoding !== "utf-16")
|
|
182
|
+
throw new CodeNavigationError("unsupported");
|
|
183
|
+
await rpc.sendNotification("initialized", {});
|
|
184
|
+
return initialized.capabilities;
|
|
185
|
+
}
|
|
186
|
+
lookup(query, content, signal) {
|
|
187
|
+
if (this.queued >= 8)
|
|
188
|
+
return Promise.reject(new CodeNavigationError("busy"));
|
|
189
|
+
clearTimeout(this.idle);
|
|
190
|
+
this.queued++;
|
|
191
|
+
const result = this.tail.then(async () => {
|
|
192
|
+
if (this.closed || signal?.aborted)
|
|
193
|
+
throw new CodeNavigationError("unavailable");
|
|
194
|
+
let capabilities;
|
|
195
|
+
try {
|
|
196
|
+
capabilities = await (this.initialization ??= this.start());
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
this.close();
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
if (signal?.aborted)
|
|
203
|
+
throw new CodeNavigationError("unavailable");
|
|
204
|
+
if (((query.kind === "definition" || query.kind === "declaration") && !capabilities.definitionProvider && !capabilities.declarationProvider)
|
|
205
|
+
|| (query.kind === "formatting" && !capabilities.documentFormattingProvider))
|
|
206
|
+
throw new CodeNavigationError("unsupported");
|
|
207
|
+
const rpc = this.connection;
|
|
208
|
+
const textDocument = { uri: pathToFileURL(query.path).href };
|
|
209
|
+
const version = ++this.version;
|
|
210
|
+
const ready = query.kind === "diagnostics" && !capabilities.diagnosticProvider ? new Promise((resolve, reject) => {
|
|
211
|
+
this.diagnostic = { version, uri: uriKey(textDocument.uri), resolve, reject };
|
|
212
|
+
}) : undefined;
|
|
213
|
+
ready?.catch(() => { });
|
|
214
|
+
try {
|
|
215
|
+
await rpc.sendNotification("textDocument/didOpen", { textDocument: { ...textDocument, languageId: codeLanguage(query.path)?.id, version, text: content } });
|
|
216
|
+
if (query.kind === "diagnostics") {
|
|
217
|
+
const items = ready ? await withDeadline(ready, 12_000, () => this.close())
|
|
218
|
+
: (await withDeadline(rpc.sendRequest("textDocument/diagnostic", { textDocument }), 12_000, () => this.close())).items ?? [];
|
|
219
|
+
return { diagnostics: diagnosticsFor(content, items) };
|
|
220
|
+
}
|
|
221
|
+
if (query.kind === "formatting") {
|
|
222
|
+
const changes = await withDeadline(rpc.sendRequest("textDocument/formatting", {
|
|
223
|
+
textDocument, options: { tabSize: 4, insertSpaces: true },
|
|
224
|
+
}), 12_000, () => this.close());
|
|
225
|
+
const offset = codeOffsets(content);
|
|
226
|
+
const edits = (changes ?? []).map(edit => {
|
|
227
|
+
const from = offset(edit.range?.start), to = offset(edit.range?.end);
|
|
228
|
+
if (from === undefined || to === undefined || to < from || typeof edit.newText !== "string")
|
|
229
|
+
throw new CodeNavigationError("unavailable");
|
|
230
|
+
return { from, to, insert: edit.newText };
|
|
231
|
+
}).sort((a, b) => a.from - b.from || a.to - b.to);
|
|
232
|
+
return { edits };
|
|
233
|
+
}
|
|
234
|
+
const method = query.kind === "declaration" && capabilities.declarationProvider ? "declaration" : "definition";
|
|
235
|
+
const reply = await withDeadline(rpc.sendRequest(`textDocument/${method}`, {
|
|
236
|
+
textDocument, position: { line: query.line - 1, character: query.column - 1 },
|
|
237
|
+
}), 12_000, () => this.close());
|
|
238
|
+
return { locations: locations(this.root, reply) };
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
clearTimeout(this.diagnostic?.first);
|
|
242
|
+
this.diagnostic = undefined;
|
|
243
|
+
if (!this.closed) {
|
|
244
|
+
if (!this.diagnosticsOnly)
|
|
245
|
+
await rpc.sendNotification("textDocument/didClose", { textDocument });
|
|
246
|
+
else {
|
|
247
|
+
const cleared = new Promise(done => { this.diagnosticClear = { uri: uriKey(textDocument.uri), done }; });
|
|
248
|
+
try {
|
|
249
|
+
await rpc.sendNotification("textDocument/didClose", { textDocument });
|
|
250
|
+
await withDeadline(cleared, 1000, () => this.close());
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
this.close();
|
|
254
|
+
}
|
|
255
|
+
finally {
|
|
256
|
+
this.diagnosticClear = undefined;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}).finally(() => {
|
|
262
|
+
if (--this.queued === 0 && !this.closed) {
|
|
263
|
+
this.idle = setTimeout(() => this.close(), IDLE_MS);
|
|
264
|
+
this.idle.unref();
|
|
265
|
+
}
|
|
266
|
+
});
|
|
267
|
+
this.tail = result.catch(() => { });
|
|
268
|
+
return result;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
export class CodeNavigation {
|
|
272
|
+
projects = new Map();
|
|
273
|
+
closed = false;
|
|
274
|
+
close() {
|
|
275
|
+
this.closed = true;
|
|
276
|
+
for (const project of this.projects.values())
|
|
277
|
+
project.close();
|
|
278
|
+
}
|
|
279
|
+
lookup(root, request, content, signal) {
|
|
280
|
+
if (this.closed)
|
|
281
|
+
throw new CodeNavigationError("unavailable");
|
|
282
|
+
const language = codeLanguage(request.path);
|
|
283
|
+
if (!language)
|
|
284
|
+
throw new CodeNavigationError("unsupported");
|
|
285
|
+
// Servers that do not version diagnostics cannot share the editor-query connection safely.
|
|
286
|
+
const diagnosticsOnly = request.kind === "diagnostics" && (language.server === "typescript" || language.server === "pylsp");
|
|
287
|
+
const key = JSON.stringify([root, language.server, diagnosticsOnly]);
|
|
288
|
+
let project = this.projects.get(key);
|
|
289
|
+
if (!project) {
|
|
290
|
+
if (this.projects.size >= MAX_SERVERS) {
|
|
291
|
+
const idle = [...this.projects.values()].find(candidate => candidate.canEvict);
|
|
292
|
+
if (!idle)
|
|
293
|
+
throw new CodeNavigationError("busy");
|
|
294
|
+
idle.close();
|
|
295
|
+
}
|
|
296
|
+
project = new LanguageProject(root, language.server, diagnosticsOnly, () => this.projects.delete(key));
|
|
297
|
+
this.projects.set(key, project);
|
|
298
|
+
}
|
|
299
|
+
return project.lookup(request, content, signal);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
@@ -9,6 +9,7 @@ import { spawn } from "node:child_process";
|
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
10
|
import { BrowserAccess, isBrowserAuthorized } from "./browser-access.js";
|
|
11
11
|
import { NativeToolsService, NativeToolsError } from "./native-tools-service.js";
|
|
12
|
+
import { CodeNavigation, CodeNavigationError } from "./code-navigation.js";
|
|
12
13
|
import { once } from "node:events";
|
|
13
14
|
import { access, readFile, readdir, realpath, rm, stat } from "node:fs/promises";
|
|
14
15
|
import { createServer } from "node:http";
|
|
@@ -376,6 +377,7 @@ export function createHttpServer(options) {
|
|
|
376
377
|
const explicitFileOpen = createExplicitFileOpen();
|
|
377
378
|
const browserAccess = context.browserAccess ??= new BrowserAccess(join(paths.dataDir, "browser-access.json"));
|
|
378
379
|
const nativeTools = new NativeToolsService(paths.dataDir, () => context.runtime?.reloadNativeTools?.());
|
|
380
|
+
const codeNavigation = new CodeNavigation();
|
|
379
381
|
const readBaseline = [];
|
|
380
382
|
const initialReadState = store.clientState({});
|
|
381
383
|
for (const conversation of initialReadState.conversations) {
|
|
@@ -3854,6 +3856,66 @@ export function createHttpServer(options) {
|
|
|
3854
3856
|
}
|
|
3855
3857
|
return;
|
|
3856
3858
|
}
|
|
3859
|
+
if (url.pathname === "/api/files/code-navigation") {
|
|
3860
|
+
if (request.method !== "POST") {
|
|
3861
|
+
json(405, { code: "method" });
|
|
3862
|
+
return;
|
|
3863
|
+
}
|
|
3864
|
+
if (!isBrowserAuthorized(request) && !isLocalOrPrivateAddress(remote)) {
|
|
3865
|
+
json(403, { code: "unavailable" });
|
|
3866
|
+
return;
|
|
3867
|
+
}
|
|
3868
|
+
const workspaceId = url.searchParams.get("workspaceId")?.trim();
|
|
3869
|
+
const workspace = workspaceId ? store.workspace(workspaceId) : undefined;
|
|
3870
|
+
if (!workspace || workspace.closedAt) {
|
|
3871
|
+
json(404, { code: "workspace_missing" });
|
|
3872
|
+
return;
|
|
3873
|
+
}
|
|
3874
|
+
const controller = new AbortController();
|
|
3875
|
+
response.once("close", () => controller.abort());
|
|
3876
|
+
try {
|
|
3877
|
+
const payload = await readRequestText(request, MAX_FILE_BYTES * 2);
|
|
3878
|
+
if (payload.tooLarge) {
|
|
3879
|
+
json(413, { code: "too_large" });
|
|
3880
|
+
return;
|
|
3881
|
+
}
|
|
3882
|
+
let body;
|
|
3883
|
+
try {
|
|
3884
|
+
body = JSON.parse(payload.text);
|
|
3885
|
+
}
|
|
3886
|
+
catch {
|
|
3887
|
+
json(400, { code: "bad_query" });
|
|
3888
|
+
return;
|
|
3889
|
+
}
|
|
3890
|
+
const kind = body?.kind, path = body?.path, line = body?.line, column = body?.column, content = body?.content;
|
|
3891
|
+
const symbol = kind === "definition" || kind === "declaration";
|
|
3892
|
+
if ((!symbol && kind !== "diagnostics" && kind !== "formatting") || typeof path !== "string" || !path || path.length > 4096
|
|
3893
|
+
|| (symbol && (!Number.isSafeInteger(line) || line < 1 || !Number.isSafeInteger(column) || column < 1))
|
|
3894
|
+
|| (content !== undefined && (typeof content !== "string" || Buffer.byteLength(content) > MAX_FILE_BYTES))) {
|
|
3895
|
+
json(400, { code: "bad_query" });
|
|
3896
|
+
return;
|
|
3897
|
+
}
|
|
3898
|
+
const checkout = await resolveFileCwd(workspace.path);
|
|
3899
|
+
const cwd = await resolveFileCwd(checkout, url.searchParams.get("cwd"));
|
|
3900
|
+
await explorerPath(checkout, cwd, path, true);
|
|
3901
|
+
const file = await resolveInsideRoot(cwd, path);
|
|
3902
|
+
const disk = await readWorkspaceFile(cwd, path);
|
|
3903
|
+
const result = await codeNavigation.lookup(checkout, symbol ? { kind, path: file, line, column } : { kind, path: file }, content ?? disk.content, controller.signal);
|
|
3904
|
+
if (!controller.signal.aborted)
|
|
3905
|
+
json(200, result);
|
|
3906
|
+
}
|
|
3907
|
+
catch (error) {
|
|
3908
|
+
if (controller.signal.aborted)
|
|
3909
|
+
return;
|
|
3910
|
+
if (error instanceof CodeNavigationError)
|
|
3911
|
+
json(422, { code: error.code });
|
|
3912
|
+
else if (error instanceof FilesError)
|
|
3913
|
+
json(error.status, { code: "bad_file" });
|
|
3914
|
+
else
|
|
3915
|
+
json(502, { code: "unavailable" });
|
|
3916
|
+
}
|
|
3917
|
+
return;
|
|
3918
|
+
}
|
|
3857
3919
|
if (url.pathname === "/api/files" || url.pathname === "/api/file") {
|
|
3858
3920
|
const json = (status, body) => {
|
|
3859
3921
|
response.writeHead(status, { "content-type": "application/json; charset=utf-8" }).end(JSON.stringify(body));
|
|
@@ -4218,6 +4280,9 @@ export function createHttpServer(options) {
|
|
|
4218
4280
|
}
|
|
4219
4281
|
}
|
|
4220
4282
|
});
|
|
4221
|
-
server.once("close", () => { void nativeTools.close(); });
|
|
4222
|
-
return Object.assign(server, {
|
|
4283
|
+
server.once("close", () => { codeNavigation.close(); void nativeTools.close(); });
|
|
4284
|
+
return Object.assign(server, {
|
|
4285
|
+
closeNativeTools: () => nativeTools.close(),
|
|
4286
|
+
closeCodeNavigation: () => codeNavigation.close(),
|
|
4287
|
+
});
|
|
4223
4288
|
}
|
package/dist/server/index.js
CHANGED
|
@@ -497,6 +497,7 @@ async function shutdown(reason) {
|
|
|
497
497
|
// Stop accepting new connections first. Existing clients stay connected until
|
|
498
498
|
// their cancelled work has recorded its terminal state.
|
|
499
499
|
const httpClosed = closeHttpServer();
|
|
500
|
+
httpServer.closeCodeNavigation();
|
|
500
501
|
const nativeToolsClosed = httpServer.closeNativeTools();
|
|
501
502
|
// Kill every shell BEFORE the sockets close, so a PTY is never outlived by the server that owns it.
|
|
502
503
|
terminalService.closeAll();
|
|
@@ -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) {
|