@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/mcp.js ADDED
@@ -0,0 +1,346 @@
1
+ // Model Context Protocol client. Connects to MCP servers (local processes over
2
+ // stdio, or remote servers over Streamable HTTP) and exposes their tools to the
3
+ // agent as mcp__<server>__<tool>.
4
+ //
5
+ // Config uses the common "mcpServers" shape, read from (later wins):
6
+ // ~/.leto/mcp.json your servers, everywhere
7
+ // <project>/.mcp.json shared project servers (asks before first use)
8
+ // <project>/.leto/mcp.json project servers for leto (asks before first use)
9
+ // {
10
+ // "mcpServers": {
11
+ // "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_TOKEN": "..." } },
12
+ // "docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer ..." } }
13
+ // }
14
+ // }
15
+ import fs from 'node:fs';
16
+ import { pluginMcpFiles } from './plugins.js';
17
+ import { policyDisablesPlugins } from './policy.js';
18
+ import path from 'node:path';
19
+ import { spawn } from 'node:child_process';
20
+ import readline from 'node:readline';
21
+ import { HOME_DIR } from './config.js';
22
+ import { VERSION } from './version.js';
23
+ import { projectDir } from './legacy.js';
24
+
25
+ const PROTOCOL = '2025-06-18';
26
+ const CONNECT_TIMEOUT = 20000;
27
+ const CALL_TIMEOUT = 300000;
28
+
29
+ export function mcpConfigFiles(cwd) {
30
+ return {
31
+ user: [path.join(HOME_DIR, 'mcp.json'), ...(policyDisablesPlugins() ? [] : pluginMcpFiles())],
32
+ project: [path.join(cwd, '.mcp.json'), path.join(projectDir(cwd), 'mcp.json')],
33
+ };
34
+ }
35
+
36
+ function readServers(file) {
37
+ try {
38
+ const json = JSON.parse(fs.readFileSync(file, 'utf8'));
39
+ return json.mcpServers ?? json.servers ?? {};
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ // Returns { servers: {name: {...cfg, source}}, projectFiles: [files that exist] }
46
+ export function loadMcpConfig(cwd, { includeProject = true } = {}) {
47
+ const { user, project } = mcpConfigFiles(cwd);
48
+ const servers = {};
49
+ const projectFiles = [];
50
+ for (const file of user) for (const [name, cfg] of Object.entries(readServers(file) ?? {})) servers[name] = { ...cfg, source: file };
51
+ for (const file of project) {
52
+ const found = readServers(file);
53
+ if (!found) continue;
54
+ projectFiles.push(file);
55
+ if (includeProject) for (const [name, cfg] of Object.entries(found)) servers[name] = { ...cfg, source: file };
56
+ }
57
+ return { servers, projectFiles };
58
+ }
59
+
60
+ // Expand ${VAR} references from the environment in strings.
61
+ const expand = (v) => (typeof v === 'string' ? v.replace(/\$\{(\w+)\}/g, (_, k) => process.env[k] ?? '') : v);
62
+ const expandAll = (obj) => Object.fromEntries(Object.entries(obj ?? {}).map(([k, v]) => [k, expand(v)]));
63
+
64
+ class StdioTransport {
65
+ constructor(cfg, cwd) {
66
+ this.cfg = cfg;
67
+ this.cwd = cwd;
68
+ this.pending = new Map();
69
+ this.nextId = 1;
70
+ this.stderr = '';
71
+ }
72
+
73
+ async start() {
74
+ const { command, args = [], env = {} } = this.cfg;
75
+ this.proc = spawn(expand(command), args.map(expand), {
76
+ cwd: this.cfg.cwd ? path.resolve(this.cwd, this.cfg.cwd) : this.cwd,
77
+ env: { ...process.env, ...expandAll(env) },
78
+ stdio: ['pipe', 'pipe', 'pipe'],
79
+ });
80
+ this.proc.stderr.on('data', (d) => {
81
+ this.stderr = (this.stderr + d).slice(-4000);
82
+ });
83
+ const exited = new Promise((_, reject) => {
84
+ this.proc.on('error', (err) => reject(new Error(`could not start "${command}": ${err.message}`)));
85
+ this.proc.on('exit', (code) => {
86
+ const err = new Error(`server exited (code ${code})${this.stderr ? `: ${this.stderr.trim().split('\n').slice(-3).join(' ')}` : ''}`);
87
+ for (const { reject: r } of this.pending.values()) r(err);
88
+ this.pending.clear();
89
+ this.closed = err;
90
+ reject(err);
91
+ });
92
+ });
93
+ exited.catch(() => {});
94
+ this.exited = exited;
95
+ readline.createInterface({ input: this.proc.stdout }).on('line', (line) => this.onLine(line));
96
+ }
97
+
98
+ onLine(line) {
99
+ let msg;
100
+ try {
101
+ msg = JSON.parse(line);
102
+ } catch {
103
+ return;
104
+ }
105
+ if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
106
+ const p = this.pending.get(msg.id);
107
+ if (!p) return;
108
+ this.pending.delete(msg.id);
109
+ if (msg.error) p.reject(new Error(msg.error.message ?? JSON.stringify(msg.error)));
110
+ else p.resolve(msg.result);
111
+ } else if (msg.id !== undefined && msg.method) {
112
+ // Server-to-client request: answer ping, refuse the rest politely.
113
+ const reply = msg.method === 'ping' ? { jsonrpc: '2.0', id: msg.id, result: {} } : { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: 'Not supported by leto' } };
114
+ this.send(reply);
115
+ }
116
+ }
117
+
118
+ send(obj) {
119
+ if (this.closed) throw this.closed;
120
+ this.proc.stdin.write(JSON.stringify(obj) + '\n');
121
+ }
122
+
123
+ request(method, params, { timeout = CALL_TIMEOUT, signal } = {}) {
124
+ const id = this.nextId++;
125
+ return new Promise((resolve, reject) => {
126
+ const timer = setTimeout(() => {
127
+ this.pending.delete(id);
128
+ reject(new Error(`${method} timed out`));
129
+ }, timeout);
130
+ const done = (fn) => (v) => {
131
+ clearTimeout(timer);
132
+ fn(v);
133
+ };
134
+ this.pending.set(id, { resolve: done(resolve), reject: done(reject) });
135
+ signal?.addEventListener('abort', () => {
136
+ this.pending.delete(id);
137
+ clearTimeout(timer);
138
+ try {
139
+ this.send({ jsonrpc: '2.0', method: 'notifications/cancelled', params: { requestId: id } });
140
+ } catch {}
141
+ reject(new DOMException('Aborted', 'AbortError'));
142
+ }, { once: true });
143
+ try {
144
+ this.send({ jsonrpc: '2.0', id, method, params });
145
+ } catch (err) {
146
+ this.pending.delete(id);
147
+ clearTimeout(timer);
148
+ reject(err);
149
+ }
150
+ });
151
+ }
152
+
153
+ notify(method, params) {
154
+ this.send({ jsonrpc: '2.0', method, params });
155
+ }
156
+
157
+ close() {
158
+ try {
159
+ this.proc?.stdin.end();
160
+ this.proc?.kill();
161
+ } catch {}
162
+ }
163
+ }
164
+
165
+ class HttpTransport {
166
+ constructor(cfg) {
167
+ this.url = expand(cfg.url);
168
+ this.headers = expandAll(cfg.headers);
169
+ this.nextId = 1;
170
+ this.sessionId = null;
171
+ }
172
+
173
+ async start() {}
174
+
175
+ async post(body, signal) {
176
+ const headers = { 'content-type': 'application/json', accept: 'application/json, text/event-stream', ...this.headers };
177
+ if (this.sessionId) headers['mcp-session-id'] = this.sessionId;
178
+ if (this.protocol) headers['mcp-protocol-version'] = this.protocol;
179
+ const res = await fetch(this.url, { method: 'POST', headers, body: JSON.stringify(body), signal });
180
+ const sid = res.headers.get('mcp-session-id');
181
+ if (sid) this.sessionId = sid;
182
+ if (!res.ok && res.status !== 202) {
183
+ const text = await res.text().catch(() => '');
184
+ throw new Error(`HTTP ${res.status}${res.status === 401 ? ' (unauthorized: check the headers in your MCP config)' : ''}: ${text.slice(0, 200)}`);
185
+ }
186
+ return res;
187
+ }
188
+
189
+ async request(method, params, { timeout = CALL_TIMEOUT, signal } = {}) {
190
+ const id = this.nextId++;
191
+ const ac = new AbortController();
192
+ const timer = setTimeout(() => ac.abort(), timeout);
193
+ signal?.addEventListener('abort', () => ac.abort(), { once: true });
194
+ try {
195
+ const res = await this.post({ jsonrpc: '2.0', id, method, params }, ac.signal);
196
+ const type = res.headers.get('content-type') ?? '';
197
+ const messages = [];
198
+ if (type.includes('text/event-stream')) {
199
+ const decoder = new TextDecoder();
200
+ let buf = '';
201
+ outer: for await (const chunk of res.body) {
202
+ buf += decoder.decode(chunk, { stream: true });
203
+ let i;
204
+ while ((i = buf.indexOf('\n\n')) >= 0) {
205
+ const event = buf.slice(0, i);
206
+ buf = buf.slice(i + 2);
207
+ const data = event.split('\n').filter((l) => l.startsWith('data:')).map((l) => l.slice(5).trim()).join('\n');
208
+ if (!data) continue;
209
+ try {
210
+ const msg = JSON.parse(data);
211
+ messages.push(msg);
212
+ if (msg.id === id) break outer;
213
+ } catch {}
214
+ }
215
+ }
216
+ } else {
217
+ const json = await res.json();
218
+ messages.push(...(Array.isArray(json) ? json : [json]));
219
+ }
220
+ const reply = messages.find((m) => m.id === id);
221
+ if (!reply) throw new Error(`no response to ${method}`);
222
+ if (reply.error) throw new Error(reply.error.message ?? JSON.stringify(reply.error));
223
+ return reply.result;
224
+ } catch (err) {
225
+ if (err.name === 'AbortError' && !signal?.aborted) throw new Error(`${method} timed out`);
226
+ throw err;
227
+ } finally {
228
+ clearTimeout(timer);
229
+ }
230
+ }
231
+
232
+ async notify(method, params) {
233
+ await this.post({ jsonrpc: '2.0', method, params }).catch(() => {});
234
+ }
235
+
236
+ close() {
237
+ if (this.sessionId) fetch(this.url, { method: 'DELETE', headers: { 'mcp-session-id': this.sessionId, ...this.headers } }).catch(() => {});
238
+ }
239
+ }
240
+
241
+ export class McpServer {
242
+ constructor(name, cfg, cwd) {
243
+ this.name = name;
244
+ this.cfg = cfg;
245
+ this.cwd = cwd;
246
+ this.status = 'pending';
247
+ this.error = null;
248
+ this.tools = [];
249
+ }
250
+
251
+ async connect() {
252
+ this.transport = this.cfg.url ? new HttpTransport(this.cfg) : new StdioTransport(this.cfg, this.cwd);
253
+ try {
254
+ if (!this.cfg.url && !this.cfg.command) throw new Error('needs "command" (local server) or "url" (remote server)');
255
+ await this.transport.start();
256
+ const init = this.transport.request('initialize', {
257
+ protocolVersion: PROTOCOL,
258
+ capabilities: {},
259
+ clientInfo: { name: 'leto', version: VERSION },
260
+ }, { timeout: CONNECT_TIMEOUT });
261
+ const info = await (this.transport.exited ? Promise.race([init, this.transport.exited]) : init);
262
+ this.transport.protocol = info?.protocolVersion ?? PROTOCOL;
263
+ this.serverInfo = info?.serverInfo;
264
+ this.instructions = info?.instructions;
265
+ await this.transport.notify('notifications/initialized', {});
266
+ const tools = [];
267
+ let cursor;
268
+ do {
269
+ const page = await this.transport.request('tools/list', cursor ? { cursor } : {}, { timeout: CONNECT_TIMEOUT });
270
+ tools.push(...(page?.tools ?? []));
271
+ cursor = page?.nextCursor;
272
+ } while (cursor);
273
+ this.tools = tools;
274
+ this.status = 'connected';
275
+ } catch (err) {
276
+ this.status = 'failed';
277
+ this.error = err.message;
278
+ this.transport.close();
279
+ }
280
+ return this;
281
+ }
282
+
283
+ async callTool(name, args, signal) {
284
+ const result = await this.transport.request('tools/call', { name, arguments: args ?? {} }, { signal });
285
+ const parts = [];
286
+ for (const c of result?.content ?? []) {
287
+ if (c.type === 'text') parts.push(c.text);
288
+ else if (c.type === 'image') parts.push(`[image ${c.mimeType ?? ''} omitted]`);
289
+ else if (c.type === 'resource') parts.push(c.resource?.text ?? `[resource ${c.resource?.uri ?? ''}]`);
290
+ else if (c.type === 'resource_link') parts.push(`[resource ${c.uri}]`);
291
+ else parts.push(JSON.stringify(c));
292
+ }
293
+ if (!parts.length && result?.structuredContent) parts.push(JSON.stringify(result.structuredContent, null, 2));
294
+ return { text: parts.join('\n') || '(no output)', isError: Boolean(result?.isError) };
295
+ }
296
+
297
+ close() {
298
+ this.transport?.close();
299
+ }
300
+ }
301
+
302
+ const toolId = (server, tool) => `mcp__${server}__${tool}`.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
303
+
304
+ // Turn connected servers' tools into leto tool definitions.
305
+ export function mcpTools(servers) {
306
+ const out = [];
307
+ for (const server of servers) {
308
+ if (server.status !== 'connected') continue;
309
+ for (const t of server.tools) {
310
+ const readOnly = t.annotations?.readOnlyHint === true;
311
+ out.push({
312
+ name: toolId(server.name, t.name),
313
+ label: `${server.name}:${t.name}`,
314
+ description: `[MCP server "${server.name}"] ${t.description ?? t.title ?? t.name}`.slice(0, 1024),
315
+ parameters: t.inputSchema && typeof t.inputSchema === 'object' ? { type: 'object', properties: {}, ...t.inputSchema } : { type: 'object', properties: {} },
316
+ needsPermission: !readOnly,
317
+ writes: !readOnly,
318
+ mcp: true,
319
+ summary: (a) => {
320
+ const s = JSON.stringify(a ?? {});
321
+ return s === '{}' ? '' : s.length > 80 ? s.slice(0, 80) + '…' : s;
322
+ },
323
+ preview: (a) => ({
324
+ title: `${server.name} → ${t.name}`,
325
+ lines: JSON.stringify(a ?? {}, null, 2).split('\n').slice(0, 12).map((text) => ({ sign: ' ', text })),
326
+ }),
327
+ async run(a, ctx) {
328
+ const { text, isError } = await server.callTool(t.name, a, ctx.signal);
329
+ if (isError) throw new Error(text);
330
+ return text;
331
+ },
332
+ });
333
+ }
334
+ }
335
+ return out;
336
+ }
337
+
338
+ export async function connectAll(cwd, { includeProject }) {
339
+ const { servers } = loadMcpConfig(cwd, { includeProject });
340
+ const list = Object.entries(servers)
341
+ .filter(([, cfg]) => cfg.disabled !== true)
342
+ .map(([name, cfg]) => new McpServer(name, cfg, cwd));
343
+ await Promise.all(list.map((s) => s.connect()));
344
+ process.once('exit', () => list.forEach((s) => s.close()));
345
+ return list;
346
+ }
package/src/memory.js ADDED
@@ -0,0 +1,136 @@
1
+ // Memory across sessions.
2
+ //
3
+ // - Learned notes: short facts leto saves about a project as it works
4
+ // (build quirks, conventions, gotchas), kept privately in
5
+ // ~/.leto/memory/<project>.md (never in the repository) and given to the
6
+ // model at the start of every session there.
7
+ // - Session search: find things from earlier sessions (what was decided, how
8
+ // something was fixed) in their saved transcripts.
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+ import { HOME_DIR, SESSIONS_DIR } from './config.js';
13
+ import { listSessions } from './session.js';
14
+
15
+ export const MEMORY_DIR = path.join(HOME_DIR, 'memory');
16
+ const MAX_NOTES = 200;
17
+
18
+ export function memoryFile(cwd) {
19
+ const key = crypto.createHash('sha1').update(path.resolve(cwd)).digest('hex').slice(0, 10);
20
+ return path.join(MEMORY_DIR, `${path.basename(path.resolve(cwd)).replace(/[^\w.-]+/g, '-')}-${key}.md`);
21
+ }
22
+
23
+ export function readNotes(cwd) {
24
+ try {
25
+ return fs.readFileSync(memoryFile(cwd), 'utf8').split('\n').filter((l) => l.startsWith('- ')).map((l) => l.slice(2));
26
+ } catch {
27
+ return [];
28
+ }
29
+ }
30
+
31
+ function writeNotes(cwd, notes) {
32
+ fs.mkdirSync(MEMORY_DIR, { recursive: true });
33
+ fs.writeFileSync(memoryFile(cwd), `# What leto learned about ${path.resolve(cwd)}\n\n${notes.map((n) => `- ${n}`).join('\n')}\n`, { mode: 0o600 });
34
+ }
35
+
36
+ export function addNote(cwd, note) {
37
+ const clean = String(note).replace(/\s+/g, ' ').trim().slice(0, 400);
38
+ if (!clean) throw new Error('note is empty');
39
+ const notes = readNotes(cwd);
40
+ if (notes.some((n) => n.toLowerCase() === clean.toLowerCase())) return { notes, added: false };
41
+ notes.push(clean);
42
+ writeNotes(cwd, notes.slice(-MAX_NOTES));
43
+ return { notes, added: true };
44
+ }
45
+
46
+ export function removeNote(cwd, match) {
47
+ const notes = readNotes(cwd);
48
+ const needle = String(match).toLowerCase();
49
+ const kept = notes.filter((n) => !n.toLowerCase().includes(needle));
50
+ if (kept.length === notes.length) throw new Error(`No note matches "${match}".`);
51
+ writeNotes(cwd, kept);
52
+ return notes.length - kept.length;
53
+ }
54
+
55
+ const textOf = (c) => (Array.isArray(c) ? c.filter((p) => p.type === 'text').map((p) => p.text).join('\n') : String(c ?? ''));
56
+
57
+ // Search saved sessions. Returns [{ id, title, updated, cwd, hits: [{ role, text }] }].
58
+ export function searchSessions(query, { cwd = null, limit = 8, exclude = null } = {}) {
59
+ const terms = String(query).toLowerCase().split(/\s+/).filter(Boolean);
60
+ if (!terms.length) return [];
61
+ const out = [];
62
+ for (const s of listSessions()) {
63
+ if (s.id === exclude || (cwd && s.cwd !== cwd)) continue;
64
+ let raw;
65
+ try {
66
+ raw = fs.readFileSync(path.join(SESSIONS_DIR, `${s.id}.jsonl`), 'utf8');
67
+ } catch {
68
+ continue;
69
+ }
70
+ if (!terms.every((t) => raw.toLowerCase().includes(t))) continue;
71
+ const hits = [];
72
+ for (const line of raw.split('\n')) {
73
+ if (!line.includes('"message"')) continue;
74
+ let e;
75
+ try {
76
+ e = JSON.parse(line);
77
+ } catch {
78
+ continue;
79
+ }
80
+ if (e.type !== 'message' || !['user', 'assistant'].includes(e.message.role)) continue;
81
+ const text = textOf(e.message.content);
82
+ const low = text.toLowerCase();
83
+ const at = terms.map((t) => low.indexOf(t)).filter((i) => i >= 0);
84
+ if (!at.length) continue;
85
+ const i = Math.max(0, Math.min(...at) - 160);
86
+ hits.push({ role: e.message.role, text: `${i ? '…' : ''}${text.slice(i, i + 480).replace(/\s+/g, ' ')}${text.length > i + 480 ? '…' : ''}`, score: at.length });
87
+ }
88
+ if (!hits.length) continue;
89
+ hits.sort((a, b) => b.score - a.score);
90
+ out.push({ id: s.id, title: s.title, updated: s.updated, cwd: s.cwd, hits: hits.slice(0, 3) });
91
+ if (out.length >= limit) break;
92
+ }
93
+ return out;
94
+ }
95
+
96
+ export const memoryTool = {
97
+ name: 'memory',
98
+ description:
99
+ 'Your memory across sessions in this project. add: save a short, durable fact you learned that will help in future sessions (a build or test quirk, a convention, where something lives, a decision the user made); it is kept privately for this project and given to you at the start of every session. Save facts as you learn them, without asking; don\'t save what is obvious from the code, what LETO.md already says, or anything secret. remove: forget notes containing some text (when one is wrong or out of date). list: show the notes. search: look through earlier sessions\' conversations for a topic (what was decided, how something was fixed).',
100
+ parameters: {
101
+ type: 'object',
102
+ properties: {
103
+ action: { type: 'string', enum: ['add', 'remove', 'list', 'search'] },
104
+ note: { type: 'string', description: 'add: the fact, in one sentence. remove: text that the notes to forget contain' },
105
+ query: { type: 'string', description: 'search: words to look for' },
106
+ all_projects: { type: 'boolean', description: 'search: include sessions from other folders' },
107
+ },
108
+ required: ['action'],
109
+ },
110
+ summary: (a) => `${a.action}${a.note ? `: ${a.note}` : ''}${a.query ? `: ${a.query}` : ''}`,
111
+ run(a, ctx) {
112
+ const cwd = ctx.cwd;
113
+ if (a.action === 'add') {
114
+ if (!a.note) throw new Error('note is required');
115
+ const { added, notes } = addNote(cwd, a.note);
116
+ return { content: added ? `Saved. ${notes.length} note${notes.length === 1 ? '' : 's'} for this project.` : 'Already saved.', display: added ? `remembered · ${a.note.slice(0, 80)}` : 'already known' };
117
+ }
118
+ if (a.action === 'remove') {
119
+ if (!a.note) throw new Error('note is required');
120
+ const n = removeNote(cwd, a.note);
121
+ return `Forgot ${n} note${n === 1 ? '' : 's'}.`;
122
+ }
123
+ if (a.action === 'list') {
124
+ const notes = readNotes(cwd);
125
+ return notes.length ? notes.map((n) => `- ${n}`).join('\n') : 'No notes yet for this project.';
126
+ }
127
+ if (a.action === 'search') {
128
+ if (!a.query) throw new Error('query is required');
129
+ const found = searchSessions(a.query, { cwd: a.all_projects ? null : cwd, exclude: ctx.sessionId });
130
+ if (!found.length) return { content: `No earlier session${a.all_projects ? '' : ' in this folder'} mentions "${a.query}".`, display: 'no matches' };
131
+ const text = found.map((s) => `## ${s.title || '(untitled)'} · ${new Date(s.updated).toISOString().slice(0, 10)} · session ${s.id}${a.all_projects ? ` · ${s.cwd}` : ''}\n${s.hits.map((h) => `[${h.role}] ${h.text}`).join('\n')}`).join('\n\n');
132
+ return { content: text, display: `${found.length} session${found.length === 1 ? '' : 's'}` };
133
+ }
134
+ throw new Error(`Unknown action "${a.action}".`);
135
+ },
136
+ };
@@ -0,0 +1,141 @@
1
+ // Orchestrator mode: one top model is the brain; it plans, splits the work,
2
+ // hands each piece to the team member best suited for it (any model, from
3
+ // any provider you've set up), checks what comes back, and puts it together.
4
+ //
5
+ // Saved in ~/.leto/config.json:
6
+ // "orchestrator": {
7
+ // "enabled": true,
8
+ // "brain": { "provider": "anthropic", "model": "claude-fable-5-2" },
9
+ // "team": [
10
+ // { "name": "coder", "provider": "anthropic", "model": "claude-opus-5-5", "strengths": "…" },
11
+ // { "name": "scout", "provider": "anthropic", "model": "claude-haiku-5-5", "strengths": "…" }
12
+ // ]
13
+ // }
14
+ // Each provider uses the API key saved for it (leto setup).
15
+ import { loadConfig, readConfigFile, writeConfig } from './config.js';
16
+ import { getProvider } from './providers.js';
17
+ import { priceFor } from './pricing.js';
18
+ import { checkModel } from './policy.js';
19
+
20
+ // What well-known model families are good at. Used as defaults; you can
21
+ // rewrite any member's strengths in /orchestrate.
22
+ const STRENGTHS = [
23
+ [/claude-(fable|mythos)/, 'Top reasoning and judgment: planning, architecture, ambiguous or high-stakes problems, reviewing others\' work'],
24
+ [/claude-opus/, 'Hard coding: complex multi-file features and refactors, subtle bugs, deep debugging, careful long tasks'],
25
+ [/claude-sonnet/, 'Strong, fast everyday coding: features, tests, edits across files, good value for most implementation work'],
26
+ [/claude-haiku/, 'Very fast and cheap: searching and reading code, summarizing, simple edits, boilerplate, quick checks'],
27
+ [/gpt-5(\.\d)?-codex|codex/, 'Code generation and edits, strong on well-specified programming tasks'],
28
+ [/(^|\/)o[1-9](-|$)|gpt-.*(thinking|reasoning)/, 'Deliberate reasoning: math, algorithms, tricky logic'],
29
+ [/gpt-[\d.]+-(mini|nano)/, 'Fast and cheap general model: simple tasks, summaries, classification'],
30
+ [/gpt-/, 'Broad general knowledge and coding'],
31
+ [/gemini-.*flash/, 'Fast and cheap with a very long context: skimming large files and logs'],
32
+ [/gemini/, 'Very long context and multimodal: reading whole codebases, big documents, images'],
33
+ [/grok/, 'General coding and reasoning, up-to-date knowledge'],
34
+ [/deepseek.*(r1|reason)/, 'Low-cost step-by-step reasoning'],
35
+ [/deepseek/, 'Low-cost capable coding'],
36
+ [/qwen.*coder|codestral|devstral/, 'Low-cost code generation and edits'],
37
+ [/mistral|mixtral/, 'Low-cost general tasks'],
38
+ [/llama/, 'Open model: low-cost general tasks'],
39
+ [/mumbrane/, "Mumbrane's own model"],
40
+ ];
41
+
42
+ export function strengthsFor(model) {
43
+ return STRENGTHS.find(([re]) => re.test(String(model).toLowerCase()))?.[1] ?? 'General-purpose model';
44
+ }
45
+
46
+ export function loadOrchestrator() {
47
+ const o = readConfigFile().orchestrator ?? {};
48
+ return { enabled: Boolean(o.enabled), brain: o.brain ?? null, team: Array.isArray(o.team) ? o.team : [] };
49
+ }
50
+
51
+ export function saveOrchestrator(next) {
52
+ writeConfig((file) => {
53
+ file.orchestrator = { enabled: Boolean(next.enabled), brain: next.brain ?? null, team: next.team ?? [] };
54
+ });
55
+ }
56
+
57
+ const slug = (s) => String(s).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'worker';
58
+
59
+ export function memberName(model, taken) {
60
+ const m = String(model).toLowerCase();
61
+ const base = /fable|mythos/.test(m) ? 'strategist' : /opus/.test(m) ? 'architect' : /sonnet/.test(m) ? 'coder' : /haiku|mini|nano|flash/.test(m) ? 'scout' : /gemini/.test(m) ? 'reader' : /codex|coder|codestral|devstral/.test(m) ? 'builder' : /o[1-9]|reason|r1/.test(m) ? 'thinker' : slug(m.split('/').pop());
62
+ let name = base;
63
+ for (let i = 2; taken.has(name); i++) name = `${base}-${i}`;
64
+ return name;
65
+ }
66
+
67
+ // The config a worker runs with: its provider's saved key and URL, its model.
68
+ export function workerConfig(member, base) {
69
+ checkModel(member.model);
70
+ const cfg = loadConfig({ provider: member.provider || base.provider });
71
+ cfg.model = member.model;
72
+ cfg.contextWindow = member.contextWindow || cfg.contextWindow;
73
+ cfg.subagentModel = '';
74
+ cfg.checkCommand = base.checkCommand;
75
+ if (!cfg.configured) throw new Error(`Worker "${member.name}" uses ${getProvider(member.provider)?.name ?? member.provider}, which has no API key set up. Run leto setup for it, or change the team in /orchestrate.`);
76
+ return cfg;
77
+ }
78
+
79
+ const price = (model) => {
80
+ const p = priceFor(model);
81
+ return p ? `$${p[0]}/$${p[1]} per M tokens in/out` : '';
82
+ };
83
+
84
+ export function rosterText(team) {
85
+ return team.map((m) => `- ${m.name}: ${m.model}${m.provider ? ` (${getProvider(m.provider)?.name ?? m.provider})` : ''}. ${m.strengths || strengthsFor(m.model)}${price(m.model) ? `. Cost: ${price(m.model)}` : ''}`).join('\n');
86
+ }
87
+
88
+ export function orchestratorPrompt(o) {
89
+ return `# Orchestrator mode
90
+ You are the brain of a team of models. Your job is to get the best possible result by planning the work and delegating it to the team member best suited to each piece, then checking and integrating what they return. Your own context and attention are the scarcest resource: spend them on judgment, not on routine reading and typing.
91
+
92
+ Team (use the name as the task tool's worker):
93
+ ${rosterText(o.team)}
94
+
95
+ How to work:
96
+ - Start by understanding the goal and making a plan (todo_write). Split it into self-contained jobs with clear inputs and a clear definition of done.
97
+ - Delegate with the task tool: set worker to the team member whose strengths fit the job, agent_type "explore" for read-only research and "general" for changes. Put everything the worker needs in the prompt (they can't see this conversation): goal, relevant files, constraints, and exactly what to report back.
98
+ - Match the job to the model: cheap, fast members for searching, reading and simple edits; strong coders for real implementation; your strongest members for hard bugs and design. Don't send easy work to expensive models or hard work to weak ones.
99
+ - Run independent jobs in parallel (several task calls in one reply). For parallel edits in a git repository, use isolation "worktree" so workers don't collide, then merge the branches.
100
+ - For important or uncertain work, get a second opinion: give the same job to two different members and compare, or have one member review another's change.
101
+ - Verify, don't trust: read the reports critically, check the key changes yourself (diffs, tests), and send fixes back to a worker when something is wrong.
102
+ - Do small things yourself when delegating would take longer than doing them.
103
+ - At the end, tell the user what was done, by whom, and anything left unverified.`;
104
+ }
105
+
106
+ // A good starting team from the providers you have keys for.
107
+ export async function suggestTeam(listFor) {
108
+ const file = readConfigFile();
109
+ const providers = Object.entries(file.providers ?? {}).filter(([id, p]) => p.apiKey || getProvider(id)?.noKey || p.baseUrl).map(([id]) => id);
110
+ const team = [];
111
+ let brain = null;
112
+ const taken = new Set();
113
+ const pick = (models, re) => models.find((m) => re.test(m.id));
114
+ for (const id of providers) {
115
+ let models = [];
116
+ try {
117
+ models = await listFor(id);
118
+ } catch {
119
+ continue;
120
+ }
121
+ if (!models.length) continue;
122
+ const add = (m) => {
123
+ if (!m || team.some((t) => t.model === m.id)) return;
124
+ const name = memberName(m.id, taken);
125
+ taken.add(name);
126
+ team.push({ name, provider: id, model: m.id, strengths: strengthsFor(m.id), ...(m.contextWindow ? { contextWindow: m.contextWindow } : {}) });
127
+ };
128
+ if (id === 'anthropic') {
129
+ const fable = pick(models, /claude-(fable|mythos)/);
130
+ if (fable && !brain) brain = { provider: id, model: fable.id };
131
+ add(pick(models, /claude-opus/));
132
+ add(pick(models, /claude-sonnet/));
133
+ add(pick(models, /claude-haiku/));
134
+ } else {
135
+ // The newest few models of other providers.
136
+ models.slice(0, 2).forEach(add);
137
+ }
138
+ }
139
+ if (!brain && team.length) brain = { provider: team[0].provider, model: team[0].model };
140
+ return { brain, team };
141
+ }