@mumbrane/leto 0.0.0-stage → 0.19.1

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/verify.js ADDED
@@ -0,0 +1,131 @@
1
+ // Self-checking: catch broken code while the model can still fix it.
2
+ //
3
+ // Two layers:
4
+ // 1. Syntax checks after every edit. They parse the edited file without
5
+ // running it (node --check, py_compile, JSON.parse), take milliseconds, and
6
+ // their errors go straight into that edit's tool result.
7
+ // 2. A project check command (typecheck, lint, tests) that runs when the model
8
+ // is about to finish a turn in which it changed files. If it fails, the
9
+ // errors go back to the model and the turn continues, up to a few rounds.
10
+ //
11
+ // The check command is chosen by you (/check, --check, or `leto config`)
12
+ // and stored in your own config, never read from the repository, because a
13
+ // cloned project could otherwise make leto run any command it likes.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { spawnSync, spawn } from 'node:child_process';
17
+
18
+ const has = (cmd) => spawnSync(process.platform === 'win32' ? 'where' : 'which', [cmd], { stdio: 'ignore' }).status === 0;
19
+ const cache = new Map();
20
+ const available = (cmd) => {
21
+ if (!cache.has(cmd)) cache.set(cmd, has(cmd));
22
+ return cache.get(cmd);
23
+ };
24
+
25
+ // Fast, side-effect-free syntax check of one file. Returns an error string or null.
26
+ export function syntaxCheck(file) {
27
+ const ext = path.extname(file).toLowerCase();
28
+ let text;
29
+ try {
30
+ if (fs.statSync(file).size > 2_000_000) return null;
31
+ text = fs.readFileSync(file, 'utf8');
32
+ } catch {
33
+ return null;
34
+ }
35
+ if (ext === '.json' && !/tsconfig|jsconfig|\.vscode/.test(file)) {
36
+ try {
37
+ JSON.parse(text);
38
+ return null;
39
+ } catch (err) {
40
+ return `JSON syntax error: ${err.message}`;
41
+ }
42
+ }
43
+ let r;
44
+ if (['.js', '.mjs', '.cjs'].includes(ext)) {
45
+ // JSX in a .js file isn't plain JavaScript; node --check would misreport it.
46
+ if (/<[A-Z][\w.]*[\s/>]|<\/[a-z]+>|return\s*\(\s*</.test(text)) return null;
47
+ r = spawnSync(process.execPath, ['--check', file], { encoding: 'utf8', timeout: 10000 });
48
+ } else if (ext === '.py' && available('python3')) {
49
+ r = spawnSync('python3', ['-c', 'import ast,sys; ast.parse(open(sys.argv[1]).read(), sys.argv[1])', file], { encoding: 'utf8', timeout: 10000 });
50
+ } else if (ext === '.sh' || ext === '.bash') {
51
+ r = spawnSync('bash', ['-n', file], { encoding: 'utf8', timeout: 10000 });
52
+ } else if (ext === '.rb' && available('ruby')) {
53
+ r = spawnSync('ruby', ['-c', file], { encoding: 'utf8', timeout: 10000 });
54
+ } else if (ext === '.php' && available('php')) {
55
+ r = spawnSync('php', ['-l', file], { encoding: 'utf8', timeout: 10000 });
56
+ } else return null;
57
+ if (!r || r.status === 0 || r.error) return null;
58
+ const shown = path.relative(process.cwd(), file) || path.basename(file);
59
+ const out = `${r.stderr || ''}${r.stdout || ''}`.split(file).join(shown).trim().split('\n').slice(0, 12).join('\n');
60
+ return out ? `Syntax error:\n${out}` : null;
61
+ }
62
+
63
+ // Check commands that fit this project, best first. Only suggestions: the user picks one.
64
+ export function detectChecks(cwd) {
65
+ const out = [];
66
+ const exists = (f) => fs.existsSync(path.join(cwd, f));
67
+ let pkg = null;
68
+ try {
69
+ pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
70
+ } catch {}
71
+ const runner = exists('pnpm-lock.yaml') ? 'pnpm' : exists('yarn.lock') ? 'yarn' : exists('bun.lockb') || exists('bun.lock') ? 'bun' : 'npm';
72
+ const run = (s) => (runner === 'npm' ? `npm run -s ${s}` : `${runner} ${s}`);
73
+ const scripts = pkg?.scripts ?? {};
74
+ for (const s of ['typecheck', 'type-check', 'check-types', 'tsc', 'check', 'lint']) if (scripts[s]) out.push({ command: run(s), why: `package.json "${s}" script` });
75
+ if (!out.length && exists('tsconfig.json') && exists('node_modules/.bin/tsc')) out.push({ command: 'npx tsc --noEmit', why: 'TypeScript project' });
76
+ if (scripts.test && !/no test specified/.test(scripts.test)) out.push({ command: runner === 'npm' ? 'npm test --silent' : `${runner} test`, why: 'package.json "test" script' });
77
+ if (exists('Cargo.toml')) out.push({ command: 'cargo check --quiet', why: 'Rust project' });
78
+ if (exists('go.mod')) out.push({ command: 'go vet ./...', why: 'Go project' }, { command: 'go build ./...', why: 'Go project' });
79
+ if (exists('pyproject.toml') || exists('setup.py') || exists('requirements.txt')) {
80
+ if (available('ruff')) out.push({ command: 'ruff check .', why: 'Python, ruff installed' });
81
+ if (available('mypy')) out.push({ command: 'mypy .', why: 'Python, mypy installed' });
82
+ if (available('pytest') || exists('pytest.ini') || exists('tests')) out.push({ command: 'python3 -m pytest -q -x', why: 'Python tests' });
83
+ }
84
+ if (exists('Makefile')) {
85
+ const mk = fs.readFileSync(path.join(cwd, 'Makefile'), 'utf8');
86
+ for (const t of ['check', 'lint', 'test']) if (new RegExp(`^${t}:`, 'm').test(mk)) out.push({ command: `make ${t}`, why: `Makefile "${t}" target` });
87
+ }
88
+ const seen = new Set();
89
+ return out.filter((c) => !seen.has(c.command) && seen.add(c.command));
90
+ }
91
+
92
+ // Run the project check. Resolves { ok, output, code, timedOut }.
93
+ export function runCheck(command, { cwd, signal, timeoutMs = 300000 } = {}) {
94
+ return new Promise((resolve) => {
95
+ const child = spawn(command, { cwd, shell: fs.existsSync('/bin/bash') ? '/bin/bash' : true, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, LETO: '1', CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' } });
96
+ let out = '';
97
+ const add = (d) => {
98
+ if (out.length < 400000) out += d.toString();
99
+ };
100
+ child.stdout.on('data', add);
101
+ child.stderr.on('data', add);
102
+ let timedOut = false;
103
+ const kill = () => {
104
+ try {
105
+ process.kill(-child.pid, 'SIGKILL');
106
+ } catch {}
107
+ };
108
+ const timer = setTimeout(() => {
109
+ timedOut = true;
110
+ kill();
111
+ }, timeoutMs);
112
+ signal?.addEventListener('abort', kill, { once: true });
113
+ const done = (code) => {
114
+ clearTimeout(timer);
115
+ signal?.removeEventListener('abort', kill);
116
+ resolve({ ok: code === 0 && !timedOut, code, output: out, timedOut });
117
+ };
118
+ child.on('error', () => done(-1));
119
+ child.on('close', done);
120
+ });
121
+ }
122
+
123
+ // Keep the end of long output, where compilers and test runners put the summary,
124
+ // plus the first error lines.
125
+ export function condense(output, max = 6000) {
126
+ const clean = output.replace(/\x1b\[[0-9;]*m/g, '').trim();
127
+ if (clean.length <= max) return clean;
128
+ const lines = clean.split('\n');
129
+ const errs = lines.filter((l) => /error|fail|✗|×|panic|exception/i.test(l)).slice(0, 40).join('\n').slice(0, max / 2);
130
+ return `${errs}\n…\n${clean.slice(-(max - errs.length - 10))}`;
131
+ }
package/src/version.js ADDED
@@ -0,0 +1,3 @@
1
+ import fs from 'node:fs';
2
+
3
+ export const VERSION = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
@@ -0,0 +1,87 @@
1
+ // Git worktrees: separate checkouts of the same repository, each on its own
2
+ // branch, so several agents can change code at the same time without
3
+ // stepping on each other or on your working copy.
4
+ //
5
+ // Worktrees live in ~/.leto/worktrees/<repo>-<id>, outside the project.
6
+ // When an agent finishes, its changes are committed to its branch
7
+ // (leto/<id>) and the checkout is removed; the branch stays for you to
8
+ // review and merge.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { HOME_DIR } from './config.js';
14
+
15
+ export const WORKTREES_DIR = path.join(HOME_DIR, 'worktrees');
16
+
17
+ function git(cwd, args, { allowFail = false } = {}) {
18
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 120000 });
19
+ if (r.status !== 0 && !allowFail) throw new Error(`git ${args.join(' ')} failed: ${(r.stderr || r.stdout || r.error?.message || '').trim()}`);
20
+ return { ok: r.status === 0, out: (r.stdout || '').trim(), err: (r.stderr || '').trim() };
21
+ }
22
+
23
+ export function repoRoot(cwd) {
24
+ const r = git(cwd, ['rev-parse', '--show-toplevel'], { allowFail: true });
25
+ return r.ok ? r.out : null;
26
+ }
27
+
28
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 30);
29
+
30
+ // Create a worktree on a new branch from HEAD. Uncommitted changes in your
31
+ // working copy are not carried over (HEAD is the starting point).
32
+ export function createWorktree(cwd, name = '') {
33
+ const root = repoRoot(cwd);
34
+ if (!root) throw new Error('Not a git repository, so there is no worktree to make. Run git init first, or work in place.');
35
+ if (!git(root, ['rev-parse', '--verify', 'HEAD'], { allowFail: true }).ok) throw new Error('This repository has no commits yet; make a first commit before using worktrees.');
36
+ const id = `${slug(name) || 'task'}-${crypto.randomBytes(2).toString('hex')}`;
37
+ const branch = `leto/${id}`;
38
+ const dir = path.join(WORKTREES_DIR, `${slug(path.basename(root))}-${id}`);
39
+ fs.mkdirSync(WORKTREES_DIR, { recursive: true });
40
+ git(root, ['worktree', 'add', '--quiet', '-b', branch, dir, 'HEAD']);
41
+ // Keep the agent in the same subfolder it was started from.
42
+ const sub = path.relative(root, cwd);
43
+ const workDir = sub && !sub.startsWith('..') ? path.join(dir, sub) : dir;
44
+ fs.mkdirSync(workDir, { recursive: true });
45
+ return { id, branch, dir, workDir, root, base: git(root, ['rev-parse', 'HEAD']).out };
46
+ }
47
+
48
+ // Commit what the agent changed, remove the checkout, and describe the result.
49
+ export function finishWorktree(wt, message) {
50
+ const status = git(wt.dir, ['status', '--porcelain']).out;
51
+ let committed = false;
52
+ if (status) {
53
+ git(wt.dir, ['add', '-A']);
54
+ const msg = `leto: ${message}`.slice(0, 200);
55
+ let r = git(wt.dir, ['commit', '--quiet', '--no-verify', '-m', msg], { allowFail: true });
56
+ // No git identity configured: commit as leto rather than fail.
57
+ if (!r.ok) r = git(wt.dir, ['-c', 'user.name=leto', '-c', 'user.email=leto@localhost', 'commit', '--quiet', '--no-verify', '-m', msg], { allowFail: true });
58
+ committed = r.ok;
59
+ }
60
+ const ahead = Number(git(wt.dir, ['rev-list', '--count', `${wt.base}..HEAD`], { allowFail: true }).out) || 0;
61
+ const stat = ahead ? git(wt.dir, ['diff', '--stat', `${wt.base}..HEAD`], { allowFail: true }).out : '';
62
+ git(wt.root, ['worktree', 'remove', '--force', wt.dir], { allowFail: true });
63
+ if (!ahead) {
64
+ git(wt.root, ['branch', '-D', wt.branch], { allowFail: true });
65
+ return { changed: false, branch: null, stat: '', summary: 'No changes were made, so the branch was removed.' };
66
+ }
67
+ const files = stat.split('\n').length - 1;
68
+ return {
69
+ changed: true,
70
+ committed,
71
+ branch: wt.branch,
72
+ stat,
73
+ summary: `Changes are on branch ${wt.branch} (${ahead} commit${ahead === 1 ? '' : 's'}, ${files} file${files === 1 ? '' : 's'}). Review with \`git diff HEAD...${wt.branch}\`; merge with \`git merge ${wt.branch}\`.`,
74
+ };
75
+ }
76
+
77
+ export function listLetoBranches(cwd) {
78
+ const root = repoRoot(cwd);
79
+ if (!root) return [];
80
+ return git(root, ['for-each-ref', '--format=%(refname:short)|%(committerdate:relative)|%(subject)', 'refs/heads/leto/', 'refs/heads/arrakis/'], { allowFail: true })
81
+ .out.split('\n')
82
+ .filter(Boolean)
83
+ .map((l) => {
84
+ const [branch, when, subject] = l.split('|');
85
+ return { branch, when, subject };
86
+ });
87
+ }
@@ -0,0 +1,132 @@
1
+ // Leto for VS Code.
2
+ //
3
+ // - "Leto: Open" (Cmd/Ctrl+Esc) runs leto in a terminal in this workspace.
4
+ // - The file you're looking at and your selection are shared with leto, so
5
+ // "explain this" or "fix this function" just works.
6
+ // - When leto edits a file, the change opens as a diff here.
7
+ //
8
+ // It talks to leto through small JSON files in ~/.leto/ide (no network).
9
+ const vscode = require('vscode');
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const path = require('path');
13
+
14
+ const HOME = process.env.LETO_HOME || process.env.ARRAKIS_HOME || [path.join(os.homedir(), '.leto'), path.join(os.homedir(), '.arrakis')].find((d) => fs.existsSync(d)) || path.join(os.homedir(), '.leto');
15
+ const DIR = path.join(HOME, 'ide');
16
+ const REQ = path.join(DIR, 'requests');
17
+
18
+ function folders() {
19
+ return (vscode.workspace.workspaceFolders || []).map((f) => f.uri.fsPath);
20
+ }
21
+
22
+ function stateFile() {
23
+ return path.join(DIR, `vscode-${process.pid}.json`);
24
+ }
25
+
26
+ let timer = null;
27
+ function writeState() {
28
+ clearTimeout(timer);
29
+ timer = setTimeout(() => {
30
+ try {
31
+ const ed = vscode.window.activeTextEditor;
32
+ const doc = ed && ed.document;
33
+ const sel = ed && ed.selection;
34
+ const state = {
35
+ app: vscode.env.appName,
36
+ pid: process.pid,
37
+ folders: folders(),
38
+ updated: Date.now(),
39
+ file: doc && doc.uri.scheme === 'file' ? doc.uri.fsPath : null,
40
+ language: doc ? doc.languageId : null,
41
+ dirty: doc ? doc.isDirty : false,
42
+ selection: sel && !sel.isEmpty ? { start: sel.start.line + 1, end: sel.end.line + 1, text: doc.getText(sel).slice(0, 8000) } : null,
43
+ cursor: sel ? sel.active.line + 1 : null,
44
+ open: vscode.window.visibleTextEditors.filter((e) => e.document.uri.scheme === 'file').map((e) => e.document.uri.fsPath).slice(0, 20),
45
+ diagnostics: doc
46
+ ? vscode.languages.getDiagnostics(doc.uri).filter((d) => d.severity === 0).slice(0, 20).map((d) => ({ line: d.range.start.line + 1, message: d.message }))
47
+ : [],
48
+ };
49
+ fs.mkdirSync(DIR, { recursive: true });
50
+ fs.writeFileSync(stateFile(), JSON.stringify(state));
51
+ } catch {}
52
+ }, 150);
53
+ }
54
+
55
+ // Requests from leto: open a diff, or open a file at a line.
56
+ function handleRequests() {
57
+ let files = [];
58
+ try {
59
+ files = fs.readdirSync(REQ).filter((f) => f.endsWith('.json'));
60
+ } catch {
61
+ return;
62
+ }
63
+ for (const f of files) {
64
+ const p = path.join(REQ, f);
65
+ let req;
66
+ try {
67
+ req = JSON.parse(fs.readFileSync(p, 'utf8'));
68
+ } catch {
69
+ continue;
70
+ }
71
+ // Stale, or meant for a workspace in another window: leave it (leto cleans up).
72
+ if (Date.now() - (req.t || 0) > 60000) {
73
+ fs.rmSync(p, { force: true });
74
+ continue;
75
+ }
76
+ if (!req.file || !folders().some((dir) => req.file.startsWith(dir + path.sep) || req.file === dir)) continue;
77
+ try {
78
+ fs.rmSync(p);
79
+ } catch {
80
+ continue; // another window took it
81
+ }
82
+ if (req.type === 'diff' && req.before) {
83
+ const left = vscode.Uri.file(req.before);
84
+ const right = vscode.Uri.file(req.file);
85
+ vscode.commands.executeCommand('vscode.diff', left, right, `${path.basename(req.file)} (leto${req.title ? `: ${req.title}` : ''})`, { preview: true, preserveFocus: true });
86
+ } else if (req.type === 'open') {
87
+ vscode.window.showTextDocument(vscode.Uri.file(req.file), { preview: true, preserveFocus: true, selection: req.line ? new vscode.Range(req.line - 1, 0, req.line - 1, 0) : undefined });
88
+ }
89
+ }
90
+ }
91
+
92
+ function activate(context) {
93
+ fs.mkdirSync(REQ, { recursive: true });
94
+ writeState();
95
+ context.subscriptions.push(
96
+ vscode.window.onDidChangeActiveTextEditor(writeState),
97
+ vscode.window.onDidChangeTextEditorSelection(writeState),
98
+ vscode.workspace.onDidChangeWorkspaceFolders(writeState),
99
+ vscode.languages.onDidChangeDiagnostics(writeState),
100
+ vscode.commands.registerCommand('leto.open', () => {
101
+ const existing = vscode.window.terminals.find((t) => t.name === 'leto');
102
+ if (existing) return existing.show();
103
+ const term = vscode.window.createTerminal({ name: 'leto', cwd: folders()[0], env: { LETO_IDE: 'vscode' } });
104
+ term.show();
105
+ term.sendText('leto');
106
+ }),
107
+ vscode.commands.registerCommand('leto.sendSelection', () => {
108
+ writeState();
109
+ const term = vscode.window.terminals.find((t) => t.name === 'leto');
110
+ if (!term) return vscode.commands.executeCommand('leto.open');
111
+ term.show();
112
+ }),
113
+ );
114
+ let watcher = null;
115
+ try {
116
+ watcher = fs.watch(REQ, () => handleRequests());
117
+ } catch {}
118
+ const poll = setInterval(handleRequests, 1000);
119
+ context.subscriptions.push({ dispose: () => {
120
+ clearInterval(poll);
121
+ if (watcher) watcher.close();
122
+ fs.rmSync(stateFile(), { force: true });
123
+ } });
124
+ }
125
+
126
+ function deactivate() {
127
+ try {
128
+ fs.rmSync(stateFile(), { force: true });
129
+ } catch {}
130
+ }
131
+
132
+ module.exports = { activate, deactivate };
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "leto",
3
+ "displayName": "Leto",
4
+ "description": "Use the leto coding agent from VS Code: it sees your open file and selection, and its edits open as diffs.",
5
+ "version": "0.1.0",
6
+ "publisher": "mumbrane",
7
+ "license": "MIT",
8
+ "engines": { "vscode": "^1.80.0" },
9
+ "categories": ["Other"],
10
+ "main": "./extension.js",
11
+ "activationEvents": ["onStartupFinished"],
12
+ "contributes": {
13
+ "commands": [
14
+ { "command": "leto.open", "title": "Leto: Open" },
15
+ { "command": "leto.sendSelection", "title": "Leto: Ask about the selection" }
16
+ ],
17
+ "keybindings": [
18
+ { "command": "leto.open", "key": "ctrl+escape", "mac": "cmd+escape" }
19
+ ]
20
+ }
21
+ }