@floydous/pi-agent-kernel 0.4.3 → 0.6.0

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.
Files changed (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,52 +0,0 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
- import { LSP_SERVERS } from "./lsp_registry";
4
-
5
- /**
6
- * Detect language identifier and root directory for a given file in workspace
7
- */
8
- export function detectLanguageFromPath(filePath: string): string | null {
9
- const ext = path.extname(filePath).toLowerCase();
10
- const base = path.basename(filePath).toLowerCase();
11
-
12
- // Exact file name matching (e.g. Dockerfile, Gemfile)
13
- for (const [key, cfg] of Object.entries(LSP_SERVERS)) {
14
- if (cfg.extensions.some((e) => e.toLowerCase() === base)) {
15
- return key;
16
- }
17
- }
18
-
19
- // Extension matching
20
- for (const [key, cfg] of Object.entries(LSP_SERVERS)) {
21
- if (cfg.extensions.some((e) => e.toLowerCase() === ext)) {
22
- return key;
23
- }
24
- }
25
-
26
- return null;
27
- }
28
-
29
- /**
30
- * Find workspace root by scanning upward for language marker files (tsconfig.json, Cargo.toml, pyproject.toml, etc.)
31
- */
32
- export function findWorkspaceRoot(startDir: string, languageKey?: string): string {
33
- let current = path.resolve(startDir);
34
- const root = path.parse(current).root;
35
-
36
- const markers = languageKey && LSP_SERVERS[languageKey]
37
- ? [...LSP_SERVERS[languageKey].markers, ".git"]
38
- : [".git", "package.json", "Cargo.toml", "pyproject.toml", "go.mod"];
39
-
40
- while (current && current !== root) {
41
- for (const marker of markers) {
42
- if (fs.existsSync(path.join(current, marker))) {
43
- return current;
44
- }
45
- }
46
- const parent = path.dirname(current);
47
- if (parent === current) break;
48
- current = parent;
49
- }
50
-
51
- return startDir;
52
- }
@@ -1,323 +0,0 @@
1
- import { pathToFileURL, fileURLToPath } from "node:url";
2
- import * as path from "node:path";
3
- import * as fs from "node:fs";
4
- import {
5
- LspDiagnostic,
6
- LspDiagnosticSeverity,
7
- LspLocation,
8
- LspLocationLink,
9
- LspHover,
10
- LspDocumentSymbol,
11
- LspSymbolInformation,
12
- LspSymbolKind,
13
- } from "./lsp_types";
14
-
15
- export function normalizeUri(uri: string): string {
16
- try {
17
- let p = fileURLToPath(uri);
18
- if (process.platform === "win32" && /^[a-zA-Z]:/.test(p)) {
19
- p = p[0].toLowerCase() + p.slice(1);
20
- }
21
- const u = pathToFileURL(p).href;
22
- return u.replace(/^file:\/\/\/([a-zA-Z]):/, (_, letter) => "file:///" + letter.toLowerCase() + ":");
23
- } catch {
24
- return uri;
25
- }
26
- }
27
-
28
- /**
29
- * Robust cross-platform path to file:// URI conversion
30
- */
31
- export function pathToUri(filePath: string): string {
32
- const abs = path.resolve(filePath);
33
- return normalizeUri(pathToFileURL(abs).href);
34
- }
35
-
36
- /**
37
- * Robust cross-platform file:// URI to local file path conversion
38
- */
39
- export function uriToPath(uri: string): string {
40
- try {
41
- const raw = fileURLToPath(uri);
42
- if (process.platform === "win32" && /^[a-z]:/i.test(raw)) {
43
- return raw[0].toUpperCase() + raw.slice(1);
44
- }
45
- return raw;
46
- } catch {
47
- return uri.replace(/^file:\/\/\/?/, "");
48
- }
49
- }
50
-
51
- /**
52
- * Format severity enum into concise label
53
- */
54
- function severityLabel(severity?: LspDiagnosticSeverity): string {
55
- switch (severity) {
56
- case LspDiagnosticSeverity.Error:
57
- return "ERROR";
58
- case LspDiagnosticSeverity.Warning:
59
- return "WARN";
60
- case LspDiagnosticSeverity.Information:
61
- return "INFO";
62
- case LspDiagnosticSeverity.Hint:
63
- return "HINT";
64
- default:
65
- return "DIAG";
66
- }
67
- }
68
-
69
- const MAX_DEFINITIONS = 200;
70
- const MAX_REFERENCES = 200;
71
- const MAX_REFERENCE_FILE_BYTES = 1024 * 1024;
72
- const MAX_SYMBOLS = 100;
73
- const MAX_SYMBOL_DEPTH = 10;
74
- const MAX_HOVER_CHARS = 32 * 1024;
75
- const MAX_DIAGNOSTIC_MESSAGE_CHARS = 2 * 1024;
76
-
77
- function clipText(value: unknown, limit: number): string {
78
- const text = String(value ?? "");
79
- return text.length > limit ? `${text.slice(0, limit)}…` : text;
80
- }
81
-
82
- /**
83
- * Symbol kind name lookup
84
- */
85
- function symbolKindLabel(kind: LspSymbolKind): string {
86
- return LspSymbolKind[kind]?.toLowerCase() || "symbol";
87
- }
88
-
89
- /**
90
- * Format diagnostics into compact, token-dense text output
91
- */
92
- export function formatDiagnostics(
93
- diagnostics: LspDiagnostic[],
94
- _filePath?: string,
95
- _cwd?: string
96
- ): string {
97
- if (!diagnostics || diagnostics.length === 0) {
98
- return "";
99
- }
100
-
101
- const visible = diagnostics.slice(0, 200);
102
- const lines = visible.map((d) => {
103
- const sev = severityLabel(d.severity);
104
- const line = d.range.start.line + 1; // Convert 0-indexed to 1-indexed
105
- const col = d.range.start.character + 1;
106
- const codeStr = d.code !== undefined ? ` [${d.code}]` : "";
107
- const srcStr = d.source ? ` (${d.source})` : "";
108
- return `- [${line}:${col}] [${sev}]${codeStr} ${clipText(d.message, MAX_DIAGNOSTIC_MESSAGE_CHARS)}${srcStr}`;
109
- });
110
- if (diagnostics.length > visible.length) {
111
- lines.push(`[Truncated: ${visible.length}/${diagnostics.length} diagnostics]`);
112
- }
113
-
114
- return lines.join("\n");
115
- }
116
-
117
- /**
118
- * Normalize LSP Definition / Location / LocationLink into simple LspLocation[]
119
- */
120
- export function normalizeLocations(
121
- result: LspLocation | LspLocation[] | LspLocationLink[] | null | undefined
122
- ): LspLocation[] {
123
- if (!result) return [];
124
- if (!Array.isArray(result)) return [result];
125
-
126
- return result.map((item) => {
127
- if ("targetUri" in item) {
128
- // LspLocationLink
129
- return {
130
- uri: item.targetUri,
131
- range: item.targetSelectionRange || item.targetRange,
132
- };
133
- }
134
- return item;
135
- });
136
- }
137
-
138
- /**
139
- * Format definition or declaration locations into compact output
140
- */
141
- export function formatDefinitions(
142
- locations: LspLocation[],
143
- cwd?: string
144
- ): string {
145
- if (!locations || locations.length === 0) {
146
- return "Definition not found.";
147
- }
148
-
149
- const visible = locations.slice(0, MAX_DEFINITIONS);
150
- const lines = visible.map((loc) => {
151
- const filePath = uriToPath(loc.uri);
152
- const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
153
- const displayPath = rawDisplay.replace(/\\/g, "/");
154
- const line = loc.range.start.line + 1;
155
- const col = loc.range.start.character + 1;
156
- return `${displayPath}:${line}:${col}`;
157
- });
158
- if (locations.length > visible.length) {
159
- lines.push(`[Truncated: ${visible.length}/${locations.length} definitions]`);
160
- }
161
-
162
- return lines.join("\n");
163
- }
164
-
165
- /**
166
- * Extract a bounded snippet around the target character span without truncating the symbol.
167
- */
168
- export function windowAround(
169
- line: string,
170
- startCol0: number,
171
- endCol0: number,
172
- budget = 50
173
- ): string {
174
- const normLine = line.replace(/\r?\n$/, "");
175
- const s = Math.max(0, Math.min(startCol0, normLine.length));
176
- const e = Math.max(s, Math.min(endCol0, normLine.length));
177
- const symLen = Math.max(1, e - s);
178
- const effectiveBudget = Math.min(4096, Math.max(budget, symLen));
179
- const pad = Math.max(0, effectiveBudget - symLen);
180
- const left = Math.max(0, s - Math.floor(pad / 2));
181
- const right = Math.min(normLine.length, e + Math.ceil(pad / 2));
182
- const snippet = normLine.slice(left, right).trim().slice(0, 4096);
183
- const prefix = left > 0 ? "... " : "";
184
- const suffix = right < normLine.length ? " ..." : "";
185
- return `${prefix}${snippet}${suffix}`.trim();
186
- }
187
-
188
- /**
189
- * Format symbol references into compact output with bounded line snippets.
190
- * Never leaks read evidence into epistemic ledger (metadata only).
191
- */
192
- export function formatReferences(
193
- references: LspLocation[],
194
- cwd?: string
195
- ): string {
196
- if (!references || references.length === 0) {
197
- return "No references found.";
198
- }
199
-
200
- // Per-query line cache: read each file from disk at most once
201
- const fileLinesCache = new Map<string, string[] | null>();
202
-
203
- const getLines = (filePath: string): string[] | null => {
204
- if (fileLinesCache.has(filePath)) {
205
- return fileLinesCache.get(filePath)!;
206
- }
207
- try {
208
- if (fs.existsSync(filePath)) {
209
- const stat = fs.statSync(filePath);
210
- if (stat.isFile() && stat.size <= MAX_REFERENCE_FILE_BYTES) {
211
- const lines = fs.readFileSync(filePath, "utf8").split("\n");
212
- fileLinesCache.set(filePath, lines);
213
- return lines;
214
- }
215
- }
216
- } catch {
217
- // Fall through to null for inaccessible/virtual files
218
- }
219
- fileLinesCache.set(filePath, null);
220
- return null;
221
- };
222
-
223
- const visible = references.slice(0, MAX_REFERENCES);
224
- const lines = visible.map((loc) => {
225
- const filePath = uriToPath(loc.uri);
226
- const rawDisplay = cwd ? path.relative(cwd, filePath) || filePath : filePath;
227
- const displayPath = rawDisplay.replace(/\\/g, "/");
228
- const line1 = loc.range.start.line + 1;
229
- const col1 = loc.range.start.character + 1;
230
- const baseLoc = `${displayPath}:${line1}:${col1}`;
231
-
232
- const cachedLines = getLines(filePath);
233
- if (!cachedLines || loc.range.start.line >= cachedLines.length) {
234
- return baseLoc;
235
- }
236
-
237
- const rawLine = cachedLines[loc.range.start.line] || "";
238
- const startCol0 = loc.range.start.character;
239
- const endCol0 =
240
- loc.range.end?.line === loc.range.start.line
241
- ? loc.range.end.character
242
- : startCol0 + 1;
243
-
244
- const snippet = windowAround(rawLine, startCol0, endCol0, 50);
245
- return snippet ? `${baseLoc}: ${snippet}` : baseLoc;
246
- });
247
- if (references.length > visible.length) {
248
- lines.push(`[Truncated: ${visible.length}/${references.length} references]`);
249
- }
250
- return lines.join("\n");
251
- }
252
-
253
- /**
254
- * Format hover response (type signatures, markdown docstrings)
255
- */
256
- export function formatHover(hover: LspHover | null | undefined): string {
257
- if (!hover || !hover.contents) {
258
- return "No hover information available at this position.";
259
- }
260
-
261
- const extractText = (content: any): string => {
262
- if (typeof content === "string") return content;
263
- if (content && typeof content === "object") {
264
- if ("value" in content) return content.value;
265
- if (Array.isArray(content)) return content.map(extractText).join("\n");
266
- }
267
- return String(content);
268
- };
269
-
270
- const rawText = extractText(hover.contents).trim();
271
- // Strip transient LSP loading state markers (e.g. tsserver / vtsls prefixing "(loading...) ")
272
- const cleanText = rawText.replace(/\(loading\.\.\.\)\s*/g, "").trim();
273
- if (!cleanText) return "No hover information available at this position.";
274
- return cleanText.length > MAX_HOVER_CHARS
275
- ? `${cleanText.slice(0, MAX_HOVER_CHARS)}\n[Hover truncated]`
276
- : cleanText;
277
- }
278
-
279
- /**
280
- * Format document symbols (hierarchical or flat)
281
- */
282
- export function formatDocumentSymbols(
283
- symbols: (LspDocumentSymbol | LspSymbolInformation)[] | null | undefined
284
- ): string {
285
- if (!symbols || symbols.length === 0) {
286
- return "No symbols found.";
287
- }
288
-
289
- const lines: string[] = [];
290
- let emitted = 0;
291
- let truncated = false;
292
-
293
- const renderSymbol = (s: any, depth = 0) => {
294
- if (emitted >= MAX_SYMBOLS || depth > MAX_SYMBOL_DEPTH) {
295
- truncated = true;
296
- return;
297
- }
298
- const indent = " ".repeat(depth);
299
- const kind = symbolKindLabel(s.kind);
300
- const range = s.range || s.location?.range;
301
- const line = range ? range.start.line + 1 : 1;
302
- const detail = s.detail ? ` (${clipText(s.detail, 500)})` : "";
303
- lines.push(`${indent}${line}: [${kind}] ${clipText(s.name, 200)}${detail}`);
304
- emitted++;
305
-
306
- if (s.children && Array.isArray(s.children)) {
307
- for (const child of s.children) renderSymbol(child, depth + 1);
308
- }
309
- };
310
-
311
- for (const s of symbols) {
312
- if (emitted >= MAX_SYMBOLS) {
313
- truncated = true;
314
- break;
315
- }
316
- renderSymbol(s, 0);
317
- }
318
-
319
- if (truncated) {
320
- lines.push(`[Truncated: ${emitted}/${symbols.length} symbols shown]`);
321
- }
322
- return lines.join("\n");
323
- }
@@ -1,320 +0,0 @@
1
- import crossSpawnSync from "cross-spawn";
2
- import * as fs from "node:fs";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- import { buildLspEnvironment } from "./lsp_client";
6
- import {
7
- PI_LSP_BIN_DIR,
8
- LSP_SERVERS,
9
- clearExecutableCache,
10
- findExecutable,
11
- } from "./lsp_registry";
12
- import { kernelDebug } from "../safety/kernel_debug";
13
-
14
- const DEFAULT_INSTALL_TIMEOUT_MS = 120_000;
15
-
16
- export interface InstallResult {
17
- success: boolean;
18
- message: string;
19
- binPath?: string;
20
- }
21
-
22
- export interface InstallerSpec {
23
- command: string;
24
- args: string[];
25
- verifyBin: string;
26
- label: string;
27
- timeoutMs?: number;
28
- }
29
-
30
- export interface InstallerCommandResult {
31
- status: number | null;
32
- stdout?: string;
33
- stderr?: string;
34
- error?: Error;
35
- }
36
-
37
- export type InstallerCommandResolver = (
38
- command: string,
39
- ) => string | null;
40
- export type InstallerCommandRunner = (
41
- command: string,
42
- args: string[],
43
- options: {
44
- cwd: string;
45
- env: Record<string, string>;
46
- shell: false;
47
- windowsHide: true;
48
- timeout: number;
49
- encoding: "utf8";
50
- stdio: "pipe";
51
- },
52
- ) => InstallerCommandResult;
53
-
54
- export function ensureLspBinDir(): string {
55
- if (!fs.existsSync(PI_LSP_BIN_DIR)) {
56
- fs.mkdirSync(PI_LSP_BIN_DIR, { recursive: true });
57
- }
58
- return PI_LSP_BIN_DIR;
59
- }
60
-
61
- const NPM_INSTALL = (
62
- packages: string[],
63
- verifyBin: string,
64
- label: string,
65
- ): InstallerSpec => ({
66
- command: "npm",
67
- args: ["install", "-g", ...packages],
68
- verifyBin,
69
- label,
70
- });
71
-
72
- const CARGO_INSTALL = (
73
- crate: string,
74
- version: string,
75
- verifyBin: string,
76
- label: string,
77
- extraArgs: string[] = [],
78
- ): InstallerSpec => ({
79
- command: "cargo",
80
- args: ["install", "--locked", crate, "--version", version, ...extraArgs],
81
- verifyBin,
82
- label,
83
- });
84
-
85
- export function getInstallerSpecs(): Record<string, InstallerSpec[]> {
86
- return {
87
- typescript: [
88
- NPM_INSTALL(
89
- ["@vtsls/language-server@0.3.0", "typescript@7.0.2"],
90
- "vtsls",
91
- "vtsls 0.3.0 and TypeScript 7.0.2",
92
- ),
93
- ],
94
- python: [
95
- {
96
- command: "uv",
97
- args: ["tool", "install", "ty==0.0.83"],
98
- verifyBin: "ty",
99
- label: "Astral ty 0.0.83",
100
- },
101
- NPM_INSTALL(["pyright@1.1.414"], "pyright-langserver", "Pyright 1.1.414"),
102
- ],
103
- go: [
104
- {
105
- command: "go",
106
- args: ["install", "golang.org/x/tools/gopls@v0.23.0"],
107
- verifyBin: "gopls",
108
- label: "gopls v0.23.0",
109
- },
110
- ],
111
- toml: [
112
- CARGO_INSTALL(
113
- "taplo-cli",
114
- "0.10.0",
115
- "taplo",
116
- "Taplo CLI 0.10.0",
117
- ["--features", "lsp"],
118
- ),
119
- ],
120
- shell: [
121
- NPM_INSTALL(
122
- ["bash-language-server@5.8.1"],
123
- "bash-language-server",
124
- "bash-language-server 5.8.1",
125
- ),
126
- ],
127
- html: [
128
- NPM_INSTALL(
129
- ["vscode-langservers-extracted@4.10.0"],
130
- "vscode-html-language-server",
131
- "vscode-langservers-extracted 4.10.0",
132
- ),
133
- ],
134
- json: [
135
- NPM_INSTALL(
136
- ["@biomejs/biome@2.5.14"],
137
- "biome",
138
- "Biome 2.5.14",
139
- ),
140
- NPM_INSTALL(
141
- ["vscode-langservers-extracted@4.10.0"],
142
- "vscode-json-language-server",
143
- "vscode-langservers-extracted 4.10.0",
144
- ),
145
- ],
146
- yaml: [
147
- NPM_INSTALL(
148
- ["yaml-language-server@1.24.0"],
149
- "yaml-language-server",
150
- "yaml-language-server 1.24.0",
151
- ),
152
- ],
153
- docker: [
154
- NPM_INSTALL(
155
- ["dockerfile-language-server-nodejs@0.15.0"],
156
- "docker-langserver",
157
- "dockerfile-language-server-nodejs 0.15.0",
158
- ),
159
- ],
160
- php: [
161
- NPM_INSTALL(
162
- ["intelephense@1.18.5"],
163
- "intelephense",
164
- "Intelephense 1.18.5",
165
- ),
166
- ],
167
- typst: [
168
- CARGO_INSTALL("tinymist", "0.15.2", "tinymist", "Tinymist 0.15.2"),
169
- ],
170
- csharp: [
171
- {
172
- command: "dotnet",
173
- args: ["tool", "install", "-g", "csharp-ls", "--version", "0.28.0"],
174
- verifyBin: "csharp-ls",
175
- label: "csharp-ls 0.28.0",
176
- },
177
- ],
178
- ruby: [
179
- {
180
- command: "gem",
181
- args: ["install", "ruby-lsp", "--version", "0.26.11", "--no-document"],
182
- verifyBin: "ruby-lsp",
183
- label: "ruby-lsp 0.26.11",
184
- },
185
- ],
186
- sql: [
187
- {
188
- command: "go",
189
- args: ["install", "github.com/sqls-server/sqls@v0.2.48"],
190
- verifyBin: "sqls",
191
- label: "sqls v0.2.48",
192
- },
193
- ],
194
- latex: [
195
- CARGO_INSTALL("texlab", "4.3.2", "texlab", "Texlab 4.3.2"),
196
- ],
197
- protobuf: [
198
- CARGO_INSTALL("protols", "0.14.1", "protols", "Protols 0.14.1"),
199
- ],
200
- };
201
- }
202
-
203
- function defaultResolver(command: string): string | null {
204
- return findExecutable(command, [], [process.cwd()]);
205
- }
206
-
207
- function defaultRunner(
208
- command: string,
209
- args: string[],
210
- options: Parameters<InstallerCommandRunner>[2],
211
- ): InstallerCommandResult {
212
- return crossSpawnSync(command, args, options);
213
- }
214
-
215
- export function executeInstallerSpec(
216
- spec: InstallerSpec,
217
- dependencies: {
218
- resolve?: InstallerCommandResolver;
219
- run?: InstallerCommandRunner;
220
- verify?: (binName: string) => InstallResult;
221
- } = {},
222
- ): InstallResult {
223
- const resolve = dependencies.resolve || defaultResolver;
224
- const run = dependencies.run || defaultRunner;
225
- const verify = dependencies.verify || ((binName: string) =>
226
- verifyInstalledBinary(binName));
227
-
228
- let executable: string | null;
229
- try {
230
- executable = resolve(spec.command);
231
- } catch (error) {
232
- return {
233
- success: false,
234
- message: `Unable to resolve trusted ${spec.command} executable: ${error instanceof Error ? error.message : String(error)}`,
235
- };
236
- }
237
- if (!executable) {
238
- return {
239
- success: false,
240
- message: `Required package manager '${spec.command}' was not found in a trusted executable directory.`,
241
- };
242
- }
243
-
244
- try {
245
- const result = run(executable, spec.args, {
246
- cwd: os.homedir(),
247
- env: buildLspEnvironment(),
248
- shell: false,
249
- windowsHide: true,
250
- timeout: spec.timeoutMs || DEFAULT_INSTALL_TIMEOUT_MS,
251
- encoding: "utf8",
252
- stdio: "pipe",
253
- });
254
- if (result.error) throw result.error;
255
- if (result.status !== 0) {
256
- const detail = String(result.stderr || result.stdout || "").trim();
257
- throw new Error(detail || `${spec.command} exited with status ${result.status}`);
258
- }
259
- return verify(spec.verifyBin);
260
- } catch (error) {
261
- return {
262
- success: false,
263
- message: `Failed to install ${spec.label}: ${error instanceof Error ? error.message : String(error)}`,
264
- };
265
- }
266
- }
267
-
268
- function verifyInstalledBinary(binName: string): InstallResult {
269
- clearExecutableCache();
270
- const bin = findExecutable(binName, [], [process.cwd()]);
271
- if (bin) {
272
- return {
273
- success: true,
274
- message: `Successfully installed ${binName} (${bin})`,
275
- binPath: bin,
276
- };
277
- }
278
- return {
279
- success: false,
280
- message: `Installer completed, but trusted binary '${binName}' was not found.`,
281
- };
282
- }
283
-
284
- const MANUAL_INSTALLS: Record<string, string> = {
285
- rust: "Install rust-analyzer through a reviewed rustup toolchain, then rerun /lsp install rust.",
286
- markdown: "Install Marksman 2026-02-08 with your system package manager, then rerun /lsp install markdown.",
287
- cpp: "Install reviewed LLVM/clangd 23.1.2, then rerun /lsp install cpp.",
288
- zig: "Install reviewed ZLS 0.16.0, then rerun /lsp install zig.",
289
- lua: "Install reviewed Lua Language Server 3.19.1, then rerun /lsp install lua.",
290
- };
291
-
292
- export async function installLanguageServer(
293
- languageOrKey: string,
294
- onProgress?: (msg: string) => void,
295
- ): Promise<InstallResult> {
296
- const norm = languageOrKey.toLowerCase().trim();
297
- ensureLspBinDir();
298
-
299
- const manual = MANUAL_INSTALLS[norm];
300
- if (manual) return { success: false, message: manual };
301
-
302
- const specs = getInstallerSpecs()[norm];
303
- if (!specs || specs.length === 0) {
304
- const hint = LSP_SERVERS[norm]?.installHint;
305
- return {
306
- success: false,
307
- message: `No pinned automated installer is available${hint ? `. Manual option: ${hint}` : "."}`,
308
- };
309
- }
310
-
311
- let lastFailure = "No installer attempted";
312
- for (const spec of specs) {
313
- onProgress?.(`Installing ${spec.label} with trusted ${spec.command}...`);
314
- const result = executeInstallerSpec(spec);
315
- if (result.success) return result;
316
- lastFailure = result.message;
317
- kernelDebug(result.message);
318
- }
319
- return { success: false, message: lastFailure };
320
- }