homeagent-runner 0.4.16 → 0.4.18

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.
@@ -0,0 +1,999 @@
1
+ import path from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { lstat, opendir } from 'node:fs/promises';
4
+ import { AppError } from '../shared/protocol.js';
5
+ import { toolEnvironment } from './processes.js';
6
+ const CODE_EXTENSIONS = new Set([
7
+ '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts',
8
+ '.py', '.rs', '.go', '.java', '.c', '.cc', '.cpp', '.h', '.hpp', '.cs', '.json',
9
+ ]);
10
+ function isCodeFile(filename) {
11
+ return CODE_EXTENSIONS.has(path.extname(filename).toLowerCase());
12
+ }
13
+ function extractLeadingDoc(lines, lineIndex) {
14
+ const docLines = [];
15
+ let idx = lineIndex - 1;
16
+ while (idx >= 0 && lines[idx].trim() === '') {
17
+ if (lineIndex - idx > 1)
18
+ break;
19
+ idx--;
20
+ }
21
+ if (idx < 0)
22
+ return undefined;
23
+ const trimmed = lines[idx].trim();
24
+ if (trimmed.endsWith('*/')) {
25
+ const block = [];
26
+ while (idx >= 0) {
27
+ const current = lines[idx].trim();
28
+ block.unshift(current
29
+ .replace(/^\/\*\*?/, '')
30
+ .replace(/\*\/$/, '')
31
+ .replace(/^\*\s?/, '')
32
+ .trim());
33
+ if (current.startsWith('/*'))
34
+ break;
35
+ idx--;
36
+ }
37
+ const text = block.filter(Boolean).join('\n').trim();
38
+ return text || undefined;
39
+ }
40
+ while (idx >= 0) {
41
+ const current = lines[idx].trim();
42
+ if (current.startsWith('///') || current.startsWith('//!') || current.startsWith('//')) {
43
+ docLines.unshift(current.replace(/^\/\/[/!]?\s?/, ''));
44
+ idx--;
45
+ }
46
+ else if (current.startsWith('#') && !current.startsWith('#!')) {
47
+ docLines.unshift(current.replace(/^#+\s?/, ''));
48
+ idx--;
49
+ }
50
+ else {
51
+ break;
52
+ }
53
+ }
54
+ const joined = docLines.join('\n').trim();
55
+ return joined || undefined;
56
+ }
57
+ function extractPythonDocstring(lines, startLineIndex) {
58
+ let idx = startLineIndex + 1;
59
+ while (idx < lines.length && lines[idx].trim() === '')
60
+ idx++;
61
+ if (idx >= lines.length)
62
+ return undefined;
63
+ const first = lines[idx].trim();
64
+ const quote = first.startsWith('"""') ? '"""' : first.startsWith("'''") ? "'''" : undefined;
65
+ if (!quote)
66
+ return undefined;
67
+ const afterOpen = first.slice(3);
68
+ if (afterOpen.endsWith(quote) && afterOpen.length >= 3) {
69
+ return afterOpen.slice(0, -3).trim() || undefined;
70
+ }
71
+ const collected = [afterOpen];
72
+ idx++;
73
+ while (idx < lines.length) {
74
+ const line = lines[idx];
75
+ const endAt = line.indexOf(quote);
76
+ if (endAt >= 0) {
77
+ collected.push(line.slice(0, endAt));
78
+ break;
79
+ }
80
+ collected.push(line.trim());
81
+ idx++;
82
+ }
83
+ return collected.join('\n').trim() || undefined;
84
+ }
85
+ function findBlockEndLine(lines, startIndex, ext) {
86
+ if (ext === '.py') {
87
+ const baseIndent = lines[startIndex].match(/^\s*/)?.[0].length ?? 0;
88
+ let lastContent = startIndex;
89
+ for (let i = startIndex + 1; i < lines.length; i++) {
90
+ const text = lines[i];
91
+ const trimmed = text.trim();
92
+ if (!trimmed || trimmed.startsWith('#'))
93
+ continue;
94
+ const indent = text.match(/^\s*/)?.[0].length ?? 0;
95
+ if (indent <= baseIndent)
96
+ break;
97
+ lastContent = i;
98
+ }
99
+ return lastContent + 1;
100
+ }
101
+ let depth = 0;
102
+ let opened = false;
103
+ for (let i = startIndex; i < lines.length; i++) {
104
+ const line = lines[i];
105
+ for (let c = 0; c < line.length; c++) {
106
+ const ch = line[c];
107
+ if (ch === '/' && line[c + 1] === '/')
108
+ break;
109
+ if (ch === '{') {
110
+ depth++;
111
+ opened = true;
112
+ }
113
+ else if (ch === '}') {
114
+ depth--;
115
+ if (opened && depth <= 0)
116
+ return i + 1;
117
+ }
118
+ }
119
+ if (!opened && line.trim().endsWith(';'))
120
+ return i + 1;
121
+ }
122
+ return startIndex + 1;
123
+ }
124
+ export function parseDocumentIntelligence(text, filename) {
125
+ const ext = path.extname(filename).toLowerCase();
126
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
127
+ const symbols = [];
128
+ const imports = [];
129
+ if (ext === '.py') {
130
+ const containerStack = [];
131
+ for (let i = 0; i < lines.length; i++) {
132
+ const raw = lines[i];
133
+ const trimmed = raw.trim();
134
+ if (!trimmed || trimmed.startsWith('#'))
135
+ continue;
136
+ const indent = raw.match(/^\s*/)?.[0].length ?? 0;
137
+ while (containerStack.length && containerStack[containerStack.length - 1].indent >= indent) {
138
+ containerStack.pop();
139
+ }
140
+ const fromImport = /^from\s+([A-Za-z0-9_.]+)\s+import\s+(.+)$/.exec(trimmed);
141
+ if (fromImport) {
142
+ const mod = fromImport[1];
143
+ const parts = fromImport[2].split(',');
144
+ for (const part of parts) {
145
+ const clean = part.trim();
146
+ if (!clean || clean === '*')
147
+ continue;
148
+ const asMatch = /^([A-Za-z_][A-Za-z0-9_]*)(?:\s+as\s+([A-Za-z_][A-Za-z0-9_]*))?$/.exec(clean);
149
+ if (asMatch) {
150
+ imports.push({
151
+ importedName: asMatch[1],
152
+ localName: asMatch[2] ?? asMatch[1],
153
+ source: mod,
154
+ line: i + 1,
155
+ });
156
+ }
157
+ }
158
+ continue;
159
+ }
160
+ const plainImport = /^import\s+([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z_][A-Za-z0-9_]*))?$/.exec(trimmed);
161
+ if (plainImport) {
162
+ const mod = plainImport[1];
163
+ const local = plainImport[2] ?? mod.split('.')[0];
164
+ imports.push({ importedName: '*', localName: local, source: mod, line: i + 1 });
165
+ continue;
166
+ }
167
+ const classMatch = /^class\s+([A-Za-z_][A-Za-z0-9_]*)\b/.exec(trimmed);
168
+ if (classMatch) {
169
+ const name = classMatch[1];
170
+ const col = raw.indexOf(name) + 1;
171
+ const endLine = findBlockEndLine(lines, i, ext);
172
+ const containerName = containerStack[containerStack.length - 1]?.name;
173
+ const doc = extractPythonDocstring(lines, i) ?? extractLeadingDoc(lines, i);
174
+ symbols.push({
175
+ name,
176
+ kind: 'class',
177
+ line: i + 1,
178
+ column: col,
179
+ endLine,
180
+ endColumn: (lines[endLine - 1]?.length ?? 0) + 1,
181
+ ...(containerName ? { containerName } : {}),
182
+ signature: trimmed.replace(/:\s*$/, ''),
183
+ ...(doc ? { documentation: doc } : {}),
184
+ exported: !name.startsWith('_'),
185
+ });
186
+ containerStack.push({ name, indent });
187
+ continue;
188
+ }
189
+ const defMatch = /^(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/.exec(trimmed);
190
+ if (defMatch) {
191
+ const name = defMatch[1];
192
+ const col = raw.indexOf(name) + 1;
193
+ const endLine = findBlockEndLine(lines, i, ext);
194
+ const containerName = containerStack[containerStack.length - 1]?.name;
195
+ const doc = extractPythonDocstring(lines, i) ?? extractLeadingDoc(lines, i);
196
+ symbols.push({
197
+ name,
198
+ kind: containerName ? 'method' : 'function',
199
+ line: i + 1,
200
+ column: col,
201
+ endLine,
202
+ endColumn: (lines[endLine - 1]?.length ?? 0) + 1,
203
+ ...(containerName ? { containerName } : {}),
204
+ signature: trimmed.replace(/:\s*$/, ''),
205
+ ...(doc ? { documentation: doc } : {}),
206
+ exported: !name.startsWith('_'),
207
+ });
208
+ continue;
209
+ }
210
+ if (indent === 0) {
211
+ const assignMatch = /^([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*[^=]+)?=\s*(.+)$/.exec(trimmed);
212
+ if (assignMatch) {
213
+ const name = assignMatch[1];
214
+ const col = raw.indexOf(name) + 1;
215
+ const doc = extractLeadingDoc(lines, i);
216
+ symbols.push({
217
+ name,
218
+ kind: /^[A-Z0-9_]+$/.test(name) ? 'constant' : 'variable',
219
+ line: i + 1,
220
+ column: col,
221
+ endLine: i + 1,
222
+ endColumn: raw.length + 1,
223
+ signature: trimmed.slice(0, 160),
224
+ ...(doc ? { documentation: doc } : {}),
225
+ exported: !name.startsWith('_'),
226
+ });
227
+ }
228
+ }
229
+ }
230
+ return { symbols, imports };
231
+ }
232
+ // JS/TS/Rust/Go/C-family line + brace tracker
233
+ let braceDepth = 0;
234
+ const containers = [];
235
+ for (let i = 0; i < lines.length; i++) {
236
+ const raw = lines[i];
237
+ const trimmed = raw.trim();
238
+ if (!trimmed || trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*')) {
239
+ continue;
240
+ }
241
+ // Track ES module imports
242
+ const esImport = /^import\s+(?:type\s+)?(.+?)\s+from\s+['"]([^'"]+)['"]/.exec(trimmed);
243
+ if (esImport) {
244
+ const clause = esImport[1].trim();
245
+ const source = esImport[2];
246
+ const namedMatch = /\{([^}]+)\}/.exec(clause);
247
+ if (namedMatch) {
248
+ for (const item of namedMatch[1].split(',')) {
249
+ const clean = item.trim().replace(/^type\s+/, '');
250
+ if (!clean)
251
+ continue;
252
+ const parts = /^([A-Za-z_$][A-Za-z0-9_$]*)(?:\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*))?$/.exec(clean);
253
+ if (parts) {
254
+ imports.push({ importedName: parts[1], localName: parts[2] ?? parts[1], source, line: i + 1 });
255
+ }
256
+ }
257
+ }
258
+ const namespaceMatch = /\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)/.exec(clause);
259
+ if (namespaceMatch) {
260
+ imports.push({ importedName: '*', localName: namespaceMatch[1], source, line: i + 1 });
261
+ }
262
+ const defaultMatch = /^([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*,|$)/.exec(clause);
263
+ if (defaultMatch && defaultMatch[1] !== 'type') {
264
+ imports.push({ importedName: 'default', localName: defaultMatch[1], source, line: i + 1 });
265
+ }
266
+ }
267
+ const cjsRequire = /^(?:const|let|var)\s+(\{[^}]+\}|[A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)/.exec(trimmed);
268
+ if (cjsRequire) {
269
+ const target = cjsRequire[1].trim();
270
+ const source = cjsRequire[2];
271
+ if (target.startsWith('{') && target.endsWith('}')) {
272
+ for (const item of target.slice(1, -1).split(',')) {
273
+ const clean = item.trim();
274
+ const parts = /^([A-Za-z_$][A-Za-z0-9_$]*)(?:\s*:\s*([A-Za-z_$][A-Za-z0-9_$]*))?$/.exec(clean);
275
+ if (parts)
276
+ imports.push({ importedName: parts[1], localName: parts[2] ?? parts[1], source, line: i + 1 });
277
+ }
278
+ }
279
+ else {
280
+ imports.push({ importedName: 'default', localName: target, source, line: i + 1 });
281
+ }
282
+ }
283
+ const currentContainer = containers[containers.length - 1]?.name;
284
+ const exported = /^(?:export\s+|pub(?:\([^)]*\))?\s+)/.test(trimmed) || (ext === '.go' && /^[A-Z]/.test(trimmed.replace(/^(?:func|type|var|const)\s+/, '')));
285
+ const doc = extractLeadingDoc(lines, i);
286
+ const patterns = [
287
+ [/^(?:export\s+(?:default\s+)?)?(?:abstract\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*)/, 'class', true],
288
+ [/^(?:export\s+(?:default\s+)?)?interface\s+([A-Za-z_$][A-Za-z0-9_$]*)/, 'interface', true],
289
+ [/^(?:export\s+)?type\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*=/, 'type', false],
290
+ [/^(?:export\s+)?(?:const\s+)?enum\s+([A-Za-z_$][A-Za-z0-9_$]*)/, 'enum', true],
291
+ [/^(?:export\s+(?:default\s+)?)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][A-Za-z0-9_$]*)/, 'function', false],
292
+ [/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=]+)?=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*=>/, 'function', false],
293
+ [/^(?:export\s+)?const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=]+)?=/, 'constant', false],
294
+ [/^(?:export\s+)?(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=]+)?=/, 'variable', false],
295
+ [/^(?:pub(?:\([^)]*\))?\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*)/, 'struct', true],
296
+ [/^(?:pub(?:\([^)]*\))?\s+)?trait\s+([A-Za-z_][A-Za-z0-9_]*)/, 'trait', true],
297
+ [/^impl(?:<[^>]*>)?\s+(?:[A-Za-z0-9_:<>]+\s+for\s+)?([A-Za-z_][A-Za-z0-9_]*)/, 'impl', true],
298
+ [/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*)/, 'function', false],
299
+ [/^func\s+(?:\([^)]+\)\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*\(/, 'function', false],
300
+ [/^type\s+([A-Za-z_][A-Za-z0-9_]*)\s+struct\b/, 'struct', true],
301
+ [/^type\s+([A-Za-z_][A-Za-z0-9_]*)\s+interface\b/, 'interface', true],
302
+ ];
303
+ let matched = false;
304
+ for (const [regex, kind, isContainer] of patterns) {
305
+ if ((kind === 'constant' || kind === 'variable') && braceDepth > 0)
306
+ continue;
307
+ const m = regex.exec(trimmed);
308
+ if (m) {
309
+ const name = m[1];
310
+ const col = raw.indexOf(name) + 1;
311
+ const endLine = findBlockEndLine(lines, i, ext);
312
+ const resolvedKind = currentContainer && kind === 'function' ? 'method' : kind;
313
+ symbols.push({
314
+ name,
315
+ kind: resolvedKind,
316
+ line: i + 1,
317
+ column: col,
318
+ endLine,
319
+ endColumn: (lines[endLine - 1]?.length ?? 0) + 1,
320
+ ...(currentContainer ? { containerName: currentContainer } : {}),
321
+ signature: trimmed.replace(/\s*\{$/, '').slice(0, 180),
322
+ ...(doc ? { documentation: doc } : {}),
323
+ exported: exported || (ext === '.go' && /^[A-Z]/.test(name)),
324
+ });
325
+ if (isContainer) {
326
+ containers.push({ name, depth: braceDepth });
327
+ }
328
+ matched = true;
329
+ break;
330
+ }
331
+ }
332
+ if (!matched && currentContainer && braceDepth === (containers[containers.length - 1]?.depth ?? 0) + 1) {
333
+ const methodMatch = /^(?:(?:public|private|protected|readonly|static|async|override|get|set)\s+)*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?:<[^>]*>)?\s*\([^;]*\)\s*(?::\s*[^{;]+)?\{?$/.exec(trimmed);
334
+ if (methodMatch) {
335
+ const name = methodMatch[1];
336
+ if (!['if', 'for', 'while', 'switch', 'catch', 'return', 'new', 'super'].includes(name)) {
337
+ const col = raw.indexOf(name) + 1;
338
+ const endLine = findBlockEndLine(lines, i, ext);
339
+ symbols.push({
340
+ name,
341
+ kind: 'method',
342
+ line: i + 1,
343
+ column: col,
344
+ endLine,
345
+ endColumn: (lines[endLine - 1]?.length ?? 0) + 1,
346
+ containerName: currentContainer,
347
+ signature: trimmed.replace(/\s*\{$/, '').slice(0, 180),
348
+ ...(doc ? { documentation: doc } : {}),
349
+ exported: false,
350
+ });
351
+ }
352
+ }
353
+ }
354
+ for (let c = 0; c < raw.length; c++) {
355
+ const ch = raw[c];
356
+ if (ch === '/' && raw[c + 1] === '/')
357
+ break;
358
+ if (ch === '{')
359
+ braceDepth++;
360
+ else if (ch === '}') {
361
+ braceDepth = Math.max(0, braceDepth - 1);
362
+ while (containers.length && containers[containers.length - 1].depth >= braceDepth) {
363
+ containers.pop();
364
+ }
365
+ }
366
+ }
367
+ }
368
+ return { symbols, imports };
369
+ }
370
+ function identifierAtPosition(lines, line, column) {
371
+ if (!line || line < 1 || line > lines.length)
372
+ return undefined;
373
+ const text = lines[line - 1];
374
+ const regex = /[A-Za-z_$][A-Za-z0-9_$]*/g;
375
+ const tokens = [];
376
+ for (const match of text.matchAll(regex)) {
377
+ const start = (match.index ?? 0) + 1;
378
+ tokens.push({ word: match[0], start, end: start + match[0].length - 1 });
379
+ }
380
+ if (!tokens.length)
381
+ return undefined;
382
+ if (column !== undefined) {
383
+ const exact = tokens.find(token => column >= token.start && column <= token.end + 1);
384
+ if (exact)
385
+ return exact.word;
386
+ }
387
+ const keywords = new Set(['import', 'from', 'export', 'default', 'const', 'let', 'var', 'function', 'async', 'await', 'return', 'class', 'interface', 'type', 'enum', 'def', 'fn', 'pub', 'struct', 'trait', 'impl', 'func']);
388
+ return (tokens.find(token => !keywords.has(token.word)) ?? tokens[0]).word;
389
+ }
390
+ export class Lsp {
391
+ policy;
392
+ files;
393
+ git;
394
+ constructor(policy, files, git) {
395
+ this.policy = policy;
396
+ this.files = files;
397
+ this.git = git;
398
+ }
399
+ async listSourceFiles(project, subPath, respectGitIgnore, signal) {
400
+ let sourcePaths;
401
+ if (respectGitIgnore) {
402
+ try {
403
+ sourcePaths = await this.git.listFiles(project, subPath, signal);
404
+ }
405
+ catch (error) {
406
+ if (error instanceof AppError && error.code === 'search_source_limit')
407
+ throw error;
408
+ }
409
+ }
410
+ if (sourcePaths !== undefined) {
411
+ const filtered = sourcePaths.filter(isCodeFile);
412
+ return { files: filtered.slice(0, 2000), gitIgnoreApplied: true, truncated: filtered.length > 2000 };
413
+ }
414
+ const start = await this.policy.resolve(project, subPath);
415
+ const pending = [start];
416
+ const discovered = [];
417
+ let scanned = 0, truncated = false;
418
+ while (pending.length && discovered.length < 2000) {
419
+ if (signal?.aborted)
420
+ throw new AppError('cancelled', 'LSP workspace scan cancelled');
421
+ if (++scanned > 10000) {
422
+ truncated = true;
423
+ break;
424
+ }
425
+ const current = pending.pop();
426
+ let stat;
427
+ try {
428
+ await this.policy.resolve(project, current);
429
+ stat = await lstat(current);
430
+ }
431
+ catch {
432
+ continue;
433
+ }
434
+ if (stat.isDirectory()) {
435
+ const dir = await opendir(current);
436
+ for await (const entry of dir) {
437
+ if (pending.length + scanned >= 10000) {
438
+ truncated = true;
439
+ break;
440
+ }
441
+ if (!entry.isSymbolicLink() && entry.name !== 'node_modules' && entry.name !== 'dist' && !project.deniedNames.includes(entry.name)) {
442
+ pending.push(path.join(current, entry.name));
443
+ }
444
+ }
445
+ }
446
+ else if (stat.isFile() && isCodeFile(current)) {
447
+ discovered.push(path.relative(project.root, current));
448
+ }
449
+ }
450
+ return { files: discovered.sort(), gitIgnoreApplied: false, truncated };
451
+ }
452
+ async readText(project, filePath) {
453
+ const snapshot = await this.files.snapshot(project, filePath);
454
+ if (snapshot.bytes.includes(0))
455
+ throw new AppError('binary_file', 'LSP tools require UTF-8 text files');
456
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(snapshot.bytes);
457
+ const lines = text.replace(/\r\n/g, '\n').split('\n');
458
+ return { text, lines, sha256: snapshot.sha256 };
459
+ }
460
+ async resolveModuleFile(project, fromFile, specifier) {
461
+ const fromDir = path.dirname(path.join(project.root, fromFile));
462
+ const candidates = [];
463
+ if (specifier.startsWith('.')) {
464
+ const base = path.resolve(fromDir, specifier);
465
+ const ext = path.extname(base);
466
+ if (ext === '.js' || ext === '.mjs' || ext === '.cjs') {
467
+ const stem = base.slice(0, -ext.length);
468
+ candidates.push(`${stem}.ts`, `${stem}.tsx`, base, `${stem}.d.ts`);
469
+ }
470
+ else if (ext) {
471
+ candidates.push(base);
472
+ }
473
+ else {
474
+ candidates.push(`${base}.ts`, `${base}.tsx`, `${base}.js`, `${base}.jsx`, `${base}.mjs`, `${base}.cjs`, `${base}.py`, `${base}.rs`, `${base}.go`, path.join(base, 'index.ts'), path.join(base, 'index.tsx'), path.join(base, 'index.js'), path.join(base, '__init__.py'));
475
+ }
476
+ }
477
+ else if (/^[A-Za-z_][A-Za-z0-9_.]*$/.test(specifier)) {
478
+ const pyRel = specifier.replace(/\./g, path.sep);
479
+ candidates.push(path.join(fromDir, `${pyRel}.py`), path.join(project.root, `${pyRel}.py`), path.join(project.root, pyRel, '__init__.py'));
480
+ }
481
+ for (const candidate of candidates) {
482
+ try {
483
+ const resolved = await this.policy.resolve(project, candidate);
484
+ const stat = await lstat(resolved);
485
+ if (stat.isFile())
486
+ return path.relative(project.root, resolved);
487
+ }
488
+ catch { }
489
+ }
490
+ return undefined;
491
+ }
492
+ async documentSymbols(project, args) {
493
+ const { text, sha256 } = await this.readText(project, args.path);
494
+ const { symbols, imports } = parseDocumentIntelligence(text, args.path);
495
+ return { path: args.path, sha256, symbols, imports };
496
+ }
497
+ async workspaceSymbols(project, args, signal) {
498
+ const { files, gitIgnoreApplied, truncated: scanTruncated } = await this.listSourceFiles(project, args.path, args.respectGitIgnore, signal);
499
+ const query = args.query?.toLowerCase();
500
+ const matched = [];
501
+ let filesScanned = 0;
502
+ for (const file of files) {
503
+ if (signal?.aborted)
504
+ throw new AppError('cancelled', 'LSP symbol search cancelled');
505
+ try {
506
+ const { text } = await this.readText(project, file);
507
+ filesScanned++;
508
+ const { symbols } = parseDocumentIntelligence(text, file);
509
+ for (const sym of symbols) {
510
+ if (args.exportedOnly && !sym.exported)
511
+ continue;
512
+ if (args.kind && sym.kind !== args.kind)
513
+ continue;
514
+ const lower = sym.name.toLowerCase();
515
+ if (query && !lower.includes(query))
516
+ continue;
517
+ const score = !query ? 1 : (lower === query ? 3 : lower.startsWith(query) ? 2 : 1);
518
+ matched.push({ path: file, ...sym, score });
519
+ }
520
+ }
521
+ catch { }
522
+ }
523
+ matched.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name) || a.path.localeCompare(b.path) || a.line - b.line);
524
+ const truncated = scanTruncated || matched.length > args.limit;
525
+ return {
526
+ symbols: matched.slice(0, args.limit).map(({ score: _score, ...item }) => item),
527
+ filesScanned,
528
+ gitIgnoreApplied,
529
+ truncated,
530
+ };
531
+ }
532
+ async resolveTargetSymbol(project, args) {
533
+ const doc = await this.readText(project, args.path);
534
+ const symbol = args.symbol?.trim() || identifierAtPosition(doc.lines, args.line, args.column);
535
+ if (!symbol)
536
+ throw new AppError('symbol_not_found', 'No identifier found at the requested position; provide symbol or a valid 1-based line/column');
537
+ return { symbol, doc };
538
+ }
539
+ async definition(project, args, signal) {
540
+ const { symbol, doc } = await this.resolveTargetSymbol(project, args);
541
+ const localIntel = parseDocumentIntelligence(doc.text, args.path);
542
+ const previewOf = (lines, startLine, endLine) => lines.slice(Math.max(0, startLine - 1), Math.min(lines.length, startLine + 6, endLine)).join('\n');
543
+ const localDefs = localIntel.symbols
544
+ .filter(item => item.name === symbol)
545
+ .map(item => ({ path: args.path, ...item, preview: previewOf(doc.lines, item.line, item.endLine) }));
546
+ if (localDefs.length) {
547
+ return { symbol, resolvedVia: 'local', definitions: localDefs };
548
+ }
549
+ const importBinding = localIntel.imports.find(imp => imp.localName === symbol);
550
+ if (importBinding) {
551
+ const targetFile = await this.resolveModuleFile(project, args.path, importBinding.source);
552
+ if (targetFile) {
553
+ try {
554
+ const targetDoc = await this.readText(project, targetFile);
555
+ const targetIntel = parseDocumentIntelligence(targetDoc.text, targetFile);
556
+ const wanted = importBinding.importedName === 'default' || importBinding.importedName === '*'
557
+ ? symbol
558
+ : importBinding.importedName;
559
+ const importedDefs = targetIntel.symbols
560
+ .filter(item => item.name === wanted || (importBinding.importedName === 'default' && item.exported))
561
+ .map(item => ({ path: targetFile, ...item, preview: previewOf(targetDoc.lines, item.line, item.endLine) }));
562
+ if (importedDefs.length) {
563
+ return { symbol, resolvedVia: 'import', importedFrom: importBinding.source, definitions: importedDefs };
564
+ }
565
+ }
566
+ catch { }
567
+ }
568
+ }
569
+ const { files } = await this.listSourceFiles(project, '.', args.respectGitIgnore, signal);
570
+ const workspaceDefs = [];
571
+ for (const file of files) {
572
+ if (file === args.path)
573
+ continue;
574
+ if (signal?.aborted)
575
+ throw new AppError('cancelled', 'LSP definition lookup cancelled');
576
+ try {
577
+ const fileDoc = await this.readText(project, file);
578
+ const intel = parseDocumentIntelligence(fileDoc.text, file);
579
+ for (const item of intel.symbols) {
580
+ if (item.name === symbol) {
581
+ workspaceDefs.push({ path: file, ...item, preview: previewOf(fileDoc.lines, item.line, item.endLine) });
582
+ }
583
+ }
584
+ }
585
+ catch { }
586
+ }
587
+ workspaceDefs.sort((a, b) => Number(b.exported) - Number(a.exported) || a.path.localeCompare(b.path) || a.line - b.line);
588
+ return {
589
+ symbol,
590
+ resolvedVia: workspaceDefs.length ? 'workspace' : 'none',
591
+ definitions: workspaceDefs.slice(0, 20),
592
+ };
593
+ }
594
+ async references(project, args, signal) {
595
+ const { symbol } = await this.resolveTargetSymbol(project, args);
596
+ const escaped = symbol.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
597
+ const wordRegex = new RegExp(`(?<![A-Za-z0-9_$])${escaped}(?![A-Za-z0-9_$])`, 'g');
598
+ const { files, gitIgnoreApplied, truncated: scanTruncated } = await this.listSourceFiles(project, '.', args.respectGitIgnore, signal);
599
+ const orderedFiles = [args.path, ...files.filter(f => f !== args.path)];
600
+ const references = [];
601
+ let filesScanned = 0, truncated = scanTruncated;
602
+ for (const file of orderedFiles) {
603
+ if (signal?.aborted)
604
+ throw new AppError('cancelled', 'LSP references search cancelled');
605
+ try {
606
+ const { text, lines } = await this.readText(project, file);
607
+ filesScanned++;
608
+ const intel = parseDocumentIntelligence(text, file);
609
+ const declLines = new Set(intel.symbols.filter(s => s.name === symbol).map(s => s.line));
610
+ const importLines = new Set(intel.imports.filter(imp => imp.localName === symbol || imp.importedName === symbol).map(imp => imp.line));
611
+ for (let i = 0; i < lines.length; i++) {
612
+ const lineText = lines[i];
613
+ const trimmed = lineText.trim();
614
+ if (trimmed.startsWith('//') || trimmed.startsWith('#') || trimmed.startsWith('*') || trimmed.startsWith('/*'))
615
+ continue;
616
+ const codePart = lineText.split('//')[0];
617
+ for (const match of codePart.matchAll(wordRegex)) {
618
+ const lineNum = i + 1;
619
+ const isDeclaration = declLines.has(lineNum);
620
+ const isImport = importLines.has(lineNum);
621
+ if (!args.includeDeclaration && isDeclaration)
622
+ continue;
623
+ if (references.length >= args.limit) {
624
+ truncated = true;
625
+ break;
626
+ }
627
+ const context = args.contextLines > 0
628
+ ? {
629
+ startLine: Math.max(0, i - args.contextLines) + 1,
630
+ text: lines.slice(Math.max(0, i - args.contextLines), i + args.contextLines + 1).map(l => l.slice(0, 500)).join('\n'),
631
+ }
632
+ : undefined;
633
+ references.push({
634
+ path: file,
635
+ line: lineNum,
636
+ column: (match.index ?? 0) + 1,
637
+ text: lineText.slice(0, 500),
638
+ isDeclaration,
639
+ isImport,
640
+ ...(context ? { context } : {}),
641
+ });
642
+ }
643
+ if (truncated && references.length >= args.limit)
644
+ break;
645
+ }
646
+ }
647
+ catch { }
648
+ if (truncated && references.length >= args.limit)
649
+ break;
650
+ }
651
+ return {
652
+ symbol,
653
+ references,
654
+ filesScanned,
655
+ gitIgnoreApplied,
656
+ truncated,
657
+ };
658
+ }
659
+ async hover(project, args, signal) {
660
+ const resolved = await this.definition(project, args, signal);
661
+ const primary = resolved.definitions[0];
662
+ if (!primary) {
663
+ return { symbol: resolved.symbol, found: false };
664
+ }
665
+ return {
666
+ symbol: resolved.symbol,
667
+ found: true,
668
+ kind: primary.kind,
669
+ signature: primary.signature,
670
+ ...(primary.documentation ? { documentation: primary.documentation } : {}),
671
+ ...(primary.containerName ? { containerName: primary.containerName } : {}),
672
+ exported: primary.exported,
673
+ resolvedVia: resolved.resolvedVia,
674
+ definedAt: {
675
+ path: primary.path,
676
+ line: primary.line,
677
+ column: primary.column,
678
+ endLine: primary.endLine,
679
+ },
680
+ preview: primary.preview,
681
+ };
682
+ }
683
+ async analyzeFileDiagnostics(project, filePath, tsModule) {
684
+ const { text, lines } = await this.readText(project, filePath);
685
+ const ext = path.extname(filePath).toLowerCase();
686
+ const items = [];
687
+ if (ext === '.json') {
688
+ try {
689
+ JSON.parse(text);
690
+ }
691
+ catch (error) {
692
+ const message = error instanceof Error ? error.message : 'Invalid JSON';
693
+ const posMatch = /position\s+(\d+)/i.exec(message);
694
+ let line = 1, column = 1;
695
+ if (posMatch) {
696
+ const offset = Number(posMatch[1]);
697
+ const prefix = text.slice(0, offset);
698
+ const split = prefix.split('\n');
699
+ line = split.length;
700
+ column = split[split.length - 1].length + 1;
701
+ }
702
+ items.push({ path: filePath, line, column, severity: 'error', code: 'json_syntax', message, source: 'builtin-json' });
703
+ }
704
+ return items;
705
+ }
706
+ let tsChecked = false;
707
+ if (tsModule?.createSourceFile && tsModule?.ScriptKind && ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'].includes(ext)) {
708
+ try {
709
+ const scriptKind = ext === '.tsx' ? tsModule.ScriptKind.TSX : ext === '.jsx' ? tsModule.ScriptKind.JSX : ext.includes('ts') ? tsModule.ScriptKind.TS : tsModule.ScriptKind.JS;
710
+ const sourceFile = tsModule.createSourceFile(filePath, text, tsModule.ScriptTarget?.Latest ?? 99, true, scriptKind);
711
+ const parseDiagnostics = sourceFile.parseDiagnostics ?? [];
712
+ for (const diag of parseDiagnostics) {
713
+ const pos = typeof sourceFile.getLineAndCharacterOfPosition === 'function'
714
+ ? sourceFile.getLineAndCharacterOfPosition(diag.start ?? 0)
715
+ : (typeof tsModule.getLineAndCharacterOfPosition === 'function' ? tsModule.getLineAndCharacterOfPosition(sourceFile, diag.start ?? 0) : { line: 0, character: 0 });
716
+ const msg = typeof tsModule.flattenDiagnosticMessageText === 'function'
717
+ ? tsModule.flattenDiagnosticMessageText(diag.messageText, '\n')
718
+ : String(diag.messageText ?? 'Syntax error');
719
+ items.push({
720
+ path: filePath,
721
+ line: pos.line + 1,
722
+ column: pos.character + 1,
723
+ severity: 'error',
724
+ code: `TS${diag.code}`,
725
+ message: msg,
726
+ source: 'typescript',
727
+ });
728
+ }
729
+ tsChecked = true;
730
+ }
731
+ catch { }
732
+ }
733
+ if (!tsChecked) {
734
+ // Lightweight bracket/delimiter balance check for non-TS files
735
+ const stack = [];
736
+ const pairs = { '(': ')', '[': ']', '{': '}' };
737
+ const closing = { ')': '(', ']': '[', '}': '{' };
738
+ for (let i = 0; i < lines.length; i++) {
739
+ const line = lines[i];
740
+ let inQuote = null;
741
+ for (let c = 0; c < line.length; c++) {
742
+ const ch = line[c];
743
+ if (!inQuote && ((ch === '/' && line[c + 1] === '/') || (ext === '.py' && ch === '#')))
744
+ break;
745
+ if (ch === '"' || ch === "'") {
746
+ if (inQuote === ch && line[c - 1] !== '\\')
747
+ inQuote = null;
748
+ else if (!inQuote)
749
+ inQuote = ch;
750
+ continue;
751
+ }
752
+ if (inQuote)
753
+ continue;
754
+ if (pairs[ch])
755
+ stack.push({ ch, line: i + 1, col: c + 1 });
756
+ else if (closing[ch]) {
757
+ const last = stack.pop();
758
+ if (!last || last.ch !== closing[ch]) {
759
+ items.push({
760
+ path: filePath,
761
+ line: i + 1,
762
+ column: c + 1,
763
+ severity: 'error',
764
+ code: 'unmatched_delimiter',
765
+ message: `Unmatched closing '${ch}'`,
766
+ source: 'builtin-syntax',
767
+ });
768
+ break;
769
+ }
770
+ }
771
+ }
772
+ }
773
+ if (stack.length && items.length === 0) {
774
+ const unclosed = stack[stack.length - 1];
775
+ items.push({
776
+ path: filePath,
777
+ line: unclosed.line,
778
+ column: unclosed.col,
779
+ severity: 'error',
780
+ code: 'unclosed_delimiter',
781
+ message: `Unclosed '${unclosed.ch}'`,
782
+ source: 'builtin-syntax',
783
+ });
784
+ }
785
+ }
786
+ // Check unresolved relative imports in JS/TS/Python
787
+ const { imports } = parseDocumentIntelligence(text, filePath);
788
+ const seenImports = new Set();
789
+ for (const imp of imports) {
790
+ if (!imp.source.startsWith('.'))
791
+ continue;
792
+ const key = `${imp.line}:${imp.source}`;
793
+ if (seenImports.has(key))
794
+ continue;
795
+ seenImports.add(key);
796
+ const resolved = await this.resolveModuleFile(project, filePath, imp.source);
797
+ if (!resolved) {
798
+ const col = Math.max(1, (lines[imp.line - 1]?.indexOf(imp.source) ?? 0) + 1);
799
+ items.push({
800
+ path: filePath,
801
+ line: imp.line,
802
+ column: col,
803
+ severity: 'error',
804
+ code: 'unresolved_import',
805
+ message: `Cannot resolve relative import '${imp.source}'`,
806
+ source: 'builtin-imports',
807
+ });
808
+ }
809
+ }
810
+ return items;
811
+ }
812
+ async queryExternalLspDiagnostics(project, targetFiles, executableInput, extraArgs, signal) {
813
+ const alias = Object.hasOwn(project.commandAliases, executableInput) ? project.commandAliases[executableInput] : undefined;
814
+ const executable = alias?.executable ?? executableInput;
815
+ const argv = [...(alias?.args ?? []), ...extraArgs];
816
+ if (!alias)
817
+ this.policy.command(project, executable);
818
+ else if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(executable)) {
819
+ throw new AppError('command_denied', 'Command aliases must resolve to an executable, not a .cmd/.bat wrapper');
820
+ }
821
+ const docs = [];
822
+ for (const relPath of targetFiles.slice(0, 16)) {
823
+ const { text } = await this.readText(project, relPath);
824
+ const absPath = await this.policy.resolve(project, relPath);
825
+ const normalized = absPath.split(path.sep).join('/');
826
+ const uri = normalized.startsWith('/') ? `file://${normalized}` : `file:///${normalized}`;
827
+ const ext = path.extname(relPath).toLowerCase();
828
+ const languageId = ext === '.py' ? 'python' : ext === '.rs' ? 'rust' : ext === '.go' ? 'go' : ext.includes('ts') ? 'typescript' : 'javascript';
829
+ docs.push({ uri, relPath, text, languageId });
830
+ }
831
+ const rootNormalized = project.root.split(path.sep).join('/');
832
+ const rootUri = rootNormalized.startsWith('/') ? `file://${rootNormalized}` : `file:///${rootNormalized}`;
833
+ const collected = [];
834
+ await new Promise((resolve, reject) => {
835
+ const child = spawn(executable, argv, {
836
+ cwd: project.root,
837
+ shell: false,
838
+ windowsHide: true,
839
+ env: toolEnvironment(),
840
+ stdio: 'pipe',
841
+ });
842
+ let buffer = Buffer.alloc(0);
843
+ let settled = false;
844
+ const finish = (err) => {
845
+ if (settled)
846
+ return;
847
+ settled = true;
848
+ clearTimeout(timer);
849
+ try {
850
+ child.kill();
851
+ }
852
+ catch { }
853
+ if (err)
854
+ reject(err);
855
+ else
856
+ resolve();
857
+ };
858
+ const timer = setTimeout(() => finish(), 4000).unref();
859
+ signal?.addEventListener('abort', () => finish(new AppError('cancelled', 'External LSP query cancelled')), { once: true });
860
+ child.stdin.on('error', () => { });
861
+ child.once('error', err => finish(new AppError('lsp_server_failed', `Failed to start LSP server: ${err.message}`)));
862
+ child.once('close', () => finish());
863
+ const send = (payload) => {
864
+ const json = Buffer.from(JSON.stringify(payload), 'utf8');
865
+ child.stdin.write(`Content-Length: ${json.length}\r\n\r\n`);
866
+ child.stdin.write(json);
867
+ };
868
+ let openedCount = 0;
869
+ const handleMessage = (msg) => {
870
+ if (msg.id === 1 && msg.result) {
871
+ send({ jsonrpc: '2.0', method: 'initialized', params: {} });
872
+ for (const doc of docs) {
873
+ send({
874
+ jsonrpc: '2.0',
875
+ method: 'textDocument/didOpen',
876
+ params: { textDocument: { uri: doc.uri, languageId: doc.languageId, version: 1, text: doc.text } },
877
+ });
878
+ }
879
+ if (!docs.length)
880
+ finish();
881
+ }
882
+ else if (msg.method === 'textDocument/publishDiagnostics' && msg.params) {
883
+ const uri = String(msg.params.uri ?? '');
884
+ const matchedDoc = docs.find(d => d.uri.toLowerCase() === uri.toLowerCase());
885
+ const filePath = matchedDoc?.relPath ?? uri;
886
+ for (const d of msg.params.diagnostics ?? []) {
887
+ const line = (d.range?.start?.line ?? 0) + 1;
888
+ const column = (d.range?.start?.character ?? 0) + 1;
889
+ const sev = d.severity === 1 ? 'error' : d.severity === 2 ? 'warning' : 'info';
890
+ collected.push({
891
+ path: filePath,
892
+ line,
893
+ column,
894
+ severity: sev,
895
+ code: String(d.code ?? 'lsp'),
896
+ message: String(d.message ?? ''),
897
+ source: String(d.source ?? path.basename(executable)),
898
+ });
899
+ }
900
+ openedCount++;
901
+ if (openedCount >= docs.length) {
902
+ send({ jsonrpc: '2.0', id: 2, method: 'shutdown', params: null });
903
+ finish();
904
+ }
905
+ }
906
+ };
907
+ child.stdout.on('data', (chunk) => {
908
+ buffer = Buffer.concat([buffer, chunk]);
909
+ while (true) {
910
+ const headerEnd = buffer.indexOf('\r\n\r\n');
911
+ if (headerEnd < 0)
912
+ break;
913
+ const header = buffer.subarray(0, headerEnd).toString('ascii');
914
+ const match = /Content-Length:\s*(\d+)/i.exec(header);
915
+ if (!match) {
916
+ finish();
917
+ return;
918
+ }
919
+ const length = Number(match[1]);
920
+ const bodyStart = headerEnd + 4;
921
+ if (buffer.length < bodyStart + length)
922
+ break;
923
+ const body = buffer.subarray(bodyStart, bodyStart + length).toString('utf8');
924
+ buffer = buffer.subarray(bodyStart + length);
925
+ try {
926
+ handleMessage(JSON.parse(body));
927
+ }
928
+ catch { }
929
+ }
930
+ });
931
+ send({
932
+ jsonrpc: '2.0',
933
+ id: 1,
934
+ method: 'initialize',
935
+ params: {
936
+ processId: process.pid,
937
+ rootUri,
938
+ capabilities: { textDocument: { publishDiagnostics: {} } },
939
+ },
940
+ });
941
+ });
942
+ return collected;
943
+ }
944
+ async diagnostics(project, principal, args, signal) {
945
+ let targetFiles;
946
+ if (args.path && args.path !== '.') {
947
+ const resolved = await this.policy.resolve(project, args.path);
948
+ const stat = await lstat(resolved);
949
+ if (stat.isFile()) {
950
+ targetFiles = [path.relative(project.root, resolved)];
951
+ }
952
+ else {
953
+ targetFiles = (await this.listSourceFiles(project, args.path, args.respectGitIgnore, signal)).files;
954
+ }
955
+ }
956
+ else {
957
+ targetFiles = (await this.listSourceFiles(project, '.', args.respectGitIgnore, signal)).files;
958
+ }
959
+ if (args.serverExecutable) {
960
+ if (!principal.scopes.includes('execute') || project.readOnly) {
961
+ throw new AppError('forbidden', 'External LSP server execution requires execute scope on a writable project');
962
+ }
963
+ const external = await this.queryExternalLspDiagnostics(project, targetFiles, args.serverExecutable, args.serverArgs, signal);
964
+ return {
965
+ diagnostics: external.slice(0, args.limit),
966
+ filesChecked: Math.min(targetFiles.length, 16),
967
+ engine: 'external-lsp',
968
+ truncated: external.length > args.limit,
969
+ };
970
+ }
971
+ let tsModule;
972
+ try {
973
+ const mod = await import('typescript');
974
+ tsModule = mod.default ?? mod;
975
+ }
976
+ catch { }
977
+ const diagnostics = [];
978
+ let filesChecked = 0;
979
+ for (const file of targetFiles.slice(0, 200)) {
980
+ if (signal?.aborted)
981
+ throw new AppError('cancelled', 'LSP diagnostics cancelled');
982
+ try {
983
+ const fileDiags = await this.analyzeFileDiagnostics(project, file, tsModule);
984
+ filesChecked++;
985
+ diagnostics.push(...fileDiags);
986
+ if (diagnostics.length >= args.limit)
987
+ break;
988
+ }
989
+ catch { }
990
+ }
991
+ return {
992
+ diagnostics: diagnostics.slice(0, args.limit),
993
+ filesChecked,
994
+ engine: tsModule ? 'builtin+typescript' : 'builtin',
995
+ truncated: diagnostics.length > args.limit || targetFiles.length > 200,
996
+ };
997
+ }
998
+ }
999
+ //# sourceMappingURL=lsp.js.map