@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.
Files changed (56) hide show
  1. package/README.md +395 -2
  2. package/bin/leto.js +8 -0
  3. package/evals/core/suite.json +249 -0
  4. package/index.js +12 -0
  5. package/package.json +43 -4
  6. package/src/agent.js +572 -0
  7. package/src/agents.js +68 -0
  8. package/src/anthropic.js +204 -0
  9. package/src/browser.js +427 -0
  10. package/src/btw.js +56 -0
  11. package/src/checkpoints.js +90 -0
  12. package/src/ci.js +115 -0
  13. package/src/cli.js +1926 -0
  14. package/src/client.js +111 -0
  15. package/src/config.js +205 -0
  16. package/src/documents.js +198 -0
  17. package/src/eval.js +289 -0
  18. package/src/hooks.js +115 -0
  19. package/src/ide.js +231 -0
  20. package/src/input.js +148 -0
  21. package/src/jobs.js +97 -0
  22. package/src/legacy.js +41 -0
  23. package/src/lsp.js +401 -0
  24. package/src/markdown.js +153 -0
  25. package/src/mcp.js +346 -0
  26. package/src/memory.js +136 -0
  27. package/src/orchestrator.js +141 -0
  28. package/src/patching.js +185 -0
  29. package/src/permissions.js +75 -0
  30. package/src/plugins.js +118 -0
  31. package/src/policy.js +74 -0
  32. package/src/pricing.js +67 -0
  33. package/src/processes.js +139 -0
  34. package/src/prompt.js +134 -0
  35. package/src/prompts.js +189 -0
  36. package/src/providers.js +59 -0
  37. package/src/repomap.js +211 -0
  38. package/src/sandbox.js +90 -0
  39. package/src/sdk.js +220 -0
  40. package/src/selftool.js +238 -0
  41. package/src/serve.js +233 -0
  42. package/src/session.js +168 -0
  43. package/src/setup.js +157 -0
  44. package/src/skills.js +125 -0
  45. package/src/theme.js +185 -0
  46. package/src/toolcalls.js +257 -0
  47. package/src/tools.js +976 -0
  48. package/src/tui.js +1179 -0
  49. package/src/ui.js +454 -0
  50. package/src/update.js +33 -0
  51. package/src/usage.js +83 -0
  52. package/src/verify.js +131 -0
  53. package/src/version.js +3 -0
  54. package/src/worktree.js +87 -0
  55. package/vscode/extension.js +132 -0
  56. package/vscode/package.json +21 -0
