@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/theme.js ADDED
@@ -0,0 +1,185 @@
1
+ // "Spice": leto's design language.
2
+ //
3
+ // A desert palette: spice gold as the primary, burnt orange and ember as
4
+ // accents, sand for soft text, dark umber panels behind code. Sage, saffron
5
+ // and rose carry meaning (success, caution, error) and are used sparingly.
6
+ // (The keys below name roles, kept from earlier themes: `violet` is the
7
+ // primary color, `orchid` the hot accent, `lilac` the soft text, and so on.)
8
+ //
9
+ // Colors render in 24-bit where the terminal supports it and fall back to the
10
+ // nearest 256-color value elsewhere (e.g. macOS Terminal.app). NO_COLOR turns
11
+ // everything off.
12
+
13
+ export const PALETTE = {
14
+ violet: [232, 166, 64], // primary: spice gold
15
+ iris: [196, 104, 38], // deep accent: burnt orange
16
+ orchid: [244, 128, 52], // hot accent: ember
17
+ lilac: [240, 226, 196], // soft text: sand
18
+ mist: [156, 144, 124], // muted text: dune
19
+ dusk: [96, 86, 70], // faint lines
20
+ mint: [150, 208, 130], // success: sage
21
+ amber: [242, 206, 108], // caution / numbers: saffron
22
+ rose: [238, 110, 110],
23
+ sky: [124, 196, 210], // functions, links: oasis teal
24
+ ink: [26, 19, 11], // text on gold chips
25
+ panel: [40, 32, 22], // code panels: umber
26
+ raise: [58, 45, 28], // selected rows, your messages
27
+ addBg: [28, 50, 30],
28
+ delBg: [64, 28, 26],
29
+ };
30
+
31
+ // Other palettes, same roles. `spice-light` is for light terminal backgrounds;
32
+ // `mono` drops the hues except for errors.
33
+ export const PALETTES = {
34
+ spice: { ...PALETTE },
35
+ 'spice-light': {
36
+ violet: [166, 98, 6], iris: [160, 66, 12], orchid: [190, 76, 16], lilac: [52, 38, 20], mist: [118, 102, 82], dusk: [196, 182, 156],
37
+ mint: [36, 128, 66], amber: [160, 112, 0], rose: [186, 44, 58], sky: [18, 106, 138], ink: [255, 250, 240],
38
+ panel: [244, 236, 220], raise: [236, 222, 194], addBg: [214, 240, 220], delBg: [250, 222, 222],
39
+ },
40
+ mono: {
41
+ violet: [225, 225, 225], iris: [160, 160, 160], orchid: [245, 245, 245], lilac: [215, 215, 215], mist: [140, 140, 140], dusk: [80, 80, 80],
42
+ mint: [200, 200, 200], amber: [210, 210, 210], rose: [235, 110, 110], sky: [190, 190, 190], ink: [20, 20, 20],
43
+ panel: [38, 38, 38], raise: [52, 52, 52], addBg: [40, 56, 44], delBg: [60, 40, 40],
44
+ },
45
+ };
46
+
47
+ // 'auto' picks the light palette when the terminal says its background is light.
48
+ export function resolveTheme(name) {
49
+ if (name && name !== 'auto' && PALETTES[name]) return name;
50
+ const bg = Number((process.env.COLORFGBG ?? '').split(';').pop());
51
+ return bg === 7 || bg === 15 ? 'spice-light' : 'spice';
52
+ }
53
+
54
+ export let THEME = 'spice';
55
+ export function setTheme(name) {
56
+ THEME = resolveTheme(name);
57
+ Object.assign(PALETTE, PALETTES[THEME]);
58
+ return THEME;
59
+ }
60
+
61
+ const env = process.env;
62
+ export const TRUECOLOR =
63
+ /truecolor|24bit/i.test(env.COLORTERM ?? '') ||
64
+ /iTerm|WezTerm|vscode|ghostty|Hyper|Tabby|WarpTerminal|rio/i.test(env.TERM_PROGRAM ?? '') ||
65
+ Boolean(env.WT_SESSION || env.KITTY_WINDOW_ID || env.ALACRITTY_LOG);
66
+
67
+ function to256([r, g, b]) {
68
+ // Grays get the 24-step gray ramp, colors the 6x6x6 cube.
69
+ if (Math.abs(r - g) < 10 && Math.abs(g - b) < 10) {
70
+ if (r < 8) return 16;
71
+ if (r > 248) return 231;
72
+ return 232 + Math.round(((r - 8) / 247) * 23);
73
+ }
74
+ const q = (v) => (v < 48 ? 0 : v < 115 ? 1 : Math.round((v - 35) / 40));
75
+ return 16 + 36 * q(r) + 6 * q(g) + q(b);
76
+ }
77
+
78
+ const fgCode = (rgb) => (TRUECOLOR ? `38;2;${rgb[0]};${rgb[1]};${rgb[2]}` : `38;5;${to256(rgb)}`);
79
+ const bgCode = (rgb) => (TRUECOLOR ? `48;2;${rgb[0]};${rgb[1]};${rgb[2]}` : `48;5;${to256(rgb)}`);
80
+
81
+ // Each style closes with its own reset code, so styles nest (e.g. colored
82
+ // text inside a background panel keeps the panel).
83
+ const wrap = (open, close, on) => (s) => (on ? `\x1b[${open}m${s}\x1b[${close}m` : String(s));
84
+
85
+ const mix = (a, b, t) => a.map((v, i) => Math.round(v + (b[i] - v) * t));
86
+
87
+ export function makeTheme(on) {
88
+ const fg = (rgb) => wrap(fgCode(rgb), '39', on);
89
+ const bg = (rgb) => wrap(bgCode(rgb), '49', on);
90
+ const P = PALETTE;
91
+ const t = {
92
+ on,
93
+ bold: wrap('1', '22', on),
94
+ dim: wrap('2', '22', on),
95
+ italic: wrap('3', '23', on),
96
+ underline: wrap('4', '24', on),
97
+ strike: wrap('9', '29', on),
98
+ inverse: wrap('7', '27', on),
99
+ fg,
100
+ bg,
101
+ violet: fg(P.violet),
102
+ iris: fg(P.iris),
103
+ orchid: fg(P.orchid),
104
+ lilac: fg(P.lilac),
105
+ mist: fg(P.mist),
106
+ faint: fg(P.dusk),
107
+ mint: fg(P.mint),
108
+ amber: fg(P.amber),
109
+ rose: fg(P.rose),
110
+ sky: fg(P.sky),
111
+ ink: fg(P.ink),
112
+ panelBg: bg(P.panel),
113
+ raiseBg: bg(P.raise),
114
+ addBg: bg(P.addBg),
115
+ delBg: bg(P.delBg),
116
+ violetBg: bg(P.violet),
117
+
118
+ // Color each character along a gradient of stops. `phase` (0-1) shifts it.
119
+ gradient(text, stops = [P.iris, P.violet, P.orchid], phase = 0) {
120
+ if (!on) return String(text);
121
+ const chars = [...String(text)];
122
+ const n = Math.max(1, chars.length - 1);
123
+ return (
124
+ chars
125
+ .map((ch, i) => {
126
+ if (ch === ' ') return ch;
127
+ let x = (i / n + phase) % 1;
128
+ if (phase) x = x < 0.5 ? x * 2 : 2 - x * 2; // ping-pong so it loops smoothly
129
+ const seg = x * (stops.length - 1);
130
+ const k = Math.min(stops.length - 2, Math.floor(seg));
131
+ return `\x1b[${fgCode(mix(stops[k], stops[k + 1], seg - k))}m${ch}`;
132
+ })
133
+ .join('') + '\x1b[39m'
134
+ );
135
+ },
136
+
137
+ // A bright band sweeping across muted text (for the working indicator).
138
+ shimmer(text, frame) {
139
+ if (!on) return String(text);
140
+ const chars = [...String(text)];
141
+ const pos = (frame % (chars.length + 8)) - 4;
142
+ return (
143
+ chars
144
+ .map((ch, i) => {
145
+ const d = Math.abs(i - pos);
146
+ const c = d < 1 ? P.lilac : d < 2.5 ? mix(P.lilac, P.violet, 0.5) : d < 4 ? P.violet : mix(P.violet, P.mist, 0.55);
147
+ return `\x1b[${fgCode(c)}m${ch}`;
148
+ })
149
+ .join('') + '\x1b[39m'
150
+ );
151
+ },
152
+ };
153
+ // Names the rest of the code already uses, mapped onto the palette.
154
+ Object.assign(t, {
155
+ accent: t.violet,
156
+ sand: t.lilac,
157
+ gray: t.mist,
158
+ green: t.mint,
159
+ red: t.rose,
160
+ yellow: t.amber,
161
+ magenta: t.orchid,
162
+ cyan: t.sky,
163
+ blue: t.violet,
164
+ userBg: t.raiseBg,
165
+ });
166
+ return t;
167
+ }
168
+
169
+ // Glyphs of the design language, in one place.
170
+ export const GLYPH = {
171
+ reply: '◆',
172
+ tool: '◇',
173
+ result: '╰',
174
+ user: '▌',
175
+ thinking: '✧',
176
+ prompt: '❯',
177
+ ok: '✓',
178
+ fail: '✕',
179
+ info: '·',
180
+ todo: { pending: '○', in_progress: '◉', completed: '●' },
181
+ spinner: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'],
182
+ };
183
+
184
+ // "LETO" in a two-row block font.
185
+ export const LOGO = ['▄▀█ █▀█ █▀█ ▄▀█ █▄▀ █ █▀', '█▀█ █▀▄ █▀▄ █▀█ █ █ █ ▄█'];
@@ -0,0 +1,257 @@
1
+ // Tool calls for models whose function calling is missing or unreliable.
2
+ //
3
+ // - parseToolCalls() finds tool calls a model wrote as text instead of using
4
+ // the API's tool-call field: <tool_call>{json}</tool_call> (Hermes/Qwen
5
+ // style), <function=name>{json}</function> (Llama style),
6
+ // <invoke name="x"><parameter name="p">v</parameter></invoke>, and fenced
7
+ // ```json {"name": …, "arguments": …}``` blocks. Only names of real tools
8
+ // count, so ordinary prose and code samples are left alone.
9
+ // - repairJson() fixes common breakage in tool arguments: code fences,
10
+ // trailing commas, single quotes, unquoted keys, missing closing brackets.
11
+ // - Text tool mode (config toolMode "text") skips the API's tools field
12
+ // entirely: the tools are described in the system prompt, calls are parsed
13
+ // from the reply, and results go back as plain user messages.
14
+
15
+ export function repairJson(raw) {
16
+ if (raw == null) return null;
17
+ let s = String(raw).trim();
18
+ if (!s) return {};
19
+ const tryParse = (x) => {
20
+ try {
21
+ return JSON.parse(x);
22
+ } catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ let v = tryParse(s);
27
+ if (v !== undefined) return v;
28
+ s = s.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
29
+ const start = s.indexOf('{');
30
+ if (start > 0) s = s.slice(start);
31
+ v = tryParse(s);
32
+ if (v !== undefined) return v;
33
+ // Trailing commas, single-quoted strings, unquoted keys, Python literals.
34
+ let t = s
35
+ .replace(/,\s*([}\]])/g, '$1')
36
+ .replace(/'((?:[^'\\]|\\.)*)'/g, (_, x) => JSON.stringify(x.replace(/\\'/g, "'")))
37
+ .replace(/([{,]\s*)([A-Za-z_][\w-]*)\s*:/g, '$1"$2":')
38
+ .replace(/:\s*True\b/g, ': true')
39
+ .replace(/:\s*False\b/g, ': false')
40
+ .replace(/:\s*None\b/g, ': null');
41
+ v = tryParse(t);
42
+ if (v !== undefined) return v;
43
+ // Cut off part-way: close the open string and brackets.
44
+ t = closeOpen(t);
45
+ v = tryParse(t);
46
+ return v === undefined ? null : v;
47
+ }
48
+
49
+ function closeOpen(s) {
50
+ const stack = [];
51
+ let inStr = false;
52
+ let esc = false;
53
+ for (const ch of s) {
54
+ if (inStr) {
55
+ if (esc) esc = false;
56
+ else if (ch === '\\') esc = true;
57
+ else if (ch === '"') inStr = false;
58
+ continue;
59
+ }
60
+ if (ch === '"') inStr = true;
61
+ else if (ch === '{') stack.push('}');
62
+ else if (ch === '[') stack.push(']');
63
+ else if (ch === '}' || ch === ']') stack.pop();
64
+ }
65
+ let out = s;
66
+ if (inStr) out += '"';
67
+ out = out.replace(/,\s*$/, '');
68
+ return out + stack.reverse().join('');
69
+ }
70
+
71
+ // Pull JSON objects out of text by balancing braces (strings respected).
72
+ function jsonObjectsIn(text) {
73
+ const out = [];
74
+ for (let i = 0; i < text.length; i++) {
75
+ if (text[i] !== '{') continue;
76
+ let depth = 0;
77
+ let inStr = false;
78
+ let esc = false;
79
+ for (let j = i; j < text.length; j++) {
80
+ const ch = text[j];
81
+ if (inStr) {
82
+ if (esc) esc = false;
83
+ else if (ch === '\\') esc = true;
84
+ else if (ch === '"') inStr = false;
85
+ continue;
86
+ }
87
+ if (ch === '"') inStr = true;
88
+ else if (ch === '{') depth++;
89
+ else if (ch === '}' && --depth === 0) {
90
+ out.push({ start: i, end: j + 1, text: text.slice(i, j + 1) });
91
+ i = j;
92
+ break;
93
+ }
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+
99
+ let seq = 0;
100
+ const callId = () => `call_txt_${Date.now().toString(36)}_${seq++}`;
101
+
102
+ function asCall(name, args, names) {
103
+ if (!name || !names.has(name)) return null;
104
+ let input = args;
105
+ if (typeof input === 'string') input = repairJson(input) ?? {};
106
+ if (!input || typeof input !== 'object' || Array.isArray(input)) input = {};
107
+ return { id: callId(), type: 'function', function: { name, arguments: JSON.stringify(input) } };
108
+ }
109
+
110
+ // Returns { calls, text } where text has the tool-call markup removed.
111
+ export function parseToolCalls(text, toolNames) {
112
+ const names = toolNames instanceof Set ? toolNames : new Set(toolNames);
113
+ const calls = [];
114
+ const spans = [];
115
+ const s = String(text ?? '');
116
+ const take = (re, fn) => {
117
+ for (const m of s.matchAll(re)) {
118
+ if (spans.some(([a, b]) => m.index < b && m.index + m[0].length > a)) continue;
119
+ const call = fn(m);
120
+ if (call) {
121
+ calls.push({ at: m.index, call });
122
+ spans.push([m.index, m.index + m[0].length]);
123
+ }
124
+ }
125
+ };
126
+ // <tool_call>{"name": "...", "arguments": {...}}</tool_call>
127
+ take(/<tool_call>\s*([\s\S]*?)\s*(?:<\/tool_call>|$)/g, (m) => {
128
+ const obj = repairJson(m[1]);
129
+ return obj && asCall(obj.name ?? obj.tool ?? obj.function?.name, obj.arguments ?? obj.parameters ?? obj.input ?? obj.function?.arguments ?? {}, names);
130
+ });
131
+ // <function=name>{...}</function>
132
+ take(/<function=([\w.-]+)>\s*([\s\S]*?)\s*(?:<\/function>|$)/g, (m) => asCall(m[1], m[2] || '{}', names));
133
+ // <invoke name="x"><parameter name="p">v</parameter></invoke>
134
+ take(/<invoke name="([\w.-]+)">([\s\S]*?)<\/invoke>/g, (m) => {
135
+ const args = {};
136
+ for (const p of m[2].matchAll(/<parameter name="([\w-]+)">([\s\S]*?)<\/parameter>/g)) {
137
+ const v = p[2].trim();
138
+ const parsed = /^[[{]|^(true|false|null|-?\d+(\.\d+)?)$/.test(v) ? repairJson(v) : null;
139
+ args[p[1]] = parsed ?? v;
140
+ }
141
+ return asCall(m[1], args, names);
142
+ });
143
+ // ```json {"name": "...", "arguments": {...}} ``` or a bare object on its own.
144
+ if (!calls.length) {
145
+ for (const o of jsonObjectsIn(s)) {
146
+ const obj = repairJson(o.text);
147
+ if (!obj || typeof obj !== 'object') continue;
148
+ const name = obj.name ?? obj.tool ?? obj.function?.name;
149
+ const args = obj.arguments ?? obj.parameters ?? obj.input ?? obj.function?.arguments;
150
+ if (args === undefined) continue;
151
+ const call = asCall(name, args, names);
152
+ if (call) {
153
+ calls.push({ at: o.start, call });
154
+ // Remove the surrounding code fence too.
155
+ const before = s.slice(0, o.start).match(/```(?:json)?\s*$/);
156
+ const after = s.slice(o.end).match(/^\s*```/);
157
+ spans.push([before ? o.start - before[0].length : o.start, after ? o.end + after[0].length : o.end]);
158
+ }
159
+ }
160
+ }
161
+ calls.sort((a, b) => a.at - b.at);
162
+ let clean = s;
163
+ for (const [a, b] of [...spans].sort((x, y) => y[0] - x[0])) clean = clean.slice(0, a) + clean.slice(b);
164
+ clean = clean.replace(/<\/?tool_calls?>/g, '').replace(/\n{3,}/g, '\n\n').trim();
165
+ return { calls: calls.map((c) => c.call), text: clean };
166
+ }
167
+
168
+ // Hide tool-call markup while a reply streams, so the user sees only prose.
169
+ export class MarkupFilter {
170
+ constructor(onText) {
171
+ this.onText = onText;
172
+ this.hold = '';
173
+ this.hidden = false;
174
+ }
175
+
176
+ static MARKERS = ['<tool_call>', '<function=', '<invoke name='];
177
+
178
+ push(s) {
179
+ if (this.hidden) return;
180
+ this.hold += s;
181
+ for (const m of MarkupFilter.MARKERS) {
182
+ const i = this.hold.indexOf(m);
183
+ if (i >= 0) {
184
+ this.flush(this.hold.slice(0, i));
185
+ this.hold = '';
186
+ this.hidden = true;
187
+ return;
188
+ }
189
+ }
190
+ // Keep back a tail that could be the start of a marker.
191
+ const lt = this.hold.lastIndexOf('<');
192
+ if (lt >= 0 && this.hold.length - lt < 16 && MarkupFilter.MARKERS.some((m) => m.startsWith(this.hold.slice(lt)))) {
193
+ this.flush(this.hold.slice(0, lt));
194
+ this.hold = this.hold.slice(lt);
195
+ } else {
196
+ this.flush(this.hold);
197
+ this.hold = '';
198
+ }
199
+ }
200
+
201
+ end() {
202
+ if (!this.hidden) this.flush(this.hold);
203
+ this.hold = '';
204
+ }
205
+
206
+ flush(s) {
207
+ if (s) this.onText(s);
208
+ }
209
+ }
210
+
211
+ // System-prompt section that teaches text tool calling.
212
+ export function renderToolPrompt(tools) {
213
+ const list = tools
214
+ .map((t) => `## ${t.function.name}\n${t.function.description}\nParameters (JSON Schema): ${JSON.stringify(t.function.parameters ?? { type: 'object', properties: {} })}`)
215
+ .join('\n\n');
216
+ return `# Calling tools
217
+ You can call the tools below. To call one, write a tool_call block with a JSON object holding the tool name and its arguments, exactly like this:
218
+
219
+ <tool_call>
220
+ {"name": "read_file", "arguments": {"path": "src/app.js"}}
221
+ </tool_call>
222
+
223
+ Rules:
224
+ - The arguments must be valid JSON that matches the tool's parameters.
225
+ - You may write several tool_call blocks in one reply; they run in order.
226
+ - After your tool calls, stop and wait. The results come back in a <tool_result> message.
227
+ - When you don't need a tool, just answer normally without any tool_call block.
228
+
229
+ ${list}`;
230
+ }
231
+
232
+ // Internal history -> text-only messages for text tool mode.
233
+ export function toTextHistory(messages, tools) {
234
+ const out = [];
235
+ for (const m of messages) {
236
+ if (m.role === 'system' && !out.length) {
237
+ out.push({ role: 'system', content: `${m.content}\n\n${renderToolPrompt(tools)}` });
238
+ } else if (m.role === 'assistant' && m.tool_calls?.length) {
239
+ const calls = m.tool_calls.map((c) => {
240
+ let args = {};
241
+ try {
242
+ args = JSON.parse(c.function.arguments || '{}');
243
+ } catch {}
244
+ return `<tool_call>\n${JSON.stringify({ name: c.function.name, arguments: args })}\n</tool_call>`;
245
+ });
246
+ out.push({ role: 'assistant', content: [m.content, ...calls].filter(Boolean).join('\n\n') });
247
+ } else if (m.role === 'tool') {
248
+ const text = `<tool_result id="${m.tool_call_id}">\n${m.content}\n</tool_result>`;
249
+ const last = out.at(-1);
250
+ // Several results from one reply go in one user message.
251
+ if (last?.role === 'user' && last.toolResults) last.content += `\n\n${text}`;
252
+ else out.push({ role: 'user', content: text, toolResults: true });
253
+ if (m.images?.length) out.push({ role: 'user', content: [{ type: 'text', text: '(Images returned by the tool above.)' }, ...m.images.map((url) => ({ type: 'image_url', image_url: { url } }))] });
254
+ } else out.push(m);
255
+ }
256
+ return out.map(({ toolResults, ...m }) => m);
257
+ }