@mumbrane/leto 0.0.0-stage → 0.19.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.
- package/README.md +395 -2
- package/bin/leto.js +8 -0
- package/evals/core/suite.json +249 -0
- package/index.js +12 -0
- package/package.json +43 -4
- package/src/agent.js +572 -0
- package/src/agents.js +68 -0
- package/src/anthropic.js +204 -0
- package/src/browser.js +427 -0
- package/src/btw.js +56 -0
- package/src/checkpoints.js +90 -0
- package/src/ci.js +115 -0
- package/src/cli.js +1926 -0
- package/src/client.js +111 -0
- package/src/config.js +205 -0
- package/src/documents.js +198 -0
- package/src/eval.js +289 -0
- package/src/hooks.js +115 -0
- package/src/ide.js +231 -0
- package/src/input.js +148 -0
- package/src/jobs.js +97 -0
- package/src/legacy.js +41 -0
- package/src/lsp.js +401 -0
- package/src/markdown.js +153 -0
- package/src/mcp.js +346 -0
- package/src/memory.js +136 -0
- package/src/orchestrator.js +141 -0
- package/src/patching.js +185 -0
- package/src/permissions.js +75 -0
- package/src/plugins.js +118 -0
- package/src/policy.js +74 -0
- package/src/pricing.js +67 -0
- package/src/processes.js +139 -0
- package/src/prompt.js +134 -0
- package/src/prompts.js +189 -0
- package/src/providers.js +59 -0
- package/src/repomap.js +211 -0
- package/src/sandbox.js +90 -0
- package/src/sdk.js +220 -0
- package/src/selftool.js +238 -0
- package/src/serve.js +233 -0
- package/src/session.js +168 -0
- package/src/setup.js +157 -0
- package/src/skills.js +125 -0
- package/src/theme.js +185 -0
- package/src/toolcalls.js +257 -0
- package/src/tools.js +976 -0
- package/src/tui.js +1179 -0
- package/src/ui.js +454 -0
- package/src/update.js +33 -0
- package/src/usage.js +83 -0
- package/src/verify.js +131 -0
- package/src/version.js +3 -0
- package/src/worktree.js +87 -0
- package/vscode/extension.js +132 -0
- package/vscode/package.json +21 -0
package/src/lsp.js
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
// Language servers (LSP): precise code navigation and real compiler errors.
|
|
2
|
+
//
|
|
3
|
+
// leto starts the language server a project already uses, when it is
|
|
4
|
+
// installed, and talks to it over stdio:
|
|
5
|
+
// TypeScript/JavaScript typescript-language-server (global or node_modules/.bin)
|
|
6
|
+
// Python pyright-langserver, or pylsp
|
|
7
|
+
// Go gopls
|
|
8
|
+
// Rust rust-analyzer
|
|
9
|
+
// C/C++/Objective-C clangd
|
|
10
|
+
// Add or override servers in ~/.leto/config.json:
|
|
11
|
+
// "lsp": { ".rb": "ruby-lsp", ".java": "jdtls" }
|
|
12
|
+
//
|
|
13
|
+
// The lsp tool gives the model definition, references, hover (types and
|
|
14
|
+
// docs), symbols and diagnostics. After an edit, a running server's errors
|
|
15
|
+
// for that file are added to the edit's result.
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
19
|
+
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
20
|
+
import { readConfigFile } from './config.js';
|
|
21
|
+
|
|
22
|
+
const SERVERS = [
|
|
23
|
+
{ key: 'ts', exts: ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.mts', '.cts'], cmds: [['typescript-language-server', '--stdio']] },
|
|
24
|
+
{ key: 'py', exts: ['.py', '.pyi'], cmds: [['pyright-langserver', '--stdio'], ['basedpyright-langserver', '--stdio'], ['pylsp']] },
|
|
25
|
+
{ key: 'go', exts: ['.go'], cmds: [['gopls']] },
|
|
26
|
+
{ key: 'rs', exts: ['.rs'], cmds: [['rust-analyzer']] },
|
|
27
|
+
{ key: 'c', exts: ['.c', '.h', '.cc', '.cpp', '.cxx', '.hpp', '.hh', '.m', '.mm'], cmds: [['clangd', '--background-index=false', '--log=error']] },
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const LANG_IDS = { '.ts': 'typescript', '.tsx': 'typescriptreact', '.js': 'javascript', '.jsx': 'javascriptreact', '.mjs': 'javascript', '.cjs': 'javascript', '.mts': 'typescript', '.cts': 'typescript', '.py': 'python', '.pyi': 'python', '.go': 'go', '.rs': 'rust', '.c': 'c', '.h': 'c', '.cc': 'cpp', '.cpp': 'cpp', '.cxx': 'cpp', '.hpp': 'cpp', '.hh': 'cpp', '.m': 'objective-c', '.mm': 'objective-cpp' };
|
|
31
|
+
const SYMBOL_KINDS = ['', 'file', 'module', 'namespace', 'package', 'class', 'method', 'property', 'field', 'constructor', 'enum', 'interface', 'function', 'variable', 'constant', 'string', 'number', 'boolean', 'array', 'object', 'key', 'null', 'enum member', 'struct', 'event', 'operator', 'type parameter'];
|
|
32
|
+
const SEVERITY = ['', 'error', 'warning', 'info', 'hint'];
|
|
33
|
+
|
|
34
|
+
const which = (cmd, root) => {
|
|
35
|
+
const local = path.join(root, 'node_modules', '.bin', cmd);
|
|
36
|
+
if (fs.existsSync(local)) return local;
|
|
37
|
+
return spawnSync('which', [cmd], { encoding: 'utf8' }).stdout.trim() || null;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
// The server command for a file, or null when none is installed.
|
|
41
|
+
export function serverFor(file, root) {
|
|
42
|
+
const ext = path.extname(file).toLowerCase();
|
|
43
|
+
const custom = readConfigFile().lsp?.[ext];
|
|
44
|
+
if (custom) {
|
|
45
|
+
const [cmd, ...args] = String(custom).split(/\s+/);
|
|
46
|
+
const exe = which(cmd, root);
|
|
47
|
+
return exe ? { key: `custom${ext}`, cmd: exe, args } : null;
|
|
48
|
+
}
|
|
49
|
+
const s = SERVERS.find((x) => x.exts.includes(ext));
|
|
50
|
+
if (!s) return null;
|
|
51
|
+
for (const [cmd, ...args] of s.cmds) {
|
|
52
|
+
const exe = which(cmd, root);
|
|
53
|
+
if (exe) return { key: s.key, cmd: exe, args, name: cmd };
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export const installHint = (file) => {
|
|
59
|
+
const ext = path.extname(file).toLowerCase();
|
|
60
|
+
return {
|
|
61
|
+
ts: 'npm install -g typescript typescript-language-server',
|
|
62
|
+
py: 'npm install -g pyright',
|
|
63
|
+
go: 'go install golang.org/x/tools/gopls@latest',
|
|
64
|
+
rs: 'rustup component add rust-analyzer',
|
|
65
|
+
c: 'install clangd (macOS: xcode-select --install; Linux: apt install clangd)',
|
|
66
|
+
}[SERVERS.find((x) => x.exts.includes(ext))?.key] ?? null;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
class LspClient {
|
|
70
|
+
constructor({ cmd, args, root }) {
|
|
71
|
+
this.root = root;
|
|
72
|
+
this.proc = spawn(cmd, args, { cwd: root, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
73
|
+
this.buf = Buffer.alloc(0);
|
|
74
|
+
this.seq = 0;
|
|
75
|
+
this.pending = new Map();
|
|
76
|
+
this.docs = new Map(); // uri -> { version, mtime }
|
|
77
|
+
this.diags = new Map(); // uri -> diagnostics
|
|
78
|
+
this.waiters = new Map(); // uri -> [resolve]
|
|
79
|
+
this.dead = false;
|
|
80
|
+
this.proc.stdout.on('data', (d) => this.onData(d));
|
|
81
|
+
this.proc.on('exit', () => {
|
|
82
|
+
this.dead = true;
|
|
83
|
+
for (const { reject } of this.pending.values()) reject(new Error('The language server stopped.'));
|
|
84
|
+
this.pending.clear();
|
|
85
|
+
});
|
|
86
|
+
this.proc.on('error', () => (this.dead = true));
|
|
87
|
+
this.proc.stdin.on('error', () => {});
|
|
88
|
+
// A language server never keeps leto from exiting.
|
|
89
|
+
this.proc.unref();
|
|
90
|
+
this.proc.stdout.unref?.();
|
|
91
|
+
this.proc.stdin.unref?.();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
send(msg) {
|
|
95
|
+
if (this.dead) return;
|
|
96
|
+
const body = Buffer.from(JSON.stringify({ jsonrpc: '2.0', ...msg }));
|
|
97
|
+
this.proc.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`), body]));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
onData(d) {
|
|
101
|
+
this.buf = Buffer.concat([this.buf, d]);
|
|
102
|
+
while (true) {
|
|
103
|
+
const sep = this.buf.indexOf('\r\n\r\n');
|
|
104
|
+
if (sep < 0) return;
|
|
105
|
+
const len = Number(this.buf.subarray(0, sep).toString().match(/Content-Length:\s*(\d+)/i)?.[1]);
|
|
106
|
+
if (!len && len !== 0) {
|
|
107
|
+
this.buf = this.buf.subarray(sep + 4);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (this.buf.length < sep + 4 + len) return;
|
|
111
|
+
const raw = this.buf.subarray(sep + 4, sep + 4 + len).toString();
|
|
112
|
+
this.buf = this.buf.subarray(sep + 4 + len);
|
|
113
|
+
let msg;
|
|
114
|
+
try {
|
|
115
|
+
msg = JSON.parse(raw);
|
|
116
|
+
} catch {
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
this.onMessage(msg);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
onMessage(msg) {
|
|
124
|
+
if (msg.id !== undefined && (msg.result !== undefined || msg.error) && !msg.method) {
|
|
125
|
+
const p = this.pending.get(msg.id);
|
|
126
|
+
if (!p) return;
|
|
127
|
+
this.pending.delete(msg.id);
|
|
128
|
+
clearTimeout(p.timer);
|
|
129
|
+
if (msg.error) p.reject(new Error(msg.error.message));
|
|
130
|
+
else p.resolve(msg.result);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (msg.method === 'textDocument/publishDiagnostics') {
|
|
134
|
+
this.diags.set(msg.params.uri, msg.params.diagnostics ?? []);
|
|
135
|
+
for (const r of this.waiters.get(msg.params.uri) ?? []) r();
|
|
136
|
+
this.waiters.delete(msg.params.uri);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
// Requests from the server: answer the common ones so it doesn't wait.
|
|
140
|
+
if (msg.id !== undefined && msg.method) {
|
|
141
|
+
const result = msg.method === 'workspace/configuration' ? (msg.params?.items ?? []).map(() => null) : null;
|
|
142
|
+
this.send({ id: msg.id, result });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
request(method, params, timeoutMs = 20000) {
|
|
147
|
+
if (this.dead) return Promise.reject(new Error('The language server is not running.'));
|
|
148
|
+
const id = ++this.seq;
|
|
149
|
+
return new Promise((resolve, reject) => {
|
|
150
|
+
const timer = setTimeout(() => {
|
|
151
|
+
this.pending.delete(id);
|
|
152
|
+
reject(new Error(`The language server didn't answer ${method} within ${timeoutMs / 1000}s (it may still be indexing).`));
|
|
153
|
+
}, timeoutMs);
|
|
154
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
155
|
+
this.send({ id, method, params });
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
notify(method, params) {
|
|
160
|
+
this.send({ method, params });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async init() {
|
|
164
|
+
const rootUri = pathToFileURL(this.root).href;
|
|
165
|
+
this.caps = await this.request('initialize', {
|
|
166
|
+
processId: process.pid,
|
|
167
|
+
rootUri,
|
|
168
|
+
rootPath: this.root,
|
|
169
|
+
workspaceFolders: [{ uri: rootUri, name: path.basename(this.root) }],
|
|
170
|
+
capabilities: {
|
|
171
|
+
textDocument: {
|
|
172
|
+
synchronization: { didSave: true },
|
|
173
|
+
publishDiagnostics: { relatedInformation: false },
|
|
174
|
+
definition: {},
|
|
175
|
+
typeDefinition: {},
|
|
176
|
+
implementation: {},
|
|
177
|
+
references: {},
|
|
178
|
+
hover: { contentFormat: ['plaintext', 'markdown'] },
|
|
179
|
+
documentSymbol: { hierarchicalDocumentSymbolSupport: true },
|
|
180
|
+
},
|
|
181
|
+
workspace: { symbol: {}, workspaceFolders: true, configuration: true },
|
|
182
|
+
},
|
|
183
|
+
}, 60000);
|
|
184
|
+
this.notify('initialized', {});
|
|
185
|
+
return this;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Tell the server about the file as it is on disk now.
|
|
189
|
+
sync(file) {
|
|
190
|
+
const uri = pathToFileURL(file).href;
|
|
191
|
+
const st = fs.statSync(file);
|
|
192
|
+
const doc = this.docs.get(uri);
|
|
193
|
+
if (doc && doc.mtime === st.mtimeMs) return uri;
|
|
194
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
195
|
+
this.diags.delete(uri);
|
|
196
|
+
if (!doc) {
|
|
197
|
+
this.notify('textDocument/didOpen', { textDocument: { uri, languageId: LANG_IDS[path.extname(file).toLowerCase()] ?? 'plaintext', version: 1, text } });
|
|
198
|
+
this.docs.set(uri, { version: 1, mtime: st.mtimeMs });
|
|
199
|
+
} else {
|
|
200
|
+
doc.version++;
|
|
201
|
+
doc.mtime = st.mtimeMs;
|
|
202
|
+
this.notify('textDocument/didChange', { textDocument: { uri, version: doc.version }, contentChanges: [{ text }] });
|
|
203
|
+
this.notify('textDocument/didSave', { textDocument: { uri } });
|
|
204
|
+
}
|
|
205
|
+
return uri;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
waitForDiagnostics(uri, ms) {
|
|
209
|
+
if (this.diags.has(uri)) return Promise.resolve();
|
|
210
|
+
return new Promise((resolve) => {
|
|
211
|
+
const t = setTimeout(resolve, ms);
|
|
212
|
+
const list = this.waiters.get(uri) ?? [];
|
|
213
|
+
list.push(() => {
|
|
214
|
+
clearTimeout(t);
|
|
215
|
+
resolve();
|
|
216
|
+
});
|
|
217
|
+
this.waiters.set(uri, list);
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
stop() {
|
|
222
|
+
if (this.dead) return;
|
|
223
|
+
try {
|
|
224
|
+
this.proc.kill();
|
|
225
|
+
} catch {}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const clients = new Map(); // `${key}|${root}` -> Promise<LspClient>
|
|
230
|
+
process.on('exit', () => {
|
|
231
|
+
for (const c of clients.values()) c.then((x) => x.stop(), () => {});
|
|
232
|
+
});
|
|
233
|
+
|
|
234
|
+
export async function clientFor(file, root, { start = true } = {}) {
|
|
235
|
+
const server = serverFor(file, root);
|
|
236
|
+
if (!server) return null;
|
|
237
|
+
const id = `${server.key}|${root}`;
|
|
238
|
+
if (!clients.has(id)) {
|
|
239
|
+
if (!start) return null;
|
|
240
|
+
clients.set(id, new LspClient({ ...server, root }).init().catch((err) => {
|
|
241
|
+
clients.delete(id);
|
|
242
|
+
throw err;
|
|
243
|
+
}));
|
|
244
|
+
}
|
|
245
|
+
return clients.get(id);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export const runningServers = () => [...clients.keys()];
|
|
249
|
+
|
|
250
|
+
const relTo = (root, file) => {
|
|
251
|
+
const r = path.relative(root, file);
|
|
252
|
+
return r && !r.startsWith('..') ? r : file;
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
function lineText(file, line) {
|
|
256
|
+
try {
|
|
257
|
+
return fs.readFileSync(file, 'utf8').split('\n')[line]?.trim().slice(0, 160) ?? '';
|
|
258
|
+
} catch {
|
|
259
|
+
return '';
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function formatLocations(result, root) {
|
|
264
|
+
const list = (Array.isArray(result) ? result : result ? [result] : []).map((l) => ({ uri: l.uri ?? l.targetUri, range: l.range ?? l.targetSelectionRange ?? l.targetRange }));
|
|
265
|
+
if (!list.length) return null;
|
|
266
|
+
const seen = new Set();
|
|
267
|
+
const uniq = list.filter((l) => {
|
|
268
|
+
const k = `${real(fileURLToPath(l.uri))}:${l.range.start.line}:${l.range.start.character}`;
|
|
269
|
+
return !seen.has(k) && seen.add(k);
|
|
270
|
+
});
|
|
271
|
+
return uniq.slice(0, 100).map((l) => {
|
|
272
|
+
const file = real(fileURLToPath(l.uri));
|
|
273
|
+
const line = l.range.start.line;
|
|
274
|
+
return `${relTo(root, file)}:${line + 1}:${l.range.start.character + 1}: ${lineText(file, line)}`;
|
|
275
|
+
}).join('\n') + (uniq.length > 100 ? `\n… ${uniq.length - 100} more` : '');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export function formatDiagnostics(diags, file, root, { min = 4 } = {}) {
|
|
279
|
+
return (diags ?? [])
|
|
280
|
+
.filter((d) => (d.severity ?? 1) <= min)
|
|
281
|
+
.slice(0, 50)
|
|
282
|
+
.map((d) => `${relTo(root, file)}:${d.range.start.line + 1}:${d.range.start.character + 1}: ${SEVERITY[d.severity ?? 1]}: ${String(d.message).split('\n')[0]}${d.source ? ` (${d.source})` : ''}`)
|
|
283
|
+
.join('\n');
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function flattenSymbols(list, depth = 0, out = []) {
|
|
287
|
+
for (const s of list ?? []) {
|
|
288
|
+
const range = s.selectionRange ?? s.range ?? s.location?.range;
|
|
289
|
+
out.push(`${' '.repeat(depth)}${s.name} (${SYMBOL_KINDS[s.kind] ?? 'symbol'}) ${range ? `line ${range.start.line + 1}` : ''}${s.location?.uri && depth === 0 && !s.selectionRange ? ` ${fileURLToPath(s.location.uri)}` : ''}`);
|
|
290
|
+
if (s.children) flattenSymbols(s.children, depth + 1, out);
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Where on the line is the symbol? (1-based column, or the first non-space.)
|
|
296
|
+
function columnFor(file, line, symbol, column) {
|
|
297
|
+
if (column) return column - 1;
|
|
298
|
+
const text = fs.readFileSync(file, 'utf8').split('\n')[line] ?? '';
|
|
299
|
+
if (symbol) {
|
|
300
|
+
const m = new RegExp(`\\b${symbol.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).exec(text);
|
|
301
|
+
if (m) return m.index;
|
|
302
|
+
throw new Error(`"${symbol}" is not on line ${line + 1} of ${path.basename(file)}: ${text.trim().slice(0, 120)}`);
|
|
303
|
+
}
|
|
304
|
+
return text.length - text.trimStart().length;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const real = (p) => {
|
|
308
|
+
try {
|
|
309
|
+
return fs.realpathSync(p);
|
|
310
|
+
} catch {
|
|
311
|
+
return p;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
export async function lspQuery({ action, file, line, column, symbol, query }, root) {
|
|
316
|
+
file = real(file);
|
|
317
|
+
root = real(root);
|
|
318
|
+
const client = await clientFor(file, root);
|
|
319
|
+
if (!client) {
|
|
320
|
+
const hint = installHint(file);
|
|
321
|
+
throw new Error(`No language server for ${path.extname(file) || 'this file'} is installed.${hint ? ` Install one: ${hint}` : ''} Use grep and repo_map instead.`);
|
|
322
|
+
}
|
|
323
|
+
const uri = client.sync(file);
|
|
324
|
+
const pos = () => {
|
|
325
|
+
if (!line) throw new Error(`${action} needs line (1-based), and symbol or column.`);
|
|
326
|
+
return { textDocument: { uri }, position: { line: line - 1, character: columnFor(file, line - 1, symbol, column) } };
|
|
327
|
+
};
|
|
328
|
+
switch (action) {
|
|
329
|
+
case 'definition':
|
|
330
|
+
case 'type_definition':
|
|
331
|
+
case 'implementation': {
|
|
332
|
+
const method = { definition: 'textDocument/definition', type_definition: 'textDocument/typeDefinition', implementation: 'textDocument/implementation' }[action];
|
|
333
|
+
return formatLocations(await client.request(method, pos()), root) ?? 'No definition found.';
|
|
334
|
+
}
|
|
335
|
+
case 'references':
|
|
336
|
+
return formatLocations(await client.request('textDocument/references', { ...pos(), context: { includeDeclaration: true } }), root) ?? 'No references found.';
|
|
337
|
+
case 'hover': {
|
|
338
|
+
const h = await client.request('textDocument/hover', pos());
|
|
339
|
+
const c = h?.contents;
|
|
340
|
+
const text = typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => x.value ?? x).join('\n') : c?.value ?? '';
|
|
341
|
+
return text.trim().slice(0, 4000) || 'Nothing to show here.';
|
|
342
|
+
}
|
|
343
|
+
case 'symbols': {
|
|
344
|
+
if (query) {
|
|
345
|
+
const res = await client.request('workspace/symbol', { query });
|
|
346
|
+
return (res ?? []).slice(0, 80).map((s) => `${s.name} (${SYMBOL_KINDS[s.kind] ?? 'symbol'}) ${relTo(root, fileURLToPath(s.location.uri))}:${s.location.range ? s.location.range.start.line + 1 : ''}`).join('\n') || `No symbols match "${query}".`;
|
|
347
|
+
}
|
|
348
|
+
return flattenSymbols(await client.request('textDocument/documentSymbol', { textDocument: { uri } })).slice(0, 300).join('\n') || 'No symbols in this file.';
|
|
349
|
+
}
|
|
350
|
+
case 'diagnostics': {
|
|
351
|
+
await client.waitForDiagnostics(uri, 8000);
|
|
352
|
+
return formatDiagnostics(client.diags.get(uri), file, root) || 'No problems reported.';
|
|
353
|
+
}
|
|
354
|
+
default:
|
|
355
|
+
throw new Error(`Unknown action "${action}". Actions: definition, references, hover, symbols, diagnostics, type_definition, implementation.`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// After an edit: errors from a server that is already running for this file.
|
|
360
|
+
export async function diagnosticsAfterEdit(file, root, waitMs = 2500) {
|
|
361
|
+
file = real(file);
|
|
362
|
+
root = real(root);
|
|
363
|
+
let client;
|
|
364
|
+
try {
|
|
365
|
+
client = await clientFor(file, root, { start: false });
|
|
366
|
+
} catch {
|
|
367
|
+
return null;
|
|
368
|
+
}
|
|
369
|
+
if (!client || client.dead) return null;
|
|
370
|
+
const uri = client.sync(file);
|
|
371
|
+
await client.waitForDiagnostics(uri, waitMs);
|
|
372
|
+
const errors = formatDiagnostics(client.diags.get(uri), file, root, { min: 1 });
|
|
373
|
+
return errors || null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export const lspTool = {
|
|
377
|
+
name: 'lsp',
|
|
378
|
+
label: 'LSP',
|
|
379
|
+
description:
|
|
380
|
+
'Ask the language server (the same engine editors use) about code: definition (where a symbol is defined), references (every place it is used), hover (its type and docs), symbols (outline of a file, or search the workspace with query), diagnostics (compiler/type errors for a file), type_definition, implementation. More precise than grep for code navigation and renames. Give path and line (1-based) plus the symbol name on that line (or column). Works for TypeScript/JavaScript, Python, Go, Rust and C/C++ when their language server is installed.',
|
|
381
|
+
parameters: {
|
|
382
|
+
type: 'object',
|
|
383
|
+
properties: {
|
|
384
|
+
action: { type: 'string', enum: ['definition', 'references', 'hover', 'symbols', 'diagnostics', 'type_definition', 'implementation'] },
|
|
385
|
+
path: { type: 'string', description: 'File path' },
|
|
386
|
+
line: { type: 'integer', description: '1-based line number (for definition, references, hover, type_definition, implementation)' },
|
|
387
|
+
symbol: { type: 'string', description: 'The name on that line to ask about' },
|
|
388
|
+
column: { type: 'integer', description: '1-based column, instead of symbol' },
|
|
389
|
+
query: { type: 'string', description: 'symbols: search the whole workspace for this name' },
|
|
390
|
+
},
|
|
391
|
+
required: ['action', 'path'],
|
|
392
|
+
},
|
|
393
|
+
summary: (a) => `${a.action} ${a.path}${a.line ? `:${a.line}` : ''}${a.symbol ? ` ${a.symbol}` : ''}${a.query ? ` "${a.query}"` : ''}`,
|
|
394
|
+
async run(a, ctx) {
|
|
395
|
+
const file = path.resolve(ctx.cwd, a.path);
|
|
396
|
+
if (!fs.existsSync(file)) throw new Error(`${a.path} does not exist.`);
|
|
397
|
+
const text = await lspQuery({ action: a.action, file, line: a.line, column: a.column, symbol: a.symbol, query: a.query }, ctx.cwd);
|
|
398
|
+
const n = text.split('\n').length;
|
|
399
|
+
return { content: text, display: /^No /.test(text) ? text : `${n} line${n === 1 ? '' : 's'}` };
|
|
400
|
+
},
|
|
401
|
+
};
|
package/src/markdown.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Streaming Markdown renderer for the terminal, in the Spice style. Text
|
|
2
|
+
// arrives in chunks; each complete line is rendered as soon as its newline
|
|
3
|
+
// arrives. Tables are held until they end so their columns can be aligned.
|
|
4
|
+
|
|
5
|
+
const ANSI = /\x1b\[[0-9;]*m/g;
|
|
6
|
+
export const visibleLength = (s) => s.replace(ANSI, '').length;
|
|
7
|
+
|
|
8
|
+
const KEYWORDS = new Set(
|
|
9
|
+
('abstract and as async await break case catch class const continue def default defer del delete do elif else enum export extends ' +
|
|
10
|
+
'false final finally fn for from func function go if impl import in interface is lambda let loop match mod module mut new nil none ' +
|
|
11
|
+
'not null or package pass private protected pub public raise return self static struct super switch this throw throws true try type ' +
|
|
12
|
+
'typeof undefined use var void where while with yield None True False').split(' '),
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
export function highlight(line, c) {
|
|
16
|
+
const token = /(\/\/.*$|#(?![!{\[]).*$|--\s.*$)|("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)|(\b\d+(?:\.\d+)?\b)|([A-Za-z_][A-Za-z0-9_]*)(?=\s*\()|([A-Za-z_][A-Za-z0-9_]*)/g;
|
|
17
|
+
return line.replace(token, (m, comment, str, num, call, word) => {
|
|
18
|
+
if (comment) return c.faint(c.italic(comment));
|
|
19
|
+
if (str) return c.mint(str);
|
|
20
|
+
if (num) return c.amber(num);
|
|
21
|
+
if (call) return KEYWORDS.has(call) ? c.orchid(call) : c.sky(call);
|
|
22
|
+
if (word && KEYWORDS.has(word)) return c.orchid(word);
|
|
23
|
+
return c.lilac(m);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function renderInline(s, c) {
|
|
28
|
+
// Split out `code` spans first so nothing inside them is touched.
|
|
29
|
+
return s
|
|
30
|
+
.split(/(`[^`]+`)/)
|
|
31
|
+
.map((part) => {
|
|
32
|
+
if (/^`[^`]+`$/.test(part)) return c.panelBg(c.sky(` ${part.slice(1, -1)} `));
|
|
33
|
+
return part
|
|
34
|
+
.replace(/\*\*([^*]+)\*\*|__([^_]+)__/g, (_, a, b) => c.bold(c.lilac(a ?? b)))
|
|
35
|
+
.replace(/(^|[\s(])\*([^*\s][^*]*)\*(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
|
|
36
|
+
.replace(/(^|[\s(])_([^_\s][^_]*)_(?=$|[\s).,:;!?])/g, (_, pre, a) => pre + c.italic(a))
|
|
37
|
+
.replace(/~~([^~]+)~~/g, (_, a) => c.strike(c.mist(a)))
|
|
38
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, text, url) => (text === url ? c.underline(c.sky(url)) : `${c.underline(c.sky(text))} ${c.faint(url)}`));
|
|
39
|
+
})
|
|
40
|
+
.join('');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class MarkdownStream {
|
|
44
|
+
constructor(c, { width = 100 } = {}) {
|
|
45
|
+
this.c = c;
|
|
46
|
+
this.width = width;
|
|
47
|
+
this.buf = '';
|
|
48
|
+
this.inCode = false;
|
|
49
|
+
this.fence = '';
|
|
50
|
+
this.lang = '';
|
|
51
|
+
this.table = [];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
push(chunk) {
|
|
55
|
+
this.buf += chunk;
|
|
56
|
+
let out = '';
|
|
57
|
+
let nl;
|
|
58
|
+
while ((nl = this.buf.indexOf('\n')) >= 0) {
|
|
59
|
+
out += this.line(this.buf.slice(0, nl));
|
|
60
|
+
this.buf = this.buf.slice(nl + 1);
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
flush() {
|
|
66
|
+
let out = '';
|
|
67
|
+
if (this.buf) {
|
|
68
|
+
out += this.line(this.buf);
|
|
69
|
+
this.buf = '';
|
|
70
|
+
}
|
|
71
|
+
out += this.flushTable();
|
|
72
|
+
if (this.inCode) {
|
|
73
|
+
out += this.panel('') + '\n';
|
|
74
|
+
this.inCode = false;
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// One row of a code panel: plum background across the panel width.
|
|
80
|
+
panel(content) {
|
|
81
|
+
const c = this.c;
|
|
82
|
+
const w = Math.max(20, Math.min(this.width - 2, 110));
|
|
83
|
+
const vis = visibleLength(content);
|
|
84
|
+
const body = vis > w - 2 ? content : content + ' '.repeat(w - 2 - vis);
|
|
85
|
+
return c.panelBg(` ${body} `);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
line(raw) {
|
|
89
|
+
const c = this.c;
|
|
90
|
+
const fence = raw.match(/^\s*(```+|~~~+)\s*([\w+#.-]*)/);
|
|
91
|
+
if (fence && (!this.inCode || raw.trim().startsWith(this.fence))) {
|
|
92
|
+
const out = this.flushTable();
|
|
93
|
+
if (!this.inCode) {
|
|
94
|
+
this.inCode = true;
|
|
95
|
+
this.fence = fence[1];
|
|
96
|
+
this.lang = fence[2] || '';
|
|
97
|
+
// Top edge of the panel carries the language as a small tag.
|
|
98
|
+
const tag = this.lang ? c.violet(this.lang) : c.faint('code');
|
|
99
|
+
return out + this.panel(tag) + '\n';
|
|
100
|
+
}
|
|
101
|
+
this.inCode = false;
|
|
102
|
+
return out + this.panel('') + '\n';
|
|
103
|
+
}
|
|
104
|
+
if (this.inCode) return this.panel(highlight(raw.replace(/\t/g, ' '), c)) + '\n';
|
|
105
|
+
|
|
106
|
+
if (/^\s*\|.*\|\s*$/.test(raw)) {
|
|
107
|
+
this.table.push(raw);
|
|
108
|
+
return '';
|
|
109
|
+
}
|
|
110
|
+
let out = this.flushTable();
|
|
111
|
+
|
|
112
|
+
let m;
|
|
113
|
+
if ((m = raw.match(/^(#{1,6})\s+(.*)$/))) {
|
|
114
|
+
const text = m[2].replace(/\s+#+\s*$/, '');
|
|
115
|
+
if (m[1].length === 1) return out + c.bold(c.gradient(text)) + '\n';
|
|
116
|
+
if (m[1].length === 2) return out + c.bold(c.violet(text)) + '\n';
|
|
117
|
+
return out + c.bold(c.lilac(renderInline(text, c))) + '\n';
|
|
118
|
+
}
|
|
119
|
+
if (/^\s*([-*_])(\s*\1){2,}\s*$/.test(raw)) return out + c.faint('─'.repeat(Math.min(this.width, 56))) + '\n';
|
|
120
|
+
if ((m = raw.match(/^\s*>\s?(.*)$/))) return out + `${c.iris('┃')} ${c.italic(c.lilac(renderInline(m[1], c)))}\n`;
|
|
121
|
+
if ((m = raw.match(/^(\s*)[-*+]\s+\[( |x|X)\]\s+(.*)$/))) {
|
|
122
|
+
const done = m[2].toLowerCase() === 'x';
|
|
123
|
+
return out + `${m[1]}${done ? c.mint('●') : c.mist('○')} ${done ? c.mist(c.strike(renderInline(m[3], c))) : renderInline(m[3], c)}\n`;
|
|
124
|
+
}
|
|
125
|
+
if ((m = raw.match(/^(\s*)[-*+]\s+(.*)$/))) {
|
|
126
|
+
const nested = m[1].length >= 2;
|
|
127
|
+
return out + `${m[1]}${nested ? c.iris('◦') : c.violet('•')} ${renderInline(m[2], c)}\n`;
|
|
128
|
+
}
|
|
129
|
+
if ((m = raw.match(/^(\s*)(\d+)[.)]\s+(.*)$/))) return out + `${m[1]}${c.violet(m[2] + '.')} ${renderInline(m[3], c)}\n`;
|
|
130
|
+
return out + renderInline(raw, c) + '\n';
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
flushTable() {
|
|
134
|
+
if (!this.table.length) return '';
|
|
135
|
+
const c = this.c;
|
|
136
|
+
const rows = this.table
|
|
137
|
+
.map((l) => l.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => renderInline(cell.trim(), c)))
|
|
138
|
+
.filter((cells) => !cells.every((cell) => /^:?-{2,}:?$/.test(cell.replace(ANSI, ''))));
|
|
139
|
+
this.table = [];
|
|
140
|
+
if (!rows.length) return '';
|
|
141
|
+
const cols = Math.max(...rows.map((r) => r.length));
|
|
142
|
+
const widths = Array.from({ length: cols }, (_, i) => Math.max(3, ...rows.map((r) => visibleLength(r[i] ?? ''))));
|
|
143
|
+
const pad = (s, w) => s + ' '.repeat(Math.max(0, w - visibleLength(s)));
|
|
144
|
+
const rule = (l, mid, r) => c.faint(l + widths.map((w) => '─'.repeat(w + 2)).join(mid) + r);
|
|
145
|
+
const lines = [rule('╭', '┬', '╮')];
|
|
146
|
+
rows.forEach((r, i) => {
|
|
147
|
+
lines.push(c.faint('│') + widths.map((w, j) => ` ${i === 0 ? c.bold(c.violet(pad(r[j] ?? '', w))) : pad(r[j] ?? '', w)} `).join(c.faint('│')) + c.faint('│'));
|
|
148
|
+
if (i === 0 && rows.length > 1) lines.push(rule('├', '┼', '┤'));
|
|
149
|
+
});
|
|
150
|
+
lines.push(rule('╰', '┴', '╯'));
|
|
151
|
+
return lines.join('\n') + '\n';
|
|
152
|
+
}
|
|
153
|
+
}
|