@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.
- 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/patching.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
// Edits that survive small mistakes, and unified-diff patches.
|
|
2
|
+
//
|
|
3
|
+
// fuzzyFind(): when old_string isn't found exactly, look for it again with
|
|
4
|
+
// line endings, trailing spaces and indentation normalized. A unique match is
|
|
5
|
+
// used (and new_string is re-indented to fit); anything ambiguous is refused.
|
|
6
|
+
//
|
|
7
|
+
// parsePatch()/applyPatch(): apply a unified diff (git diff style) to one or
|
|
8
|
+
// more files, all or nothing. Hunks are found by their context lines, so a
|
|
9
|
+
// wrong line number in the @@ header doesn't matter.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
const indentOf = (l) => l.match(/^[ \t]*/)[0];
|
|
14
|
+
const norm = (l) => l.replace(/\s+$/, '').trimStart();
|
|
15
|
+
|
|
16
|
+
// Returns { start, end, actual, reindent } or { error }.
|
|
17
|
+
export function fuzzyFind(text, oldStr) {
|
|
18
|
+
const crlf = text.includes('\r\n');
|
|
19
|
+
const body = crlf ? text.replace(/\r\n/g, '\n') : text;
|
|
20
|
+
const want = oldStr.replace(/\r\n/g, '\n').replace(/^\n+|\n+$/g, '').split('\n');
|
|
21
|
+
if (!want.some((l) => l.trim())) return { error: 'old_string is only whitespace.' };
|
|
22
|
+
const lines = body.split('\n');
|
|
23
|
+
const target = want.map(norm);
|
|
24
|
+
const hits = [];
|
|
25
|
+
for (let i = 0; i + want.length <= lines.length; i++) {
|
|
26
|
+
let ok = true;
|
|
27
|
+
for (let j = 0; j < want.length; j++) {
|
|
28
|
+
if (norm(lines[i + j]) !== target[j]) {
|
|
29
|
+
ok = false;
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
if (ok) hits.push(i);
|
|
34
|
+
if (hits.length > 1) break;
|
|
35
|
+
}
|
|
36
|
+
if (!hits.length) return { error: null };
|
|
37
|
+
if (hits.length > 1) return { error: 'old_string matches several places once whitespace is ignored. Include more surrounding lines.' };
|
|
38
|
+
const i = hits[0];
|
|
39
|
+
const actualLines = lines.slice(i, i + want.length);
|
|
40
|
+
// Offsets into the original text (CRLF counts two characters per newline).
|
|
41
|
+
const nl = crlf ? 2 : 1;
|
|
42
|
+
let start = 0;
|
|
43
|
+
for (let k = 0; k < i; k++) start += lines[k].length + nl;
|
|
44
|
+
let end = start;
|
|
45
|
+
for (let k = 0; k < actualLines.length; k++) end += actualLines[k].length + (k < actualLines.length - 1 ? nl : 0);
|
|
46
|
+
const firstWant = want.find((l) => l.trim());
|
|
47
|
+
const firstActual = actualLines[want.indexOf(firstWant)];
|
|
48
|
+
return { start, end, actual: text.slice(start, end), from: indentOf(firstWant), to: indentOf(firstActual), crlf };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Re-indent replacement text by the same shift the match needed.
|
|
52
|
+
export function reindent(newStr, from, to, crlf) {
|
|
53
|
+
let out = newStr.replace(/\r\n/g, '\n');
|
|
54
|
+
if (from !== to) {
|
|
55
|
+
out = out
|
|
56
|
+
.split('\n')
|
|
57
|
+
.map((l) => (l.startsWith(from) ? to + l.slice(from.length) : l.trim() ? to + l.trimStart() : l))
|
|
58
|
+
.join('\n');
|
|
59
|
+
}
|
|
60
|
+
return crlf ? out.replace(/\n/g, '\r\n') : out;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// One edit with exact matching first, then the tolerant match.
|
|
64
|
+
// Returns { text, count, fuzzy, index } or throws with a helpful message.
|
|
65
|
+
export function applyEdit(text, { old_string, new_string, replace_all }, label = 'old_string') {
|
|
66
|
+
const count = text.split(old_string).length - 1;
|
|
67
|
+
if (count > 1 && !replace_all) throw new Error(`${label} matches ${count} places. Include more surrounding lines to make it unique, or set replace_all.`);
|
|
68
|
+
if (count >= 1) {
|
|
69
|
+
const index = text.indexOf(old_string);
|
|
70
|
+
const next = replace_all ? text.split(old_string).join(new_string) : text.slice(0, index) + new_string + text.slice(index + old_string.length);
|
|
71
|
+
return { text: next, count: replace_all ? count : 1, fuzzy: false, index };
|
|
72
|
+
}
|
|
73
|
+
const f = fuzzyFind(text, old_string);
|
|
74
|
+
if (f.error) throw new Error(f.error);
|
|
75
|
+
if (f.start === undefined) throw new Error(`${label} was not found in the file, even ignoring whitespace. Read the file again and copy the exact text.`);
|
|
76
|
+
const replacement = reindent(new_string, f.from, f.to, f.crlf);
|
|
77
|
+
return { text: text.slice(0, f.start) + replacement + text.slice(f.end), count: 1, fuzzy: true, index: f.start };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// --- unified diffs ----------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
const stripPrefix = (p) => p.replace(/^"|"$/g, '').replace(/^[ab]\//, '').replace(/\t.*$/, '').trim();
|
|
83
|
+
|
|
84
|
+
export function parsePatch(patch) {
|
|
85
|
+
const lines = String(patch).replace(/\r\n/g, '\n').replace(/^```(?:diff|patch)?\n|\n```\s*$/g, '').replace(/\n+$/, '').split('\n');
|
|
86
|
+
const files = [];
|
|
87
|
+
let cur = null;
|
|
88
|
+
let hunk = null;
|
|
89
|
+
for (let i = 0; i < lines.length; i++) {
|
|
90
|
+
const l = lines[i];
|
|
91
|
+
if (l.startsWith('--- ') && lines[i + 1]?.startsWith('+++ ')) {
|
|
92
|
+
const from = stripPrefix(l.slice(4));
|
|
93
|
+
const to = stripPrefix(lines[i + 1].slice(4));
|
|
94
|
+
cur = { from: from === '/dev/null' ? null : from, to: to === '/dev/null' ? null : to, hunks: [] };
|
|
95
|
+
files.push(cur);
|
|
96
|
+
hunk = null;
|
|
97
|
+
i++;
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const h = l.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
101
|
+
if (h && cur) {
|
|
102
|
+
hunk = { oldStart: Number(h[1]), lines: [] };
|
|
103
|
+
cur.hunks.push(hunk);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (!hunk) continue;
|
|
107
|
+
if (l.startsWith('\\')) continue; // ""
|
|
108
|
+
const sign = l[0];
|
|
109
|
+
if (sign === ' ' || sign === '-' || sign === '+') hunk.lines.push({ sign, text: l.slice(1) });
|
|
110
|
+
else if (l === '') hunk.lines.push({ sign: ' ', text: '' });
|
|
111
|
+
}
|
|
112
|
+
if (!files.length) throw new Error('No files in the patch. Use unified diff format: "--- a/path", "+++ b/path", then @@ hunks.');
|
|
113
|
+
for (const f of files) if (!f.hunks.length) throw new Error(`The patch for ${f.to ?? f.from} has no @@ hunks.`);
|
|
114
|
+
return files;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function findBlock(lines, block, near) {
|
|
118
|
+
const tryMatch = (eq) => {
|
|
119
|
+
const cands = [];
|
|
120
|
+
for (let i = 0; i + block.length <= lines.length; i++) {
|
|
121
|
+
let ok = true;
|
|
122
|
+
for (let j = 0; j < block.length; j++) if (!eq(lines[i + j], block[j])) {
|
|
123
|
+
ok = false;
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
if (ok) cands.push(i);
|
|
127
|
+
}
|
|
128
|
+
// Several matches: take the one closest to where the header said.
|
|
129
|
+
return cands.sort((a, b) => Math.abs(a - near) - Math.abs(b - near))[0] ?? -1;
|
|
130
|
+
};
|
|
131
|
+
let at = tryMatch((a, b) => a === b);
|
|
132
|
+
if (at < 0) at = tryMatch((a, b) => a.replace(/\s+$/, '') === b.replace(/\s+$/, ''));
|
|
133
|
+
if (at < 0) at = tryMatch((a, b) => norm(a) === norm(b));
|
|
134
|
+
return at;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Work out every file's new content without writing anything.
|
|
138
|
+
export function planPatch(patch, resolve) {
|
|
139
|
+
const files = parsePatch(patch);
|
|
140
|
+
return files.map((f) => {
|
|
141
|
+
const rel = f.to ?? f.from;
|
|
142
|
+
const p = resolve(rel);
|
|
143
|
+
if (!f.from) {
|
|
144
|
+
if (fs.existsSync(p)) throw new Error(`${rel} already exists; the patch creates it from /dev/null.`);
|
|
145
|
+
const content = f.hunks.flatMap((h) => h.lines.filter((x) => x.sign !== '-').map((x) => x.text)).join('\n');
|
|
146
|
+
return { rel, p, op: 'create', content: content + '\n', added: content.split('\n').length, removed: 0 };
|
|
147
|
+
}
|
|
148
|
+
if (!fs.existsSync(p)) throw new Error(`${f.from} does not exist.`);
|
|
149
|
+
if (!f.to) return { rel, p, op: 'delete', added: 0, removed: fs.readFileSync(p, 'utf8').split('\n').length };
|
|
150
|
+
const original = fs.readFileSync(p, 'utf8');
|
|
151
|
+
const crlf = original.includes('\r\n');
|
|
152
|
+
const trailingNl = original.endsWith('\n');
|
|
153
|
+
let lines = original.replace(/\r\n/g, '\n').replace(/\n$/, '').split('\n');
|
|
154
|
+
let added = 0;
|
|
155
|
+
let removed = 0;
|
|
156
|
+
let shift = 0;
|
|
157
|
+
for (const [n, h] of f.hunks.entries()) {
|
|
158
|
+
const oldBlock = h.lines.filter((x) => x.sign !== '+').map((x) => x.text);
|
|
159
|
+
const newBlock = h.lines.filter((x) => x.sign !== '-').map((x) => x.text);
|
|
160
|
+
let at = oldBlock.length ? findBlock(lines, oldBlock, h.oldStart - 1 + shift) : Math.min(lines.length, h.oldStart - 1 + shift);
|
|
161
|
+
if (at < 0) throw new Error(`Hunk ${n + 1} of ${rel} doesn't match the file (its context and - lines weren't found). Read the file and regenerate the patch. Nothing was changed.`);
|
|
162
|
+
lines = [...lines.slice(0, at), ...newBlock, ...lines.slice(at + oldBlock.length)];
|
|
163
|
+
shift += newBlock.length - oldBlock.length;
|
|
164
|
+
added += h.lines.filter((x) => x.sign === '+').length;
|
|
165
|
+
removed += h.lines.filter((x) => x.sign === '-').length;
|
|
166
|
+
}
|
|
167
|
+
let content = lines.join('\n') + (trailingNl ? '\n' : '');
|
|
168
|
+
if (crlf) content = content.replace(/\n/g, '\r\n');
|
|
169
|
+
const moved = f.from !== f.to ? resolve(f.from) : null;
|
|
170
|
+
return { rel, p, op: moved ? 'rename' : 'modify', content, added, removed, moved };
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function writePlan(plan, record) {
|
|
175
|
+
for (const f of plan) {
|
|
176
|
+
record?.(f.p);
|
|
177
|
+
if (f.moved) record?.(f.moved);
|
|
178
|
+
if (f.op === 'delete') fs.rmSync(f.p);
|
|
179
|
+
else {
|
|
180
|
+
fs.mkdirSync(path.dirname(f.p), { recursive: true });
|
|
181
|
+
fs.writeFileSync(f.p, f.content);
|
|
182
|
+
if (f.moved && f.moved !== f.p) fs.rmSync(f.moved);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Modes: 'ask' prompts for each write/command; 'yolo' allows everything;
|
|
2
|
+
// 'deny' refuses anything that needs permission (non-interactive default).
|
|
3
|
+
// planMode (separate flag) blocks every tool that changes files or runs commands.
|
|
4
|
+
// Prompts are serialized, so parallel sub-agents ask one question at a time.
|
|
5
|
+
//
|
|
6
|
+
// Command rules let one shell command run without asking ("npm test" also
|
|
7
|
+
// covers "npm test -- --watch"). They are remembered per project in your own
|
|
8
|
+
// config (~/.leto/config.json), never in the repository, so a cloned
|
|
9
|
+
// project can't grant itself permissions.
|
|
10
|
+
|
|
11
|
+
// Shell syntax that chains or redirects commands. A rule never covers these.
|
|
12
|
+
const COMPOUND = /[;&|><`$(){}\n\\]/;
|
|
13
|
+
|
|
14
|
+
// The part of a command a rule is about: "npm test", "git status", "ls".
|
|
15
|
+
export function commandPrefix(command) {
|
|
16
|
+
const c = String(command ?? '').trim();
|
|
17
|
+
if (!c || COMPOUND.test(c)) return null;
|
|
18
|
+
const words = c.split(/\s+/);
|
|
19
|
+
if (words.length > 1 && !words[1].startsWith('-') && /^[\w.:/@=-]+$/.test(words[1])) return `${words[0]} ${words[1]}`;
|
|
20
|
+
return words[0];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function ruleCovers(rule, command) {
|
|
24
|
+
const c = String(command ?? '').trim();
|
|
25
|
+
if (COMPOUND.test(c)) return false;
|
|
26
|
+
return c === rule || c.startsWith(rule + ' ');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class Permissions {
|
|
30
|
+
constructor({ ui, mode = 'ask', allow = [], commandRules = [], saveRule = null, removeRule = null }) {
|
|
31
|
+
this.ui = ui;
|
|
32
|
+
this.mode = mode;
|
|
33
|
+
this.planMode = false;
|
|
34
|
+
this.acceptEdits = false; // shift+tab mode: file edits run without asking
|
|
35
|
+
this.sandbox = false; // bash runs sandboxed and without asking
|
|
36
|
+
this.sandboxNetwork = false;
|
|
37
|
+
this.onDeny = null;
|
|
38
|
+
this.allowed = new Set(allow);
|
|
39
|
+
this.commandRules = new Set(commandRules);
|
|
40
|
+
this.saveRule = saveRule;
|
|
41
|
+
this.removeRule = removeRule;
|
|
42
|
+
this.lock = Promise.resolve();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
allowsCommand(command) {
|
|
46
|
+
return [...this.commandRules].some((r) => ruleCovers(r, command));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
revokeRule(rule) {
|
|
50
|
+
this.commandRules.delete(rule);
|
|
51
|
+
this.removeRule?.(rule);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
check(toolName, preview, args = {}) {
|
|
55
|
+
const decide = async () => {
|
|
56
|
+
if (this.mode === 'yolo' || this.allowed.has(toolName)) return true;
|
|
57
|
+
if (this.acceptEdits && ['edit_file', 'write_file', 'multi_edit', 'notebook_edit', 'apply_patch'].includes(toolName)) return true;
|
|
58
|
+
if (toolName === 'bash' && this.allowsCommand(args.command)) return true;
|
|
59
|
+
if (this.mode === 'deny') return false;
|
|
60
|
+
if (preview) preview.shown = true;
|
|
61
|
+
const prefix = toolName === 'bash' ? commandPrefix(args.command) : null;
|
|
62
|
+
const answer = await this.ui.confirm(preview, toolName, { prefix, args });
|
|
63
|
+
if (answer === 'always') this.allowed.add(toolName);
|
|
64
|
+
if (answer === 'prefix' && prefix) {
|
|
65
|
+
this.commandRules.add(prefix);
|
|
66
|
+
this.saveRule?.(prefix);
|
|
67
|
+
}
|
|
68
|
+
if (answer === 'no') this.onDeny?.();
|
|
69
|
+
return answer !== 'no';
|
|
70
|
+
};
|
|
71
|
+
const result = this.lock.then(decide, decide);
|
|
72
|
+
this.lock = result.catch(() => {});
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
}
|
package/src/plugins.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Plugins: shareable bundles of skills, agents, commands and MCP servers.
|
|
2
|
+
//
|
|
3
|
+
// leto plugin add https://github.com/acme/leto-web (or a local folder)
|
|
4
|
+
// leto plugin list | update [name] | remove <name>
|
|
5
|
+
//
|
|
6
|
+
// A plugin is a folder (usually a git repo) laid out like:
|
|
7
|
+
// plugin.json { "name": "web", "description": "…", "version": "1.0.0" }
|
|
8
|
+
// skills/<name>/SKILL.md
|
|
9
|
+
// agents/<name>.md
|
|
10
|
+
// commands/<name>.md
|
|
11
|
+
// mcp.json { "mcpServers": { … } }
|
|
12
|
+
// Installed plugins live in ~/.leto/plugins/<name> and count as your own
|
|
13
|
+
// (user-level) skills, agents, commands and servers, everywhere.
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { spawnSync } from 'node:child_process';
|
|
17
|
+
import { HOME_DIR } from './config.js';
|
|
18
|
+
|
|
19
|
+
export const PLUGINS_DIR = path.join(HOME_DIR, 'plugins');
|
|
20
|
+
|
|
21
|
+
export function listPlugins() {
|
|
22
|
+
let names = [];
|
|
23
|
+
try {
|
|
24
|
+
names = fs.readdirSync(PLUGINS_DIR, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
25
|
+
} catch {
|
|
26
|
+
return [];
|
|
27
|
+
}
|
|
28
|
+
return names.map((n) => {
|
|
29
|
+
const dir = path.join(PLUGINS_DIR, n);
|
|
30
|
+
let meta = {};
|
|
31
|
+
try {
|
|
32
|
+
meta = JSON.parse(fs.readFileSync(path.join(dir, 'plugin.json'), 'utf8'));
|
|
33
|
+
} catch {}
|
|
34
|
+
const count = (sub, test) => {
|
|
35
|
+
try {
|
|
36
|
+
return fs.readdirSync(path.join(dir, sub)).filter(test).length;
|
|
37
|
+
} catch {
|
|
38
|
+
return 0;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
return {
|
|
42
|
+
name: n,
|
|
43
|
+
dir,
|
|
44
|
+
description: meta.description ?? '',
|
|
45
|
+
version: meta.version ?? '',
|
|
46
|
+
source: meta.source ?? readSource(dir),
|
|
47
|
+
skills: count('skills', (x) => fs.existsSync(path.join(dir, 'skills', x, 'SKILL.md'))),
|
|
48
|
+
agents: count('agents', (x) => x.endsWith('.md')),
|
|
49
|
+
commands: count('commands', (x) => x.endsWith('.md')),
|
|
50
|
+
mcp: fs.existsSync(path.join(dir, 'mcp.json')),
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readSource(dir) {
|
|
56
|
+
const r = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: dir, encoding: 'utf8' });
|
|
57
|
+
return r.status === 0 ? r.stdout.trim() : '';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Folders that loaders should also look in.
|
|
61
|
+
export const pluginDirs = (sub) => listPlugins().map((p) => path.join(p.dir, sub)).filter((d) => fs.existsSync(d));
|
|
62
|
+
export const pluginMcpFiles = () => listPlugins().map((p) => path.join(p.dir, 'mcp.json')).filter((f) => fs.existsSync(f));
|
|
63
|
+
|
|
64
|
+
export function addPlugin(source) {
|
|
65
|
+
fs.mkdirSync(PLUGINS_DIR, { recursive: true });
|
|
66
|
+
const isUrl = /^(https?:|git@|ssh:)/.test(source) || /^[\w-]+\/[\w.-]+$/.test(source);
|
|
67
|
+
const url = /^[\w-]+\/[\w.-]+$/.test(source) && !fs.existsSync(source) ? `https://github.com/${source}` : source;
|
|
68
|
+
const tmp = path.join(PLUGINS_DIR, `.incoming-${Date.now()}`);
|
|
69
|
+
if (isUrl && !fs.existsSync(source)) {
|
|
70
|
+
const r = spawnSync('git', ['clone', '--quiet', '--depth', '1', url, tmp], { encoding: 'utf8' });
|
|
71
|
+
if (r.status !== 0) throw new Error(`git clone ${url} failed: ${(r.stderr || '').trim()}`);
|
|
72
|
+
} else {
|
|
73
|
+
const src = path.resolve(source);
|
|
74
|
+
if (!fs.existsSync(src)) throw new Error(`${source} is not a folder or a git URL.`);
|
|
75
|
+
fs.cpSync(src, tmp, { recursive: true, filter: (s) => !/[\\/](node_modules|\.git)([\\/]|$)/.test(s.slice(src.length)) });
|
|
76
|
+
}
|
|
77
|
+
let meta = {};
|
|
78
|
+
try {
|
|
79
|
+
meta = JSON.parse(fs.readFileSync(path.join(tmp, 'plugin.json'), 'utf8'));
|
|
80
|
+
} catch {}
|
|
81
|
+
const has = ['skills', 'agents', 'commands', 'mcp.json'].some((x) => fs.existsSync(path.join(tmp, x)));
|
|
82
|
+
if (!has) {
|
|
83
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
84
|
+
throw new Error('That is not a leto plugin: it has no skills/, agents/, commands/ or mcp.json.');
|
|
85
|
+
}
|
|
86
|
+
const name = String(meta.name || path.basename(url).replace(/\.git$/, '')).toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
|
|
87
|
+
const dest = path.join(PLUGINS_DIR, name);
|
|
88
|
+
if (fs.existsSync(dest)) {
|
|
89
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
90
|
+
throw new Error(`A plugin named "${name}" is already installed. Update it with: leto plugin update ${name}`);
|
|
91
|
+
}
|
|
92
|
+
if (!isUrl || fs.existsSync(source)) meta.source = path.resolve(source);
|
|
93
|
+
fs.renameSync(tmp, dest);
|
|
94
|
+
if (meta.source && !fs.existsSync(path.join(dest, '.git'))) fs.writeFileSync(path.join(dest, 'plugin.json'), JSON.stringify({ ...meta, name }, null, 2) + '\n');
|
|
95
|
+
return listPlugins().find((p) => p.name === name);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function removePlugin(name) {
|
|
99
|
+
const dest = path.join(PLUGINS_DIR, name);
|
|
100
|
+
if (!fs.existsSync(dest)) throw new Error(`No plugin named "${name}".`);
|
|
101
|
+
fs.rmSync(dest, { recursive: true, force: true });
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function updatePlugin(name) {
|
|
105
|
+
const p = listPlugins().find((x) => x.name === name);
|
|
106
|
+
if (!p) throw new Error(`No plugin named "${name}".`);
|
|
107
|
+
if (fs.existsSync(path.join(p.dir, '.git'))) {
|
|
108
|
+
const r = spawnSync('git', ['pull', '--quiet', '--ff-only'], { cwd: p.dir, encoding: 'utf8' });
|
|
109
|
+
if (r.status !== 0) throw new Error(`git pull failed: ${(r.stderr || '').trim()}`);
|
|
110
|
+
return 'updated from git';
|
|
111
|
+
}
|
|
112
|
+
if (p.source && fs.existsSync(p.source)) {
|
|
113
|
+
removePlugin(name);
|
|
114
|
+
addPlugin(p.source);
|
|
115
|
+
return `re-copied from ${p.source}`;
|
|
116
|
+
}
|
|
117
|
+
throw new Error(`${name} has no git remote or source folder to update from.`);
|
|
118
|
+
}
|
package/src/policy.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Managed settings: a policy file an administrator installs on a machine to
|
|
2
|
+
// set rules leto enforces, whatever the user's own config says.
|
|
3
|
+
//
|
|
4
|
+
// Looked up in order: $LETO_POLICY, /Library/Application Support/Leto/policy.json
|
|
5
|
+
// (macOS), /etc/leto/policy.json (Linux and others).
|
|
6
|
+
//
|
|
7
|
+
// {
|
|
8
|
+
// "allowedProviders": ["anthropic", "custom"], // others can't be used
|
|
9
|
+
// "allowedModels": ["^claude-(sonnet|haiku)-"], // regexes
|
|
10
|
+
// "providers": { "custom": { "baseUrl": "https://llm.internal/v1" } }, // fixed endpoints
|
|
11
|
+
// "disableYolo": true, // no --yolo or /yolo
|
|
12
|
+
// "forceSandbox": true, // shell commands always sandboxed
|
|
13
|
+
// "disabledTools": ["web_fetch", "browser"],
|
|
14
|
+
// "maxCostPerSession": 20, // dollars
|
|
15
|
+
// "disablePlugins": true,
|
|
16
|
+
// "usageEndpoint": "https://usage.internal/leto" // usage records are sent here
|
|
17
|
+
// }
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
|
|
20
|
+
let cached;
|
|
21
|
+
|
|
22
|
+
export function policyPath() {
|
|
23
|
+
const candidates = [process.env.LETO_POLICY, process.platform === 'darwin' ? '/Library/Application Support/Leto/policy.json' : null, '/etc/leto/policy.json', process.platform === 'darwin' ? '/Library/Application Support/Arrakis/policy.json' : null, '/etc/arrakis/policy.json'].filter(Boolean);
|
|
24
|
+
return candidates.find((p) => fs.existsSync(p)) ?? null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function loadPolicy() {
|
|
28
|
+
if (cached !== undefined) return cached;
|
|
29
|
+
const file = policyPath();
|
|
30
|
+
if (!file) return (cached = null);
|
|
31
|
+
try {
|
|
32
|
+
cached = { ...JSON.parse(fs.readFileSync(file, 'utf8')), file };
|
|
33
|
+
} catch (err) {
|
|
34
|
+
throw new Error(`The managed policy at ${file} is not valid JSON (${err.message}). Ask your administrator to fix it.`);
|
|
35
|
+
}
|
|
36
|
+
return cached;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const blocked = (what) => new Error(`${what} is not allowed by your organization's leto policy (${loadPolicy().file}).`);
|
|
40
|
+
|
|
41
|
+
export function checkProvider(id) {
|
|
42
|
+
const p = loadPolicy();
|
|
43
|
+
if (p?.allowedProviders?.length && id && !p.allowedProviders.includes(id)) throw blocked(`The provider "${id}"`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function checkModel(model) {
|
|
47
|
+
const p = loadPolicy();
|
|
48
|
+
if (p?.allowedModels?.length && model && !p.allowedModels.some((re) => new RegExp(re).test(model))) throw blocked(`The model "${model}"`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export const modelAllowed = (model) => {
|
|
52
|
+
try {
|
|
53
|
+
checkModel(model);
|
|
54
|
+
return true;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export function applyPolicyToConfig(config) {
|
|
61
|
+
const p = loadPolicy();
|
|
62
|
+
if (!p) return config;
|
|
63
|
+
checkProvider(config.provider);
|
|
64
|
+
const fixed = p.providers?.[config.provider];
|
|
65
|
+
if (fixed?.baseUrl) config.baseUrl = String(fixed.baseUrl).replace(/\/+$/, '');
|
|
66
|
+
if (fixed?.apiKey) config.apiKey = fixed.apiKey;
|
|
67
|
+
return config;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export const policyDisablesTool = (name) => Boolean(loadPolicy()?.disabledTools?.includes(name));
|
|
71
|
+
export const policyForbidsYolo = () => Boolean(loadPolicy()?.disableYolo);
|
|
72
|
+
export const policyForcesSandbox = () => Boolean(loadPolicy()?.forceSandbox);
|
|
73
|
+
export const policyBudget = () => Number(loadPolicy()?.maxCostPerSession) || 0;
|
|
74
|
+
export const policyDisablesPlugins = () => Boolean(loadPolicy()?.disablePlugins);
|
package/src/pricing.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Approximate list prices in USD per million tokens, for the session cost
|
|
2
|
+
// estimate. [input, output, cache read, cache write (5 min)]
|
|
3
|
+
const PRICES = [
|
|
4
|
+
[/claude-(fable|mythos)-5-2/, [8, 40, 0.2, 10]],
|
|
5
|
+
[/claude-(fable|mythos)-5(-1)?\b/, [10, 50, 0.25, 12.5]],
|
|
6
|
+
[/claude-opus-5-5/, [4, 20, 0.2, 5]],
|
|
7
|
+
[/claude-opus-(5|4-[5-9])\b/, [5, 25, 0.5, 6.25]],
|
|
8
|
+
[/claude-sonnet-5-5/, [2, 10, 0.1, 2.5]],
|
|
9
|
+
[/claude-sonnet-5\b/, [2, 10, 0.2, 2.5]],
|
|
10
|
+
[/claude-sonnet-4/, [3, 15, 0.3, 3.75]],
|
|
11
|
+
[/claude-haiku-5-5/, [0.1, 0.5, 0.01, 0.125]],
|
|
12
|
+
[/claude-haiku-4-5/, [1, 5, 0.1, 1.25]],
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
export function priceFor(model) {
|
|
16
|
+
return PRICES.find(([re]) => re.test(model))?.[1] ?? null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class Usage {
|
|
20
|
+
constructor() {
|
|
21
|
+
this.input = 0;
|
|
22
|
+
this.output = 0;
|
|
23
|
+
this.cacheRead = 0;
|
|
24
|
+
this.cacheWrite = 0;
|
|
25
|
+
this.requests = 0;
|
|
26
|
+
this.cost = 0;
|
|
27
|
+
this.priced = true;
|
|
28
|
+
this.byModel = {}; // model -> { requests, input, output, cost }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Accepts Anthropic usage ({input_tokens, output_tokens, cache_*}) or
|
|
32
|
+
// OpenAI usage ({prompt_tokens, completion_tokens}).
|
|
33
|
+
add(model, u) {
|
|
34
|
+
if (!u) return;
|
|
35
|
+
const read = u.cache_read_input_tokens ?? u.prompt_tokens_details?.cached_tokens ?? 0;
|
|
36
|
+
const input = u.input_tokens ?? Math.max(0, (u.prompt_tokens ?? 0) - (u.prompt_tokens_details?.cached_tokens ?? 0));
|
|
37
|
+
const output = u.output_tokens ?? u.completion_tokens ?? 0;
|
|
38
|
+
const write = u.cache_creation_input_tokens ?? 0;
|
|
39
|
+
this.input += input;
|
|
40
|
+
this.output += output;
|
|
41
|
+
this.cacheRead += read;
|
|
42
|
+
this.cacheWrite += write;
|
|
43
|
+
this.requests++;
|
|
44
|
+
const p = priceFor(model);
|
|
45
|
+
const cost = p ? (input * p[0] + output * p[1] + read * p[2] + write * p[3]) / 1e6 : 0;
|
|
46
|
+
if (p) this.cost += cost;
|
|
47
|
+
else this.priced = false;
|
|
48
|
+
const m = (this.byModel[model] ??= { requests: 0, input: 0, output: 0, cost: 0, priced: Boolean(p) });
|
|
49
|
+
m.requests++;
|
|
50
|
+
m.input += input + read + write;
|
|
51
|
+
m.output += output;
|
|
52
|
+
m.cost += cost;
|
|
53
|
+
this.onRecord?.({ model, input, output, cache_read: read, cache_write: write, cost: p ? Number(cost.toFixed(6)) : null });
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
get total() {
|
|
57
|
+
return this.input + this.output + this.cacheRead + this.cacheWrite;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
get cacheHitRate() {
|
|
61
|
+
const prompt = this.input + this.cacheRead + this.cacheWrite;
|
|
62
|
+
return prompt ? this.cacheRead / prompt : 0;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const formatCost = (usd) => (usd < 0.01 ? '<$0.01' : `$${usd.toFixed(2)}`);
|
|
67
|
+
export const formatTokens = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(2)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(n));
|
package/src/processes.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// Long-running processes and shell state.
|
|
2
|
+
//
|
|
3
|
+
// Background processes: `bash` with run_in_background starts a dev server,
|
|
4
|
+
// watcher or long build and returns at once. The model reads its output
|
|
5
|
+
// later with bash_output and stops it with kill_process. Output goes to a log
|
|
6
|
+
// file; everything still running is stopped when leto exits.
|
|
7
|
+
//
|
|
8
|
+
// Shell state: each bash call is a fresh shell, but the working directory and
|
|
9
|
+
// exported variables carry over to the next call, like a terminal session.
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
|
|
15
|
+
const LOG_DIR = path.join(os.tmpdir(), `leto-procs-${process.pid}`);
|
|
16
|
+
const procs = new Map(); // id -> { id, command, pid, log, started, code, readAt, reported }
|
|
17
|
+
let seq = 0;
|
|
18
|
+
|
|
19
|
+
function killTree(pid) {
|
|
20
|
+
try {
|
|
21
|
+
process.kill(-pid, 'SIGTERM');
|
|
22
|
+
} catch {}
|
|
23
|
+
setTimeout(() => {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(-pid, 'SIGKILL');
|
|
26
|
+
} catch {}
|
|
27
|
+
}, 1500).unref();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
process.on('exit', () => {
|
|
31
|
+
for (const p of procs.values()) if (p.code === null) {
|
|
32
|
+
try {
|
|
33
|
+
process.kill(-p.pid, 'SIGKILL');
|
|
34
|
+
} catch {}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export function startProcess({ cmd, args, shell, cwd, env, command }) {
|
|
39
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
40
|
+
const id = `p${++seq}`;
|
|
41
|
+
const log = path.join(LOG_DIR, `${id}.log`);
|
|
42
|
+
const fd = fs.openSync(log, 'a');
|
|
43
|
+
const child = spawn(cmd, args, { cwd, shell, env, detached: true, stdio: ['ignore', fd, fd] });
|
|
44
|
+
fs.closeSync(fd);
|
|
45
|
+
child.unref(); // never keeps leto from exiting
|
|
46
|
+
const p = { id, command, pid: child.pid, log, started: Date.now(), code: null, readAt: 0, reported: false };
|
|
47
|
+
child.on('exit', (code, signal) => {
|
|
48
|
+
p.code = code ?? (signal ? 128 : -1);
|
|
49
|
+
p.signal = signal;
|
|
50
|
+
p.ended = Date.now();
|
|
51
|
+
});
|
|
52
|
+
child.on('error', (err) => {
|
|
53
|
+
p.code = -1;
|
|
54
|
+
p.error = err.message;
|
|
55
|
+
});
|
|
56
|
+
procs.set(id, p);
|
|
57
|
+
return p;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const listProcesses = () => [...procs.values()];
|
|
61
|
+
export const getProcess = (id) => procs.get(id);
|
|
62
|
+
|
|
63
|
+
const status = (p) => (p.code === null ? `running (pid ${p.pid}, ${Math.round((Date.now() - p.started) / 1000)}s)` : `exited with code ${p.code}${p.signal ? ` (${p.signal})` : ''}${p.error ? `: ${p.error}` : ''}`);
|
|
64
|
+
|
|
65
|
+
// New output since the last read (or all of it), optionally filtered.
|
|
66
|
+
export function readProcess(id, { filter, all = false, max = 30000 } = {}) {
|
|
67
|
+
const p = procs.get(id);
|
|
68
|
+
if (!p) throw new Error(`No background process "${id}". Running: ${listProcesses().filter((x) => x.code === null).map((x) => x.id).join(', ') || 'none'}`);
|
|
69
|
+
let buf = '';
|
|
70
|
+
try {
|
|
71
|
+
buf = fs.readFileSync(p.log, 'utf8');
|
|
72
|
+
} catch {}
|
|
73
|
+
let out = all ? buf : buf.slice(p.readAt);
|
|
74
|
+
p.readAt = buf.length;
|
|
75
|
+
if (filter) {
|
|
76
|
+
const re = new RegExp(filter, 'i');
|
|
77
|
+
out = out.split('\n').filter((l) => re.test(l)).join('\n');
|
|
78
|
+
}
|
|
79
|
+
out = out.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '');
|
|
80
|
+
if (out.length > max) out = `… (${out.length - max} earlier characters not shown)\n${out.slice(-max)}`;
|
|
81
|
+
if (p.code !== null) p.reported = true;
|
|
82
|
+
return { p, text: `${p.id} \`${p.command}\`: ${status(p)}\n${out.trim() ? out.trimEnd() : '(no new output)'}` };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function stopProcess(id) {
|
|
86
|
+
const p = procs.get(id);
|
|
87
|
+
if (!p) throw new Error(`No background process "${id}".`);
|
|
88
|
+
if (p.code !== null) return `${id} had already ${status(p)}.`;
|
|
89
|
+
killTree(p.pid);
|
|
90
|
+
p.reported = true;
|
|
91
|
+
return `Stopped ${id} (\`${p.command}\`).`;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Processes that ended since the model last looked: worth telling it.
|
|
95
|
+
export function unreportedExits() {
|
|
96
|
+
const out = [];
|
|
97
|
+
for (const p of procs.values()) {
|
|
98
|
+
if (p.code !== null && !p.reported) {
|
|
99
|
+
p.reported = true;
|
|
100
|
+
out.push(`[Background process ${p.id} (\`${p.command}\`) ${status(p)}. Read its output with bash_output.]`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// --- shell state ----------------------------------------------------------------
|
|
107
|
+
|
|
108
|
+
const SKIP_ENV = new Set(['PWD', 'OLDPWD', 'SHLVL', '_', 'LETO_STATE']);
|
|
109
|
+
|
|
110
|
+
// Wrap a command so the shell writes its final directory and environment.
|
|
111
|
+
export function withState(command, stateFile) {
|
|
112
|
+
return `trap 'pwd > "${stateFile}.cwd"; env -0 > "${stateFile}.env"' EXIT\n${command}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function readState(stateFile, baseEnv) {
|
|
116
|
+
const out = {};
|
|
117
|
+
try {
|
|
118
|
+
out.cwd = fs.readFileSync(`${stateFile}.cwd`, 'utf8').trim();
|
|
119
|
+
} catch {}
|
|
120
|
+
try {
|
|
121
|
+
const raw = fs.readFileSync(`${stateFile}.env`, 'utf8');
|
|
122
|
+
const env = {};
|
|
123
|
+
for (const kv of raw.split('\0')) {
|
|
124
|
+
const i = kv.indexOf('=');
|
|
125
|
+
if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1);
|
|
126
|
+
}
|
|
127
|
+
// Only what the commands changed, compared with what they started with.
|
|
128
|
+
out.env = {};
|
|
129
|
+
for (const [k, v] of Object.entries(env)) if (!SKIP_ENV.has(k) && baseEnv[k] !== v) out.env[k] = v;
|
|
130
|
+
out.unset = Object.keys(baseEnv).filter((k) => !SKIP_ENV.has(k) && !(k in env));
|
|
131
|
+
} catch {}
|
|
132
|
+
for (const ext of ['.cwd', '.env']) fs.rmSync(`${stateFile}${ext}`, { force: true });
|
|
133
|
+
return out;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function stateFileFor() {
|
|
137
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
138
|
+
return path.join(LOG_DIR, `state-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`);
|
|
139
|
+
}
|