package/src/eval.js ADDED
@@ -0,0 +1,289 @@
1
+ // `leto eval`: measure a model on real coding tasks inside this harness.
2
+ //
3
+ // A suite is a JSON file:
4
+ // {
5
+ // "name": "smoke",
6
+ // "defaults": { "timeout": 600 },
7
+ // "tasks": [
8
+ // { "id": "fix-add", "files": { "add.js": "…", "test.js": "…" },
9
+ // "prompt": "The test fails. Fix add.js.", "check": "node test.js" },
10
+ // { "id": "repo-task", "repo": "https://github.com/org/repo", "commit": "abc123",
11
+ // "setup": "npm ci", "prompt": "…", "check": "npm test -- auth" }
12
+ // ]
13
+ // }
14
+ // Each run gets a fresh copy of the task's files (inline "files", a local
15
+ // "repo" folder, or a git URL at "commit"), runs "setup", lets leto work
16
+ // with --yolo, then runs "check": exit code 0 is a pass. Results (pass rate,
17
+ // cost, tokens, tool calls, time) are printed and saved as JSON, and
18
+ // `leto eval compare a.json b.json` shows what changed between two runs.
19
+ import fs from 'node:fs';
20
+ import os from 'node:os';
21
+ import path from 'node:path';
22
+ import crypto from 'node:crypto';
23
+ import { spawn, spawnSync } from 'node:child_process';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { HOME_DIR } from './config.js';
26
+
27
+ const BIN = fileURLToPath(new URL('../bin/leto.js', import.meta.url));
28
+ export const EVALS_DIR = path.join(HOME_DIR, 'evals');
29
+
30
+ function sh(command, { cwd, timeoutMs = 600000, env } = {}) {
31
+ return new Promise((resolve) => {
32
+ const child = spawn(command, { cwd, shell: fs.existsSync('/bin/bash') ? '/bin/bash' : true, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, ...env } });
33
+ let out = '';
34
+ const add = (d) => {
35
+ if (out.length < 2_000_000) out += d;
36
+ };
37
+ child.stdout.on('data', add);
38
+ child.stderr.on('data', add);
39
+ let timedOut = false;
40
+ const timer = setTimeout(() => {
41
+ timedOut = true;
42
+ try {
43
+ process.kill(-child.pid, 'SIGKILL');
44
+ } catch {}
45
+ }, timeoutMs);
46
+ child.on('error', (err) => {
47
+ clearTimeout(timer);
48
+ resolve({ code: -1, out: err.message, timedOut });
49
+ });
50
+ child.on('close', (code) => {
51
+ clearTimeout(timer);
52
+ resolve({ code, out, timedOut });
53
+ });
54
+ });
55
+ }
56
+
57
+ // Suites that ship with leto: `leto eval core`.
58
+ const BUNDLED = { core: fileURLToPath(new URL('../evals/core/suite.json', import.meta.url)) };
59
+
60
+ export function loadSuite(file) {
61
+ let p = BUNDLED[file] && !fs.existsSync(file) ? BUNDLED[file] : path.resolve(file);
62
+ if (fs.existsSync(p) && fs.statSync(p).isDirectory()) p = path.join(p, 'suite.json');
63
+ const suite = JSON.parse(fs.readFileSync(p, 'utf8'));
64
+ if (!Array.isArray(suite.tasks) || !suite.tasks.length) throw new Error(`${p} has no tasks.`);
65
+ const ids = new Set();
66
+ suite.tasks.forEach((t, i) => {
67
+ t.id ??= `task-${i + 1}`;
68
+ if (ids.has(t.id)) throw new Error(`Duplicate task id "${t.id}".`);
69
+ ids.add(t.id);
70
+ if (!t.prompt) throw new Error(`Task ${t.id} has no prompt.`);
71
+ if (!t.check) throw new Error(`Task ${t.id} has no check command.`);
72
+ });
73
+ suite.name ??= path.basename(path.dirname(p)) === '.' ? 'suite' : path.basename(p, '.json');
74
+ suite.dir = path.dirname(p);
75
+ return suite;
76
+ }
77
+
78
+ // A cached clone per repository URL, so many runs don't re-download it.
79
+ function cachedClone(url) {
80
+ const dir = path.join(EVALS_DIR, 'repos', crypto.createHash('sha1').update(url).digest('hex').slice(0, 12));
81
+ if (!fs.existsSync(path.join(dir, '.git'))) {
82
+ fs.mkdirSync(path.dirname(dir), { recursive: true });
83
+ const r = spawnSync('git', ['clone', '--quiet', url, dir], { encoding: 'utf8' });
84
+ if (r.status !== 0) throw new Error(`git clone ${url} failed: ${r.stderr.trim()}`);
85
+ } else spawnSync('git', ['fetch', '--quiet', '--all'], { cwd: dir });
86
+ return dir;
87
+ }
88
+
89
+ function materialize(task, suite, work) {
90
+ if (task.files) {
91
+ for (const [rel, content] of Object.entries(task.files)) {
92
+ const f = path.join(work, rel);
93
+ fs.mkdirSync(path.dirname(f), { recursive: true });
94
+ fs.writeFileSync(f, content);
95
+ }
96
+ }
97
+ if (task.repo) {
98
+ if (/^(https?:|git@|ssh:)/.test(task.repo)) {
99
+ const cache = cachedClone(task.repo);
100
+ const r = spawnSync('git', ['clone', '--quiet', '--shared', cache, work], { encoding: 'utf8' });
101
+ if (r.status !== 0) throw new Error(`clone failed: ${r.stderr.trim()}`);
102
+ if (task.commit) {
103
+ const c = spawnSync('git', ['checkout', '--quiet', task.commit], { cwd: work, encoding: 'utf8' });
104
+ if (c.status !== 0) throw new Error(`checkout ${task.commit} failed: ${c.stderr.trim()}`);
105
+ }
106
+ } else {
107
+ const src = path.resolve(suite.dir, task.repo);
108
+ fs.cpSync(src, work, { recursive: true, filter: (s) => !/[\\/]node_modules([\\/]|$)/.test(s) });
109
+ }
110
+ }
111
+ // A git baseline lets the result record the agent's diff.
112
+ if (!fs.existsSync(path.join(work, '.git'))) {
113
+ spawnSync('git', ['init', '--quiet'], { cwd: work });
114
+ spawnSync('git', ['add', '-A'], { cwd: work });
115
+ spawnSync('git', ['-c', 'user.name=eval', '-c', 'user.email=eval@localhost', 'commit', '--quiet', '-m', 'baseline', '--allow-empty'], { cwd: work });
116
+ }
117
+ }
118
+
119
+ async function runOne(task, suite, opts, n) {
120
+ const d = { ...(suite.defaults ?? {}), ...task };
121
+ const work = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), `leto-eval-${task.id}-`)));
122
+ const result = { id: task.id, run: n, pass: false, agent_ok: false, cost_usd: null, tool_calls: 0, input_tokens: 0, output_tokens: 0, duration_s: 0, error: null };
123
+ const started = Date.now();
124
+ try {
125
+ materialize(task, suite, work);
126
+ if (d.setup) {
127
+ const s = await sh(d.setup, { cwd: work, timeoutMs: (d.setup_timeout ?? 900) * 1000 });
128
+ if (s.code !== 0) throw new Error(`setup failed (exit ${s.code}): ${s.out.trim().slice(-500)}`);
129
+ }
130
+ const args = [BIN, '-p', '--json', '--yolo'];
131
+ if (opts.orchestrate) args.push('--orchestrate');
132
+ else if (opts.model) args.push('--model', opts.model);
133
+ if (opts.maxCost || d.max_cost) args.push('--max-cost', String(opts.maxCost || d.max_cost));
134
+ if (opts.check && d.check) args.push('--check', d.check);
135
+ if (opts.sandbox) args.push('--sandbox');
136
+ args.push(d.prompt);
137
+ // Without -m or --orchestrate, a saved orchestrator team would take over; name the model.
138
+ const env = { LETO_NO_UPDATE_CHECK: '1', NO_COLOR: '1', ...(!opts.orchestrate && !opts.model ? { LETO_ORCHESTRATE: '0' } : {}), ...(opts.provider ? { LETO_PROVIDER: opts.provider } : {}), ...(opts.toolMode ? { LETO_TOOL_MODE: opts.toolMode } : {}) };
139
+ const quoted = args.map((a) => `'${a.replace(/'/g, `'\\''`)}'`).join(' ');
140
+ const agentRun = await sh(`${JSON.stringify(process.execPath)} ${quoted}`, { cwd: work, timeoutMs: (d.timeout ?? 900) * 1000, env });
141
+ const line = agentRun.out.trim().split('\n').reverse().find((l) => l.startsWith('{"ok"'));
142
+ if (line) {
143
+ const j = JSON.parse(line);
144
+ Object.assign(result, { agent_ok: j.ok, cost_usd: j.cost_usd, tool_calls: j.tool_calls ?? 0, input_tokens: (j.usage?.input_tokens ?? 0) + (j.usage?.cache_read_tokens ?? 0) + (j.usage?.cache_write_tokens ?? 0), output_tokens: j.usage?.output_tokens ?? 0, error: j.error, session_id: j.session_id });
145
+ } else result.error = agentRun.timedOut ? `agent timed out after ${d.timeout ?? 900}s` : `agent exited ${agentRun.code}: ${agentRun.out.trim().slice(-300)}`;
146
+ const check = await sh(d.check, { cwd: work, timeoutMs: (d.check_timeout ?? 600) * 1000 });
147
+ result.pass = check.code === 0;
148
+ result.check_output = check.out.trim().slice(-1500);
149
+ result.diff_stat = spawnSync('git', ['diff', '--stat', 'HEAD'], { cwd: work, encoding: 'utf8' }).stdout.trim().split('\n').pop() ?? '';
150
+ } catch (err) {
151
+ result.error = err.message;
152
+ } finally {
153
+ result.duration_s = Math.round((Date.now() - started) / 100) / 10;
154
+ if (opts.keep) result.workdir = work;
155
+ else fs.rmSync(work, { recursive: true, force: true });
156
+ }
157
+ return result;
158
+ }
159
+
160
+ async function pool(items, n, fn) {
161
+ const out = new Array(items.length);
162
+ let next = 0;
163
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
164
+ while (next < items.length) {
165
+ const i = next++;
166
+ out[i] = await fn(items[i], i);
167
+ }
168
+ }));
169
+ return out;
170
+ }
171
+
172
+ const pct = (x) => `${(x * 100).toFixed(x === 1 || x === 0 ? 0 : 1)}%`;
173
+ const median = (xs) => {
174
+ const s = [...xs].sort((a, b) => a - b);
175
+ return s.length ? s[Math.floor(s.length / 2)] : 0;
176
+ };
177
+
178
+ export async function runEval(file, opts = {}, log = (s) => process.stdout.write(s)) {
179
+ const suite = loadSuite(file);
180
+ let tasks = suite.tasks;
181
+ if (opts.filter) {
182
+ const re = new RegExp(opts.filter);
183
+ tasks = tasks.filter((t) => re.test(t.id));
184
+ }
185
+ if (!tasks.length) throw new Error('No tasks match.');
186
+ const repeat = Math.max(1, Number(opts.repeat) || 1);
187
+ const jobs = tasks.flatMap((t) => Array.from({ length: repeat }, (_, r) => ({ t, r: r + 1 })));
188
+ const concurrency = Math.max(1, Number(opts.concurrency) || 4);
189
+ log(`Running ${suite.name}: ${tasks.length} task${tasks.length === 1 ? '' : 's'}${repeat > 1 ? ` × ${repeat}` : ''}, ${concurrency} at a time${opts.model ? `, model ${opts.model}` : ''}\n\n`);
190
+ const started = Date.now();
191
+ const results = await pool(jobs, concurrency, async ({ t, r }) => {
192
+ const res = await runOne(t, suite, opts, r);
193
+ log(`${res.pass ? '✓' : '✗'} ${t.id}${repeat > 1 ? ` #${r}` : ''} ${res.duration_s}s · ${res.tool_calls} tools${res.cost_usd != null ? ` · $${res.cost_usd.toFixed(4)}` : ''}${res.error && !res.pass ? ` (${String(res.error).split('\n')[0].slice(0, 80)})` : ''}\n`);
194
+ return res;
195
+ });
196
+ const passed = results.filter((x) => x.pass).length;
197
+ const costs = results.map((x) => x.cost_usd).filter((x) => x != null);
198
+ const summary = {
199
+ suite: suite.name,
200
+ model: opts.model || null,
201
+ provider: opts.provider || null,
202
+ tool_mode: opts.toolMode || null,
203
+ orchestrate: Boolean(opts.orchestrate),
204
+ date: new Date().toISOString(),
205
+ tasks: tasks.length,
206
+ runs: results.length,
207
+ passed,
208
+ pass_rate: passed / results.length,
209
+ cost_usd: costs.length ? Number(costs.reduce((a, b) => a + b, 0).toFixed(4)) : null,
210
+ median_duration_s: median(results.map((x) => x.duration_s)),
211
+ median_tool_calls: median(results.map((x) => x.tool_calls)),
212
+ wall_s: Math.round((Date.now() - started) / 1000),
213
+ results,
214
+ };
215
+ log(`\n${passed}/${results.length} passed (${pct(summary.pass_rate)})${summary.cost_usd != null ? ` · $${summary.cost_usd.toFixed(2)} total` : ''} · median ${summary.median_duration_s}s and ${summary.median_tool_calls} tool calls per run · ${summary.wall_s}s wall\n`);
216
+ const out = opts.out || path.join(EVALS_DIR, `${suite.name}-${summary.date.replace(/[:.]/g, '-')}.json`);
217
+ fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
218
+ fs.writeFileSync(out, JSON.stringify(summary, null, 2) + '\n');
219
+ log(`Results: ${out}\n`);
220
+ return summary;
221
+ }
222
+
223
+ export function compareEvals(a, b, log = (s) => process.stdout.write(s)) {
224
+ const A = JSON.parse(fs.readFileSync(a, 'utf8'));
225
+ const B = JSON.parse(fs.readFileSync(b, 'utf8'));
226
+ const rate = (s, id) => {
227
+ const rs = s.results.filter((r) => r.id === id);
228
+ return rs.length ? rs.filter((r) => r.pass).length / rs.length : null;
229
+ };
230
+ const ids = [...new Set([...A.results, ...B.results].map((r) => r.id))];
231
+ log(`A: ${a} (${A.model ?? 'default model'}) ${pct(A.pass_rate)}\nB: ${b} (${B.model ?? 'default model'}) ${pct(B.pass_rate)}\n\n`);
232
+ let fixed = 0;
233
+ let broke = 0;
234
+ for (const id of ids) {
235
+ const x = rate(A, id);
236
+ const y = rate(B, id);
237
+ const mark = x == null || y == null ? '·' : y > x ? '↑' : y < x ? '↓' : ' ';
238
+ if (mark === '↑') fixed++;
239
+ if (mark === '↓') broke++;
240
+ log(`${mark} ${id.padEnd(30)} ${x == null ? '—' : pct(x)} → ${y == null ? '—' : pct(y)}\n`);
241
+ }
242
+ const cost = A.cost_usd != null && B.cost_usd != null ? ` · cost $${A.cost_usd.toFixed(2)} → $${B.cost_usd.toFixed(2)}` : '';
243
+ log(`\n${pct(A.pass_rate)} → ${pct(B.pass_rate)} · ${fixed} better, ${broke} worse${cost}\n`);
244
+ return { fixed, broke };
245
+ }
246
+
247
+ export function initSuite(dir) {
248
+ const file = path.join(dir, 'suite.json');
249
+ if (fs.existsSync(file)) throw new Error(`${file} already exists.`);
250
+ fs.mkdirSync(dir, { recursive: true });
251
+ const suite = {
252
+ name: path.basename(path.resolve(dir)),
253
+ defaults: { timeout: 600 },
254
+ tasks: [
255
+ {
256
+ id: 'js-off-by-one',
257
+ files: {
258
+ 'range.js': 'export function range(n) {\n const out = [];\n for (let i = 1; i < n; i++) out.push(i);\n return out;\n}\n',
259
+ 'test.js': "import { range } from './range.js';\nimport assert from 'node:assert';\nassert.deepStrictEqual(range(3), [0, 1, 2]);\nassert.deepStrictEqual(range(0), []);\nconsole.log('ok');\n",
260
+ 'package.json': '{ "type": "module" }\n',
261
+ },
262
+ prompt: 'node test.js fails. Find and fix the bug in range.js. Do not change test.js.',
263
+ check: 'node test.js && git diff --quiet HEAD -- test.js',
264
+ },
265
+ {
266
+ id: 'py-add-feature',
267
+ files: {
268
+ 'stats.py': 'def mean(xs):\n return sum(xs) / len(xs)\n',
269
+ 'test_stats.py': 'from stats import mean, median\n\nassert mean([1, 2, 3]) == 2\nassert median([3, 1, 2]) == 2\nassert median([4, 1, 3, 2]) == 2.5\nprint("ok")\n',
270
+ },
271
+ prompt: 'Add a median function to stats.py so that python3 test_stats.py passes.',
272
+ check: 'python3 test_stats.py',
273
+ },
274
+ {
275
+ id: 'js-refactor-rename',
276
+ files: {
277
+ 'src/user.js': "export function getUsrName(u) {\n return u.first + ' ' + u.last;\n}\n",
278
+ 'src/greet.js': "import { getUsrName } from './user.js';\nexport const greet = (u) => `Hello, ${getUsrName(u)}!`;\n",
279
+ 'test.js': "import { greet } from './src/greet.js';\nimport * as user from './src/user.js';\nimport assert from 'node:assert';\nassert.equal(greet({ first: 'Paul', last: 'A' }), 'Hello, Paul A!');\nassert.equal(typeof user.getUserName, 'function');\nassert.equal(user.getUsrName, undefined);\nconsole.log('ok');\n",
280
+ 'package.json': '{ "type": "module" }\n',
281
+ },
282
+ prompt: 'Rename getUsrName to getUserName everywhere in src/.',
283
+ check: 'node test.js',
284
+ },
285
+ ],
286
+ };
287
+ fs.writeFileSync(file, JSON.stringify(suite, null, 2) + '\n');
288
+ return file;
289
+ }
package/src/hooks.js ADDED
@@ -0,0 +1,115 @@
1
+ // Hooks: your own shell commands that run at points in the agent's work.
2
+ //
3
+ // In ~/.leto/config.json (yours) or <project>/.leto/settings.json
4
+ // (asks before first use):
5
+ // {
6
+ // "hooks": {
7
+ // "PreToolUse": [{ "matcher": "bash", "command": "./scripts/check-command.sh" }],
8
+ // "PostToolUse": [{ "matcher": "edit_file|write_file", "command": "npx prettier --write \"$LETO_FILE\"" }],
9
+ // "UserPromptSubmit": [{ "command": "echo \"Current branch: $(git branch --show-current)\"" }],
10
+ // "Stop": [{ "command": "say done" }]
11
+ // }
12
+ // }
13
+ //
14
+ // Each command gets a JSON description of the event on stdin, plus
15
+ // LETO_EVENT, LETO_TOOL and LETO_FILE in its environment.
16
+ // - PreToolUse: exit code 2 blocks the tool; stderr is shown to the model as the reason.
17
+ // - UserPromptSubmit: stdout is added to the message as context; exit 2 blocks the message.
18
+ // - Other non-zero exits are reported as warnings.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import { spawn } from 'node:child_process';
22
+ import { readConfigFile } from './config.js';
23
+ import { projectDir } from './legacy.js';
24
+
25
+ export const HOOK_EVENTS = ['PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'Stop'];
26
+
27
+ export function projectSettingsFile(cwd) {
28
+ return path.join(projectDir(cwd), 'settings.json');
29
+ }
30
+
31
+ export function loadHooks(cwd, { includeProject }) {
32
+ const hooks = Object.fromEntries(HOOK_EVENTS.map((e) => [e, []]));
33
+ const add = (source, defs) => {
34
+ for (const event of HOOK_EVENTS) for (const h of defs?.[event] ?? []) if (h?.command) hooks[event].push({ ...h, source });
35
+ };
36
+ add('user', readConfigFile().hooks);
37
+ if (includeProject) {
38
+ try {
39
+ add('project', JSON.parse(fs.readFileSync(projectSettingsFile(cwd), 'utf8')).hooks);
40
+ } catch {}
41
+ }
42
+ return hooks;
43
+ }
44
+
45
+ export function projectHasHooks(cwd) {
46
+ try {
47
+ const hooks = JSON.parse(fs.readFileSync(projectSettingsFile(cwd), 'utf8')).hooks ?? {};
48
+ return HOOK_EVENTS.some((e) => hooks[e]?.length);
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function matches(matcher, tool) {
55
+ if (!matcher || matcher === '*') return true;
56
+ try {
57
+ return new RegExp(`^(?:${matcher})$`).test(tool);
58
+ } catch {
59
+ return matcher === tool;
60
+ }
61
+ }
62
+
63
+ function runHook(command, payload, cwd, env) {
64
+ return new Promise((resolve) => {
65
+ const child = spawn(command, { cwd, shell: true, env: { ...process.env, ...env }, stdio: ['pipe', 'pipe', 'pipe'] });
66
+ let stdout = '';
67
+ let stderr = '';
68
+ child.stdout.on('data', (d) => (stdout += d));
69
+ child.stderr.on('data', (d) => (stderr += d));
70
+ const timer = setTimeout(() => child.kill('SIGKILL'), 60000);
71
+ child.on('error', (err) => {
72
+ clearTimeout(timer);
73
+ resolve({ code: -1, stdout, stderr: err.message });
74
+ });
75
+ child.on('close', (code) => {
76
+ clearTimeout(timer);
77
+ resolve({ code, stdout: stdout.trim(), stderr: stderr.trim() });
78
+ });
79
+ child.stdin.on('error', () => {});
80
+ child.stdin.end(JSON.stringify(payload));
81
+ });
82
+ }
83
+
84
+ export class Hooks {
85
+ constructor(hooks, { cwd, ui }) {
86
+ this.hooks = hooks;
87
+ this.cwd = cwd;
88
+ this.ui = ui;
89
+ }
90
+
91
+ get count() {
92
+ return HOOK_EVENTS.reduce((n, e) => n + this.hooks[e].length, 0);
93
+ }
94
+
95
+ // Returns { blocked: bool, reason, output }.
96
+ async run(event, { tool, input, result, prompt, sessionId } = {}) {
97
+ const list = (this.hooks[event] ?? []).filter((h) => event.endsWith('ToolUse') ? matches(h.matcher, tool) : true);
98
+ const outputs = [];
99
+ for (const h of list) {
100
+ const file = input?.path ? path.resolve(this.cwd, input.path) : '';
101
+ const { code, stdout, stderr } = await runHook(
102
+ h.command,
103
+ { event, tool, input, result, prompt, cwd: this.cwd, session_id: sessionId },
104
+ this.cwd,
105
+ { LETO_EVENT: event, LETO_TOOL: tool ?? '', LETO_FILE: file },
106
+ );
107
+ if (code === 2 && (event === 'PreToolUse' || event === 'UserPromptSubmit')) {
108
+ return { blocked: true, reason: stderr || stdout || `Blocked by ${event} hook: ${h.command}` };
109
+ }
110
+ if (code !== 0) this.ui.info(` hook "${h.command}" exited with ${code}${stderr ? `: ${stderr.split('\n')[0]}` : ''}`);
111
+ if (stdout) outputs.push(stdout);
112
+ }
113
+ return { blocked: false, output: outputs.join('\n') };
114
+ }
115
+ }
package/src/ide.js ADDED
@@ -0,0 +1,231 @@
1
+ // Editor integration (VS Code and forks such as Cursor and Windsurf).
2
+ //
3
+ // The leto extension writes what you're looking at (file, selection,
4
+ // errors) to ~/.leto/ide/vscode-<pid>.json. leto reads it before each
5
+ // message, and asks the editor to show its edits as diffs by dropping
6
+ // requests in ~/.leto/ide/requests/. No network, no ports.
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import crypto from 'node:crypto';
11
+ import zlib from 'node:zlib';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { HOME_DIR } from './config.js';
15
+
16
+ export const IDE_DIR = path.join(HOME_DIR, 'ide');
17
+ const REQ_DIR = path.join(IDE_DIR, 'requests');
18
+ const SNAP_DIR = path.join(IDE_DIR, 'snapshots');
19
+ const EXT_DIR = fileURLToPath(new URL('../vscode/', import.meta.url));
20
+
21
+ const alive = (pid) => {
22
+ try {
23
+ process.kill(pid, 0);
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ };
29
+
30
+ const inside = (child, parent) => {
31
+ const r = path.relative(parent, child);
32
+ return r === '' || (!r.startsWith('..') && !path.isAbsolute(r));
33
+ };
34
+
35
+ // The editor window that has this folder open, if any.
36
+ export function findEditor(cwd) {
37
+ let files = [];
38
+ try {
39
+ files = fs.readdirSync(IDE_DIR).filter((f) => /^vscode-\d+\.json$/.test(f));
40
+ } catch {
41
+ return null;
42
+ }
43
+ const real = fs.realpathSync(cwd);
44
+ const states = [];
45
+ for (const f of files) {
46
+ try {
47
+ const s = JSON.parse(fs.readFileSync(path.join(IDE_DIR, f), 'utf8'));
48
+ if (!alive(s.pid)) {
49
+ fs.rmSync(path.join(IDE_DIR, f), { force: true });
50
+ continue;
51
+ }
52
+ if ((s.folders ?? []).some((d) => inside(real, d) || inside(d, real) || inside(cwd, d))) states.push(s);
53
+ } catch {}
54
+ }
55
+ return states.sort((a, b) => b.updated - a.updated)[0] ?? null;
56
+ }
57
+
58
+ export class Ide {
59
+ constructor(cwd) {
60
+ this.cwd = cwd;
61
+ this.lastKey = '';
62
+ this.diffs = true;
63
+ }
64
+
65
+ get state() {
66
+ return findEditor(this.cwd);
67
+ }
68
+
69
+ get connected() {
70
+ return Boolean(this.state);
71
+ }
72
+
73
+ get name() {
74
+ return this.state?.app ?? 'VS Code';
75
+ }
76
+
77
+ // What the user is looking at, when it changed since the last message.
78
+ contextNote() {
79
+ const s = this.state;
80
+ if (!s?.file) return null;
81
+ const key = `${s.file}|${s.selection?.start}|${s.selection?.end}|${s.selection?.text?.length ?? 0}`;
82
+ if (key === this.lastKey) return null;
83
+ this.lastKey = key;
84
+ const rel = path.relative(this.cwd, s.file);
85
+ const shown = rel && !rel.startsWith('..') ? rel : s.file;
86
+ let note = `<ide-context editor="${s.app}">\nThe user has ${shown} open in their editor${s.cursor && !s.selection ? ` (cursor on line ${s.cursor})` : ''}${s.dirty ? ', with unsaved changes' : ''}.`;
87
+ if (s.selection) note += `\nThey selected lines ${s.selection.start}-${s.selection.end}:\n\`\`\`${s.language ?? ''}\n${s.selection.text}\n\`\`\``;
88
+ if (s.diagnostics?.length) note += `\nErrors the editor shows in this file:\n${s.diagnostics.map((d) => `- line ${d.line}: ${d.message}`).join('\n')}`;
89
+ note += '\nWhen they say "this", they likely mean that file or selection.\n</ide-context>';
90
+ return note;
91
+ }
92
+
93
+ // Show an edit as a diff in the editor.
94
+ showDiff(file, before, title = '') {
95
+ if (!this.diffs || !this.connected) return false;
96
+ fs.mkdirSync(REQ_DIR, { recursive: true });
97
+ fs.mkdirSync(SNAP_DIR, { recursive: true });
98
+ const id = crypto.randomBytes(4).toString('hex');
99
+ const snap = path.join(SNAP_DIR, `${id}-${path.basename(file)}`);
100
+ fs.writeFileSync(snap, before ?? '');
101
+ fs.writeFileSync(path.join(REQ_DIR, `${Date.now()}-${id}.json`), JSON.stringify({ type: 'diff', file: path.resolve(file), before: snap, title, t: Date.now() }));
102
+ cleanup();
103
+ return true;
104
+ }
105
+
106
+ open(file, line) {
107
+ if (!this.connected) return false;
108
+ fs.mkdirSync(REQ_DIR, { recursive: true });
109
+ fs.writeFileSync(path.join(REQ_DIR, `${Date.now()}-open.json`), JSON.stringify({ type: 'open', file: path.resolve(file), line, t: Date.now() }));
110
+ return true;
111
+ }
112
+ }
113
+
114
+ // Old snapshots and unclaimed requests.
115
+ function cleanup() {
116
+ const cutoff = Date.now() - 3600000;
117
+ for (const dir of [SNAP_DIR, REQ_DIR]) {
118
+ try {
119
+ for (const f of fs.readdirSync(dir)) {
120
+ const p = path.join(dir, f);
121
+ if (fs.statSync(p).mtimeMs < (dir === REQ_DIR ? Date.now() - 120000 : cutoff)) fs.rmSync(p, { force: true });
122
+ }
123
+ } catch {}
124
+ }
125
+ }
126
+
127
+ // --- building and installing the extension ---------------------------------------
128
+
129
+ function zip(entries) {
130
+ // A plain (stored, uncompressed) zip archive.
131
+ const files = [];
132
+ const central = [];
133
+ let offset = 0;
134
+ for (const { name, data } of entries) {
135
+ const nameBuf = Buffer.from(name);
136
+ const crc = zlib.crc32(data) >>> 0;
137
+ const local = Buffer.alloc(30);
138
+ local.writeUInt32LE(0x04034b50, 0);
139
+ local.writeUInt16LE(20, 4);
140
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
141
+ local.writeUInt16LE(0, 8);
142
+ local.writeUInt32LE(0, 10);
143
+ local.writeUInt32LE(crc, 14);
144
+ local.writeUInt32LE(data.length, 18);
145
+ local.writeUInt32LE(data.length, 22);
146
+ local.writeUInt16LE(nameBuf.length, 26);
147
+ local.writeUInt16LE(0, 28);
148
+ files.push(local, nameBuf, data);
149
+ const cen = Buffer.alloc(46);
150
+ cen.writeUInt32LE(0x02014b50, 0);
151
+ cen.writeUInt16LE(20, 4);
152
+ cen.writeUInt16LE(20, 6);
153
+ cen.writeUInt16LE(0x0800, 8);
154
+ cen.writeUInt16LE(0, 10);
155
+ cen.writeUInt32LE(0, 12);
156
+ cen.writeUInt32LE(crc, 16);
157
+ cen.writeUInt32LE(data.length, 20);
158
+ cen.writeUInt32LE(data.length, 24);
159
+ cen.writeUInt16LE(nameBuf.length, 28);
160
+ cen.writeUInt32LE(offset, 42);
161
+ central.push(cen, nameBuf);
162
+ offset += local.length + nameBuf.length + data.length;
163
+ }
164
+ const cenBuf = Buffer.concat(central);
165
+ const end = Buffer.alloc(22);
166
+ end.writeUInt32LE(0x06054b50, 0);
167
+ end.writeUInt16LE(entries.length, 8);
168
+ end.writeUInt16LE(entries.length, 10);
169
+ end.writeUInt32LE(cenBuf.length, 12);
170
+ end.writeUInt32LE(offset, 16);
171
+ return Buffer.concat([...files, cenBuf, end]);
172
+ }
173
+
174
+ export function buildVsix(out) {
175
+ const pkg = JSON.parse(fs.readFileSync(path.join(EXT_DIR, 'package.json'), 'utf8'));
176
+ const manifest = `<?xml version="1.0" encoding="utf-8"?>
177
+ <PackageManifest Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vsx-schema/2011" xmlns:d="http://schemas.microsoft.com/developer/vsx-schema-design/2011">
178
+ <Metadata>
179
+ <Identity Language="en-US" Id="${pkg.name}" Version="${pkg.version}" Publisher="${pkg.publisher}" />
180
+ <DisplayName>${pkg.displayName}</DisplayName>
181
+ <Description xml:space="preserve">${pkg.description}</Description>
182
+ <Categories>Other</Categories>
183
+ <Properties>
184
+ <Property Id="Microsoft.VisualStudio.Code.Engine" Value="${pkg.engines.vscode}" />
185
+ </Properties>
186
+ </Metadata>
187
+ <Installation><InstallationTarget Id="Microsoft.VisualStudio.Code" /></Installation>
188
+ <Dependencies />
189
+ <Assets>
190
+ <Asset Type="Microsoft.VisualStudio.Code.Manifest" Path="extension/package.json" Addressable="true" />
191
+ </Assets>
192
+ </PackageManifest>
193
+ `;
194
+ const types = '<?xml version="1.0" encoding="utf-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension=".json" ContentType="application/json"/><Default Extension=".js" ContentType="application/javascript"/><Default Extension=".vsixmanifest" ContentType="text/xml"/></Types>';
195
+ const data = zip([
196
+ { name: '[Content_Types].xml', data: Buffer.from(types) },
197
+ { name: 'extension.vsixmanifest', data: Buffer.from(manifest) },
198
+ { name: 'extension/package.json', data: fs.readFileSync(path.join(EXT_DIR, 'package.json')) },
199
+ { name: 'extension/extension.js', data: fs.readFileSync(path.join(EXT_DIR, 'extension.js')) },
200
+ ]);
201
+ fs.writeFileSync(out, data);
202
+ return { file: out, version: pkg.version };
203
+ }
204
+
205
+ // The editor command-line tools on this machine.
206
+ export function editorClis() {
207
+ const out = [];
208
+ const add = (name, p) => {
209
+ if (p && fs.existsSync(p) && !out.some((x) => x.path === p)) out.push({ name, path: p });
210
+ };
211
+ for (const [name, cmd] of [['VS Code', 'code'], ['Cursor', 'cursor'], ['Windsurf', 'windsurf'], ['VS Code Insiders', 'code-insiders']]) {
212
+ add(name, spawnSync('which', [cmd], { encoding: 'utf8' }).stdout.trim());
213
+ }
214
+ if (process.platform === 'darwin') {
215
+ add('VS Code', '/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code');
216
+ add('Cursor', '/Applications/Cursor.app/Contents/Resources/app/bin/cursor');
217
+ add('Windsurf', '/Applications/Windsurf.app/Contents/Resources/app/bin/windsurf');
218
+ }
219
+ return out;
220
+ }
221
+
222
+ export function installExtension(cli, { extensionsDir } = {}) {
223
+ const vsix = path.join(os.tmpdir(), `leto-vscode-${Date.now()}.vsix`);
224
+ buildVsix(vsix);
225
+ const args = ['--install-extension', vsix, '--force'];
226
+ if (extensionsDir) args.unshift('--extensions-dir', extensionsDir);
227
+ const r = spawnSync(cli.path, args, { encoding: 'utf8', timeout: 120000 });
228
+ fs.rmSync(vsix, { force: true });
229
+ if (r.status !== 0) throw new Error(`${cli.name} could not install the extension: ${(r.stderr || r.stdout || r.error?.message || '').trim().slice(0, 400)}`);
230
+ return (r.stdout || '').trim();
231
+ }