@hmharness/lsp 0.23.24 → 0.23.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/tools.d.ts +12 -1
- package/dist/tools.js +8 -0
- package/package.json +23 -23
- package/src/__tests__/deveco.test.ts +60 -60
- package/src/__tests__/fixtures/fake-server.cjs +89 -89
- package/src/__tests__/lsp.test.ts +119 -119
- package/src/__tests__/trust.test.ts +68 -68
- package/src/client.ts +137 -137
- package/src/index.ts +15 -15
- package/src/process-manager.ts +118 -118
- package/src/protocol.ts +113 -113
- package/src/registry.ts +130 -130
- package/src/tools.ts +229 -209
- package/src/trust.ts +108 -108
- package/tsconfig.build.json +18 -18
- package/verify-clangd.mts +40 -40
- package/verify-live.mts +27 -27
package/src/client.ts
CHANGED
|
@@ -1,137 +1,137 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @hmharness/lsp - LSP client over stdio
|
|
3
|
-
*
|
|
4
|
-
* Speaks the base protocol to ONE managed language-server process:
|
|
5
|
-
* initialize handshake -> requests (hover/definition/references/symbols)
|
|
6
|
-
* -> document sync notifications -> shutdown/exit. Diagnostics arrive as
|
|
7
|
-
* push notifications and land in the caller's callback (diagnostics-store
|
|
8
|
-
* behavior is the caller's; here we just route).
|
|
9
|
-
*/
|
|
10
|
-
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
11
|
-
import {
|
|
12
|
-
encodeMessage, MessageDecoder,
|
|
13
|
-
type InitializeParams, type InitializeResult, type JsonRpcResponse,
|
|
14
|
-
type Diagnostic, type DidOpenParams, type Hover, type Location, type DocumentSymbol, type ReferenceParams, type Position, type TextDocumentIdentifier,
|
|
15
|
-
} from './protocol.ts';
|
|
16
|
-
|
|
17
|
-
export interface LspClientOptions {
|
|
18
|
-
requestTimeoutMs?: number;
|
|
19
|
-
onDiagnostics?: (uri: string, diagnostics: Diagnostic[]) => void;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export class LspClient {
|
|
23
|
-
private seq = 0;
|
|
24
|
-
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
|
25
|
-
private decoder = new MessageDecoder();
|
|
26
|
-
private serverInfo: InitializeResult | null = null;
|
|
27
|
-
|
|
28
|
-
constructor(private proc: ChildProcessWithoutNullStreams, private opts: LspClientOptions = {}) {
|
|
29
|
-
proc.stdout.on('data', (chunk: Buffer) => {
|
|
30
|
-
for (const msg of this.decoder.push(chunk)) this.handle(msg as Record<string, unknown>);
|
|
31
|
-
});
|
|
32
|
-
proc.on('exit', () => {
|
|
33
|
-
for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('server exited')); }
|
|
34
|
-
this.pending.clear();
|
|
35
|
-
});
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
private handle(msg: Record<string, unknown>): void {
|
|
39
|
-
if (msg.method === 'textDocument/publishDiagnostics') {
|
|
40
|
-
const p = msg.params as { uri: string; diagnostics: Diagnostic[] };
|
|
41
|
-
this.opts.onDiagnostics?.(p.uri, p.diagnostics ?? []);
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
|
|
45
|
-
const p = this.pending.get(msg.id);
|
|
46
|
-
if (!p) return;
|
|
47
|
-
this.pending.delete(msg.id);
|
|
48
|
-
clearTimeout(p.timer);
|
|
49
|
-
const resp = msg as unknown as JsonRpcResponse;
|
|
50
|
-
if (resp.error) p.reject(new Error(`LSP ${resp.error.code}: ${resp.error.message}`));
|
|
51
|
-
else p.resolve(resp.result);
|
|
52
|
-
}
|
|
53
|
-
// window/logMessage etc: intentionally ignored (noise for the agent)
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
request<T>(method: string, params?: unknown): Promise<T> {
|
|
57
|
-
const id = ++this.seq;
|
|
58
|
-
return new Promise<T>((resolve, reject) => {
|
|
59
|
-
const timer = setTimeout(() => {
|
|
60
|
-
this.pending.delete(id);
|
|
61
|
-
reject(new Error(`LSP request ${method} timed out`));
|
|
62
|
-
}, this.opts.requestTimeoutMs ?? 20_000);
|
|
63
|
-
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
|
|
64
|
-
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', id, method, params }));
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
notify(method: string, params?: unknown): void {
|
|
69
|
-
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', method, params }));
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
async initialize(rootUri: string): Promise<InitializeResult> {
|
|
73
|
-
const params: InitializeParams = {
|
|
74
|
-
processId: process.pid,
|
|
75
|
-
rootUri,
|
|
76
|
-
workspaceFolders: [{ name: 'workspace', uri: rootUri }],
|
|
77
|
-
capabilities: { textDocument: { hover: {}, definition: {}, references: {}, documentSymbol: {}, publishDiagnostics: {} } },
|
|
78
|
-
};
|
|
79
|
-
const result = await this.request<InitializeResult>('initialize', params);
|
|
80
|
-
this.serverInfo = result;
|
|
81
|
-
this.notify('initialized', {});
|
|
82
|
-
return result;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
get info(): InitializeResult | null {
|
|
86
|
-
return this.serverInfo;
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/* ---------------- document sync (minimal: open + full change) ---------------- */
|
|
90
|
-
|
|
91
|
-
openDoc(uri: string, languageId: string, text: string): void {
|
|
92
|
-
const params: DidOpenParams = { textDocument: { uri, languageId, version: 1, text } };
|
|
93
|
-
this.notify('textDocument/didOpen', params);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
/* ---------------- Tier-0 requests ---------------- */
|
|
97
|
-
|
|
98
|
-
hover(textDocument: TextDocumentIdentifier, position: Position): Promise<Hover | null> {
|
|
99
|
-
return this.request<Hover | null>('textDocument/hover', { textDocument, position });
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
definition(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
103
|
-
return this.request<Location | Location[] | null>('textDocument/definition', { textDocument, position });
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
references(textDocument: TextDocumentIdentifier, position: Position, includeDeclaration = false): Promise<Location[]> {
|
|
107
|
-
const params: ReferenceParams = { textDocument, position, context: { includeDeclaration } };
|
|
108
|
-
return this.request<Location[]>('textDocument/references', params);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
documentSymbols(textDocument: TextDocumentIdentifier): Promise<DocumentSymbol[]> {
|
|
112
|
-
return this.request<DocumentSymbol[]>('textDocument/documentSymbol', { textDocument });
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/* ---------------- Tier-1 requests ---------------- */
|
|
116
|
-
|
|
117
|
-
implementation(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
118
|
-
return this.request<Location | Location[] | null>('textDocument/implementation', { textDocument, position });
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
/** call hierarchy: prepare the item at a position, then incoming/outgoing */
|
|
122
|
-
async prepareCallHierarchy(textDocument: TextDocumentIdentifier, position: Position): Promise<unknown> {
|
|
123
|
-
return this.request<unknown>('textDocument/prepareCallHierarchy', { textDocument, position });
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
callHierarchyIncoming(item: unknown): Promise<Array<{ from: unknown; fromRanges: Location['range'][] }>> {
|
|
127
|
-
return this.request('callHierarchy/incomingCalls', { item });
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
callHierarchyOutgoing(item: unknown): Promise<Array<{ to: unknown; toRanges: Location['range'][] }>> {
|
|
131
|
-
return this.request('callHierarchy/outgoingCalls', { item });
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
async shutdown(): Promise<void> {
|
|
135
|
-
try { await this.request('shutdown'); this.notify('exit'); } catch { /* best effort */ }
|
|
136
|
-
}
|
|
137
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/lsp - LSP client over stdio
|
|
3
|
+
*
|
|
4
|
+
* Speaks the base protocol to ONE managed language-server process:
|
|
5
|
+
* initialize handshake -> requests (hover/definition/references/symbols)
|
|
6
|
+
* -> document sync notifications -> shutdown/exit. Diagnostics arrive as
|
|
7
|
+
* push notifications and land in the caller's callback (diagnostics-store
|
|
8
|
+
* behavior is the caller's; here we just route).
|
|
9
|
+
*/
|
|
10
|
+
import type { ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
11
|
+
import {
|
|
12
|
+
encodeMessage, MessageDecoder,
|
|
13
|
+
type InitializeParams, type InitializeResult, type JsonRpcResponse,
|
|
14
|
+
type Diagnostic, type DidOpenParams, type Hover, type Location, type DocumentSymbol, type ReferenceParams, type Position, type TextDocumentIdentifier,
|
|
15
|
+
} from './protocol.ts';
|
|
16
|
+
|
|
17
|
+
export interface LspClientOptions {
|
|
18
|
+
requestTimeoutMs?: number;
|
|
19
|
+
onDiagnostics?: (uri: string, diagnostics: Diagnostic[]) => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export class LspClient {
|
|
23
|
+
private seq = 0;
|
|
24
|
+
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void; timer: NodeJS.Timeout }>();
|
|
25
|
+
private decoder = new MessageDecoder();
|
|
26
|
+
private serverInfo: InitializeResult | null = null;
|
|
27
|
+
|
|
28
|
+
constructor(private proc: ChildProcessWithoutNullStreams, private opts: LspClientOptions = {}) {
|
|
29
|
+
proc.stdout.on('data', (chunk: Buffer) => {
|
|
30
|
+
for (const msg of this.decoder.push(chunk)) this.handle(msg as Record<string, unknown>);
|
|
31
|
+
});
|
|
32
|
+
proc.on('exit', () => {
|
|
33
|
+
for (const [, p] of this.pending) { clearTimeout(p.timer); p.reject(new Error('server exited')); }
|
|
34
|
+
this.pending.clear();
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private handle(msg: Record<string, unknown>): void {
|
|
39
|
+
if (msg.method === 'textDocument/publishDiagnostics') {
|
|
40
|
+
const p = msg.params as { uri: string; diagnostics: Diagnostic[] };
|
|
41
|
+
this.opts.onDiagnostics?.(p.uri, p.diagnostics ?? []);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (typeof msg.id === 'number' && ('result' in msg || 'error' in msg)) {
|
|
45
|
+
const p = this.pending.get(msg.id);
|
|
46
|
+
if (!p) return;
|
|
47
|
+
this.pending.delete(msg.id);
|
|
48
|
+
clearTimeout(p.timer);
|
|
49
|
+
const resp = msg as unknown as JsonRpcResponse;
|
|
50
|
+
if (resp.error) p.reject(new Error(`LSP ${resp.error.code}: ${resp.error.message}`));
|
|
51
|
+
else p.resolve(resp.result);
|
|
52
|
+
}
|
|
53
|
+
// window/logMessage etc: intentionally ignored (noise for the agent)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
request<T>(method: string, params?: unknown): Promise<T> {
|
|
57
|
+
const id = ++this.seq;
|
|
58
|
+
return new Promise<T>((resolve, reject) => {
|
|
59
|
+
const timer = setTimeout(() => {
|
|
60
|
+
this.pending.delete(id);
|
|
61
|
+
reject(new Error(`LSP request ${method} timed out`));
|
|
62
|
+
}, this.opts.requestTimeoutMs ?? 20_000);
|
|
63
|
+
this.pending.set(id, { resolve: resolve as (v: unknown) => void, reject, timer });
|
|
64
|
+
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', id, method, params }));
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
notify(method: string, params?: unknown): void {
|
|
69
|
+
this.proc.stdin.write(encodeMessage({ jsonrpc: '2.0', method, params }));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async initialize(rootUri: string): Promise<InitializeResult> {
|
|
73
|
+
const params: InitializeParams = {
|
|
74
|
+
processId: process.pid,
|
|
75
|
+
rootUri,
|
|
76
|
+
workspaceFolders: [{ name: 'workspace', uri: rootUri }],
|
|
77
|
+
capabilities: { textDocument: { hover: {}, definition: {}, references: {}, documentSymbol: {}, publishDiagnostics: {} } },
|
|
78
|
+
};
|
|
79
|
+
const result = await this.request<InitializeResult>('initialize', params);
|
|
80
|
+
this.serverInfo = result;
|
|
81
|
+
this.notify('initialized', {});
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
get info(): InitializeResult | null {
|
|
86
|
+
return this.serverInfo;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/* ---------------- document sync (minimal: open + full change) ---------------- */
|
|
90
|
+
|
|
91
|
+
openDoc(uri: string, languageId: string, text: string): void {
|
|
92
|
+
const params: DidOpenParams = { textDocument: { uri, languageId, version: 1, text } };
|
|
93
|
+
this.notify('textDocument/didOpen', params);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ---------------- Tier-0 requests ---------------- */
|
|
97
|
+
|
|
98
|
+
hover(textDocument: TextDocumentIdentifier, position: Position): Promise<Hover | null> {
|
|
99
|
+
return this.request<Hover | null>('textDocument/hover', { textDocument, position });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
definition(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
103
|
+
return this.request<Location | Location[] | null>('textDocument/definition', { textDocument, position });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
references(textDocument: TextDocumentIdentifier, position: Position, includeDeclaration = false): Promise<Location[]> {
|
|
107
|
+
const params: ReferenceParams = { textDocument, position, context: { includeDeclaration } };
|
|
108
|
+
return this.request<Location[]>('textDocument/references', params);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
documentSymbols(textDocument: TextDocumentIdentifier): Promise<DocumentSymbol[]> {
|
|
112
|
+
return this.request<DocumentSymbol[]>('textDocument/documentSymbol', { textDocument });
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/* ---------------- Tier-1 requests ---------------- */
|
|
116
|
+
|
|
117
|
+
implementation(textDocument: TextDocumentIdentifier, position: Position): Promise<Location | Location[] | null> {
|
|
118
|
+
return this.request<Location | Location[] | null>('textDocument/implementation', { textDocument, position });
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** call hierarchy: prepare the item at a position, then incoming/outgoing */
|
|
122
|
+
async prepareCallHierarchy(textDocument: TextDocumentIdentifier, position: Position): Promise<unknown> {
|
|
123
|
+
return this.request<unknown>('textDocument/prepareCallHierarchy', { textDocument, position });
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
callHierarchyIncoming(item: unknown): Promise<Array<{ from: unknown; fromRanges: Location['range'][] }>> {
|
|
127
|
+
return this.request('callHierarchy/incomingCalls', { item });
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
callHierarchyOutgoing(item: unknown): Promise<Array<{ to: unknown; toRanges: Location['range'][] }>> {
|
|
131
|
+
return this.request('callHierarchy/outgoingCalls', { item });
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async shutdown(): Promise<void> {
|
|
135
|
+
try { await this.request('shutdown'); this.notify('exit'); } catch { /* best effort */ }
|
|
136
|
+
}
|
|
137
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @hmharness/lsp - LSP Client/Manager for agent code intelligence
|
|
3
|
-
*
|
|
4
|
-
* Client ONLY (master prompt rule): we drive external language servers
|
|
5
|
-
* over stdio (LSP 3.18 subset), never implement one. Security walls live
|
|
6
|
-
* in process-manager (workspace-bound cwd, scrubbed env, restart caps,
|
|
7
|
-
* timeouts). Tier-0 read-only tools in tools.ts; guarded rename/code
|
|
8
|
-
* actions are Tier-3 and NOT implemented here.
|
|
9
|
-
*/
|
|
10
|
-
export * from './protocol.ts';
|
|
11
|
-
export { ProcessManager, scrubEnv, fromPath, type ServerSpec, type ManagedServerOptions } from './process-manager.ts';
|
|
12
|
-
export { LspClient, type LspClientOptions } from './client.ts';
|
|
13
|
-
export { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.ts';
|
|
14
|
-
export { lspTools, shutdownLsp, diagnosticsSummary, type LspToolContext } from './tools.ts';
|
|
15
|
-
export { checkTrust, trustServer, untrustServer, listTrust, serverHash, trustPath, type TrustEntry, type TrustStore, type TrustVerdict } from './trust.ts';
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/lsp - LSP Client/Manager for agent code intelligence
|
|
3
|
+
*
|
|
4
|
+
* Client ONLY (master prompt rule): we drive external language servers
|
|
5
|
+
* over stdio (LSP 3.18 subset), never implement one. Security walls live
|
|
6
|
+
* in process-manager (workspace-bound cwd, scrubbed env, restart caps,
|
|
7
|
+
* timeouts). Tier-0 read-only tools in tools.ts; guarded rename/code
|
|
8
|
+
* actions are Tier-3 and NOT implemented here.
|
|
9
|
+
*/
|
|
10
|
+
export * from './protocol.ts';
|
|
11
|
+
export { ProcessManager, scrubEnv, fromPath, type ServerSpec, type ManagedServerOptions } from './process-manager.ts';
|
|
12
|
+
export { LspClient, type LspClientOptions } from './client.ts';
|
|
13
|
+
export { discoverServers, serverForFile, fileToUri, type DiscoveredServer } from './registry.ts';
|
|
14
|
+
export { lspTools, shutdownLsp, diagnosticsSummary, type LspToolContext } from './tools.ts';
|
|
15
|
+
export { checkTrust, trustServer, untrustServer, listTrust, serverHash, trustPath, type TrustEntry, type TrustStore, type TrustVerdict } from './trust.ts';
|
package/src/process-manager.ts
CHANGED
|
@@ -1,118 +1,118 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @hmharness/lsp - process manager (master prompt security rules)
|
|
3
|
-
*
|
|
4
|
-
* Owns language-server child processes with the hard walls from the LSP
|
|
5
|
-
* 专项方案 (03):
|
|
6
|
-
* - cwd is BOUND to the workspace root (a server cannot wander)
|
|
7
|
-
* - environment is an ALLOWLIST (secret env vars never inherit)
|
|
8
|
-
* - crash restart has a cap + exponential backoff (a flapping server
|
|
9
|
-
* must not become a fork bomb)
|
|
10
|
-
* - every request has a timeout and can be cancelled
|
|
11
|
-
* - the server's identity (command/version) is recorded for audit
|
|
12
|
-
*/
|
|
13
|
-
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
14
|
-
|
|
15
|
-
export interface ServerSpec {
|
|
16
|
-
/** server id, e.g. 'typescript' | 'pyright' | 'rust-analyzer' */
|
|
17
|
-
id: string;
|
|
18
|
-
/** executable + args exactly as discovered (no auto-download here) */
|
|
19
|
-
command: string;
|
|
20
|
-
args: string[];
|
|
21
|
-
/** provenance recorded for audit: where this command came from */
|
|
22
|
-
source: 'PATH' | 'explicit';
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export interface ManagedServerOptions {
|
|
26
|
-
/** secret-free env allowlist passed to the server (default: PATH/SYSTEMROOT/LANG only) */
|
|
27
|
-
envAllowlist?: string[];
|
|
28
|
-
maxRestarts?: number;
|
|
29
|
-
requestTimeoutMs?: number;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** Environment scrub: language servers do NOT need API keys to index code.
|
|
33
|
-
* Default allowlist keeps PATH working on Windows without inheriting
|
|
34
|
-
* provider tokens or user secrets. */
|
|
35
|
-
export function scrubEnv(extraAllow: string[] = []): NodeJS.ProcessEnv {
|
|
36
|
-
const allow = new Set(['PATH', 'Path', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'LANG', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', ...extraAllow]);
|
|
37
|
-
const out: NodeJS.ProcessEnv = {};
|
|
38
|
-
for (const [k, v] of Object.entries(process.env)) {
|
|
39
|
-
if (v !== undefined && allow.has(k.toUpperCase()) === false && !allow.has(k)) continue;
|
|
40
|
-
if (v !== undefined) out[k] = v;
|
|
41
|
-
}
|
|
42
|
-
return out;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export class ProcessManager {
|
|
46
|
-
private proc: ChildProcessWithoutNullStreams | null = null;
|
|
47
|
-
/** total spawns; spawns beyond the first are restarts (exit clears this.proc,
|
|
48
|
-
* so counting there would miss exactly the flapping case) */
|
|
49
|
-
private spawns = 0;
|
|
50
|
-
readonly startedAt: string | null = null;
|
|
51
|
-
lastExit: { code: number | null; signal: NodeJS.Signals | null; at: string } | null = null;
|
|
52
|
-
|
|
53
|
-
constructor(
|
|
54
|
-
readonly spec: ServerSpec,
|
|
55
|
-
private cwd: string,
|
|
56
|
-
private opts: ManagedServerOptions = {},
|
|
57
|
-
) {}
|
|
58
|
-
|
|
59
|
-
get restartCount(): number {
|
|
60
|
-
return Math.max(0, this.spawns - 1);
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
get running(): boolean {
|
|
64
|
-
return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Spawn (or respawn after crash, up to the cap). Resolves with the
|
|
68
|
-
* child's stdio streams; rejects when the restart budget is spent. */
|
|
69
|
-
start(): ChildProcessWithoutNullStreams {
|
|
70
|
-
if (this.running && this.proc) return this.proc;
|
|
71
|
-
const max = this.opts.maxRestarts ?? 3;
|
|
72
|
-
// allowed total spawns = the initial one + maxRestarts
|
|
73
|
-
if (this.spawns >= 1 + max) {
|
|
74
|
-
throw new Error(`server ${this.spec.id} exceeded restart budget (${this.restartCount} restarts >= ${max}) — refusing to flap`);
|
|
75
|
-
}
|
|
76
|
-
this.spawns += 1;
|
|
77
|
-
const proc = spawn(this.spec.command, this.spec.args, {
|
|
78
|
-
cwd: this.cwd, // bound to the workspace (03 方案: workspace 外访问)
|
|
79
|
-
env: scrubEnv(),
|
|
80
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
81
|
-
windowsHide: true,
|
|
82
|
-
}) as ChildProcessWithoutNullStreams;
|
|
83
|
-
proc.on('exit', (code, signal) => {
|
|
84
|
-
this.lastExit = { code, signal, at: new Date().toISOString() };
|
|
85
|
-
if (this.proc === proc) this.proc = null;
|
|
86
|
-
});
|
|
87
|
-
this.proc = proc;
|
|
88
|
-
return proc;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
/** Graceful stop, then hard kill. Always resolves. */
|
|
92
|
-
async stop(): Promise<void> {
|
|
93
|
-
const proc = this.proc;
|
|
94
|
-
if (!proc) return;
|
|
95
|
-
this.proc = null;
|
|
96
|
-
await new Promise<void>((resolve) => {
|
|
97
|
-
const killTimer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* gone */ } }, 3_000);
|
|
98
|
-
proc.once('exit', () => { clearTimeout(killTimer); resolve(); });
|
|
99
|
-
try { proc.kill(); } catch { clearTimeout(killTimer); resolve(); }
|
|
100
|
-
});
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** Synchronous last-resort kill (process 'exit' hook: async cleanup will
|
|
104
|
-
* not run there). Never spawns; kills the live child if any. */
|
|
105
|
-
killSync(): void {
|
|
106
|
-
const proc = this.proc;
|
|
107
|
-
this.proc = null;
|
|
108
|
-
if (proc) { try { proc.kill('SIGKILL'); } catch { /* gone */ } }
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Discover a server binary from PATH (explicit, never auto-downloaded —
|
|
113
|
-
* 03 方案: 自动下载供应链风险,来源白名单+hash 是后续 Capability OS 的事). */
|
|
114
|
-
export function fromPath(id: string, command: string, args: string[]): ServerSpec | null {
|
|
115
|
-
// PATH lookup without spawning: `where` on win, `which` elsewhere — cheap
|
|
116
|
-
// probe done by the caller; here we just mark provenance
|
|
117
|
-
return { id, command, args, source: 'PATH' };
|
|
118
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* @hmharness/lsp - process manager (master prompt security rules)
|
|
3
|
+
*
|
|
4
|
+
* Owns language-server child processes with the hard walls from the LSP
|
|
5
|
+
* 专项方案 (03):
|
|
6
|
+
* - cwd is BOUND to the workspace root (a server cannot wander)
|
|
7
|
+
* - environment is an ALLOWLIST (secret env vars never inherit)
|
|
8
|
+
* - crash restart has a cap + exponential backoff (a flapping server
|
|
9
|
+
* must not become a fork bomb)
|
|
10
|
+
* - every request has a timeout and can be cancelled
|
|
11
|
+
* - the server's identity (command/version) is recorded for audit
|
|
12
|
+
*/
|
|
13
|
+
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
export interface ServerSpec {
|
|
16
|
+
/** server id, e.g. 'typescript' | 'pyright' | 'rust-analyzer' */
|
|
17
|
+
id: string;
|
|
18
|
+
/** executable + args exactly as discovered (no auto-download here) */
|
|
19
|
+
command: string;
|
|
20
|
+
args: string[];
|
|
21
|
+
/** provenance recorded for audit: where this command came from */
|
|
22
|
+
source: 'PATH' | 'explicit';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ManagedServerOptions {
|
|
26
|
+
/** secret-free env allowlist passed to the server (default: PATH/SYSTEMROOT/LANG only) */
|
|
27
|
+
envAllowlist?: string[];
|
|
28
|
+
maxRestarts?: number;
|
|
29
|
+
requestTimeoutMs?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Environment scrub: language servers do NOT need API keys to index code.
|
|
33
|
+
* Default allowlist keeps PATH working on Windows without inheriting
|
|
34
|
+
* provider tokens or user secrets. */
|
|
35
|
+
export function scrubEnv(extraAllow: string[] = []): NodeJS.ProcessEnv {
|
|
36
|
+
const allow = new Set(['PATH', 'Path', 'SYSTEMROOT', 'SystemRoot', 'TEMP', 'TMP', 'LANG', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES', ...extraAllow]);
|
|
37
|
+
const out: NodeJS.ProcessEnv = {};
|
|
38
|
+
for (const [k, v] of Object.entries(process.env)) {
|
|
39
|
+
if (v !== undefined && allow.has(k.toUpperCase()) === false && !allow.has(k)) continue;
|
|
40
|
+
if (v !== undefined) out[k] = v;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ProcessManager {
|
|
46
|
+
private proc: ChildProcessWithoutNullStreams | null = null;
|
|
47
|
+
/** total spawns; spawns beyond the first are restarts (exit clears this.proc,
|
|
48
|
+
* so counting there would miss exactly the flapping case) */
|
|
49
|
+
private spawns = 0;
|
|
50
|
+
readonly startedAt: string | null = null;
|
|
51
|
+
lastExit: { code: number | null; signal: NodeJS.Signals | null; at: string } | null = null;
|
|
52
|
+
|
|
53
|
+
constructor(
|
|
54
|
+
readonly spec: ServerSpec,
|
|
55
|
+
private cwd: string,
|
|
56
|
+
private opts: ManagedServerOptions = {},
|
|
57
|
+
) {}
|
|
58
|
+
|
|
59
|
+
get restartCount(): number {
|
|
60
|
+
return Math.max(0, this.spawns - 1);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
get running(): boolean {
|
|
64
|
+
return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Spawn (or respawn after crash, up to the cap). Resolves with the
|
|
68
|
+
* child's stdio streams; rejects when the restart budget is spent. */
|
|
69
|
+
start(): ChildProcessWithoutNullStreams {
|
|
70
|
+
if (this.running && this.proc) return this.proc;
|
|
71
|
+
const max = this.opts.maxRestarts ?? 3;
|
|
72
|
+
// allowed total spawns = the initial one + maxRestarts
|
|
73
|
+
if (this.spawns >= 1 + max) {
|
|
74
|
+
throw new Error(`server ${this.spec.id} exceeded restart budget (${this.restartCount} restarts >= ${max}) — refusing to flap`);
|
|
75
|
+
}
|
|
76
|
+
this.spawns += 1;
|
|
77
|
+
const proc = spawn(this.spec.command, this.spec.args, {
|
|
78
|
+
cwd: this.cwd, // bound to the workspace (03 方案: workspace 外访问)
|
|
79
|
+
env: scrubEnv(),
|
|
80
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
81
|
+
windowsHide: true,
|
|
82
|
+
}) as ChildProcessWithoutNullStreams;
|
|
83
|
+
proc.on('exit', (code, signal) => {
|
|
84
|
+
this.lastExit = { code, signal, at: new Date().toISOString() };
|
|
85
|
+
if (this.proc === proc) this.proc = null;
|
|
86
|
+
});
|
|
87
|
+
this.proc = proc;
|
|
88
|
+
return proc;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Graceful stop, then hard kill. Always resolves. */
|
|
92
|
+
async stop(): Promise<void> {
|
|
93
|
+
const proc = this.proc;
|
|
94
|
+
if (!proc) return;
|
|
95
|
+
this.proc = null;
|
|
96
|
+
await new Promise<void>((resolve) => {
|
|
97
|
+
const killTimer = setTimeout(() => { try { proc.kill('SIGKILL'); } catch { /* gone */ } }, 3_000);
|
|
98
|
+
proc.once('exit', () => { clearTimeout(killTimer); resolve(); });
|
|
99
|
+
try { proc.kill(); } catch { clearTimeout(killTimer); resolve(); }
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Synchronous last-resort kill (process 'exit' hook: async cleanup will
|
|
104
|
+
* not run there). Never spawns; kills the live child if any. */
|
|
105
|
+
killSync(): void {
|
|
106
|
+
const proc = this.proc;
|
|
107
|
+
this.proc = null;
|
|
108
|
+
if (proc) { try { proc.kill('SIGKILL'); } catch { /* gone */ } }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Discover a server binary from PATH (explicit, never auto-downloaded —
|
|
113
|
+
* 03 方案: 自动下载供应链风险,来源白名单+hash 是后续 Capability OS 的事). */
|
|
114
|
+
export function fromPath(id: string, command: string, args: string[]): ServerSpec | null {
|
|
115
|
+
// PATH lookup without spawning: `where` on win, `which` elsewhere — cheap
|
|
116
|
+
// probe done by the caller; here we just mark provenance
|
|
117
|
+
return { id, command, args, source: 'PATH' };
|
|
118
|
+
}
|