@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/tools.js
ADDED
|
@@ -0,0 +1,976 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
4
|
+
import { browserTool } from './browser.js';
|
|
5
|
+
import { syntaxCheck } from './verify.js';
|
|
6
|
+
import { sandboxAvailable, sandboxCommand, looksBlocked } from './sandbox.js';
|
|
7
|
+
import { repairJson } from './toolcalls.js';
|
|
8
|
+
import { repoMapTool } from './repomap.js';
|
|
9
|
+
import { readPdf, readNotebook, editNotebook } from './documents.js';
|
|
10
|
+
import { selfTool } from './selftool.js';
|
|
11
|
+
import { lspTool, diagnosticsAfterEdit } from './lsp.js';
|
|
12
|
+
import { memoryTool } from './memory.js';
|
|
13
|
+
import { applyEdit, planPatch, writePlan, parsePatch } from './patching.js';
|
|
14
|
+
import { startProcess, readProcess, stopProcess, listProcesses, withState, readState, stateFileFor } from './processes.js';
|
|
15
|
+
|
|
16
|
+
const MAX_OUTPUT = 30000;
|
|
17
|
+
const IMAGE_MIME = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
|
|
18
|
+
const SKIP_DIRS = new Set(['.git', 'node_modules', '.hg', '.svn', '__pycache__', '.venv', 'venv', '.DS_Store']);
|
|
19
|
+
|
|
20
|
+
export function truncate(text, max = MAX_OUTPUT) {
|
|
21
|
+
if (text.length <= max) return text;
|
|
22
|
+
const half = Math.floor(max / 2);
|
|
23
|
+
return `${text.slice(0, half)}\n\n… [${text.length - max} characters truncated] …\n\n${text.slice(-half)}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function resolvePath(ctx, p) {
|
|
27
|
+
if (!p || typeof p !== 'string') throw new Error('path is required');
|
|
28
|
+
if (p.startsWith('~/')) p = path.join(process.env.HOME || '', p.slice(2));
|
|
29
|
+
return path.resolve(ctx.cwd, p);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function rel(ctx, p) {
|
|
33
|
+
const r = path.relative(ctx.cwd, p);
|
|
34
|
+
return r && !r.startsWith('..') ? r : p;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function* walk(dir) {
|
|
38
|
+
let entries;
|
|
39
|
+
try {
|
|
40
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
41
|
+
} catch {
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
45
|
+
for (const e of entries) {
|
|
46
|
+
if (SKIP_DIRS.has(e.name)) continue;
|
|
47
|
+
const full = path.join(dir, e.name);
|
|
48
|
+
if (e.isDirectory()) yield* walk(full);
|
|
49
|
+
else if (e.isFile()) yield full;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function globToRegExp(glob) {
|
|
54
|
+
if (!glob.includes('/')) glob = `**/${glob}`;
|
|
55
|
+
let re = '';
|
|
56
|
+
let braces = 0;
|
|
57
|
+
for (let i = 0; i < glob.length; i++) {
|
|
58
|
+
const ch = glob[i];
|
|
59
|
+
if (ch === '*') {
|
|
60
|
+
if (glob[i + 1] === '*') {
|
|
61
|
+
if (glob[i + 2] === '/') {
|
|
62
|
+
re += '(?:.*/)?';
|
|
63
|
+
i += 2;
|
|
64
|
+
} else {
|
|
65
|
+
re += '.*';
|
|
66
|
+
i += 1;
|
|
67
|
+
}
|
|
68
|
+
} else re += '[^/]*';
|
|
69
|
+
} else if (ch === '?') re += '[^/]';
|
|
70
|
+
else if (ch === '{') { braces++; re += '(?:'; }
|
|
71
|
+
else if (ch === '}' && braces) { braces--; re += ')'; }
|
|
72
|
+
else if (ch === ',' && braces) re += '|';
|
|
73
|
+
else re += ch.replace(/[.+^$()|[\]\\]/g, '\\$&');
|
|
74
|
+
}
|
|
75
|
+
return new RegExp(`^${re}$`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function isBinary(buf) {
|
|
79
|
+
const n = Math.min(buf.length, 8000);
|
|
80
|
+
for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
|
|
81
|
+
return false;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
let rgAvailable;
|
|
85
|
+
function hasRipgrep() {
|
|
86
|
+
if (rgAvailable === undefined) {
|
|
87
|
+
const r = spawnSync('rg', ['--version'], { stdio: 'ignore' });
|
|
88
|
+
rgAvailable = r.status === 0;
|
|
89
|
+
}
|
|
90
|
+
return rgAvailable;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function runProcess(cmd, args, { cwd, signal, timeoutMs, shell = false, onOutput, env }) {
|
|
94
|
+
return new Promise((resolve) => {
|
|
95
|
+
const child = spawn(cmd, args, { cwd, shell, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: env ?? { ...process.env, LETO: '1' } });
|
|
96
|
+
let out = '';
|
|
97
|
+
let size = 0;
|
|
98
|
+
let timedOut = false;
|
|
99
|
+
let aborted = false;
|
|
100
|
+
let tail = '';
|
|
101
|
+
const add = (d) => {
|
|
102
|
+
size += d.length;
|
|
103
|
+
if (size < 2_000_000) out += d.toString();
|
|
104
|
+
if (onOutput) {
|
|
105
|
+
tail = (tail + d.toString()).slice(-2000);
|
|
106
|
+
const last = tail.split('\n').map((l) => l.trim()).filter(Boolean).pop();
|
|
107
|
+
if (last) onOutput(last);
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
child.stdout.on('data', add);
|
|
111
|
+
child.stderr.on('data', add);
|
|
112
|
+
const kill = () => {
|
|
113
|
+
try {
|
|
114
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
115
|
+
} catch {
|
|
116
|
+
child.kill('SIGKILL');
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const timer = timeoutMs ? setTimeout(() => { timedOut = true; kill(); }, timeoutMs) : null;
|
|
120
|
+
const onAbort = () => { aborted = true; kill(); };
|
|
121
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
122
|
+
child.on('error', (err) => {
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
signal?.removeEventListener('abort', onAbort);
|
|
125
|
+
resolve({ out: '', code: -1, error: err });
|
|
126
|
+
});
|
|
127
|
+
child.on('close', (code) => {
|
|
128
|
+
clearTimeout(timer);
|
|
129
|
+
signal?.removeEventListener('abort', onAbort);
|
|
130
|
+
resolve({ out, code, timedOut, aborted });
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function diffPreview(oldStr, newStr, maxLines = 24) {
|
|
136
|
+
const lines = [];
|
|
137
|
+
for (const l of oldStr.split('\n')) lines.push({ sign: '-', text: l });
|
|
138
|
+
for (const l of newStr.split('\n')) lines.push({ sign: '+', text: l });
|
|
139
|
+
const shown = lines.slice(0, maxLines);
|
|
140
|
+
if (lines.length > maxLines) shown.push({ sign: ' ', text: `… ${lines.length - maxLines} more lines` });
|
|
141
|
+
return shown;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const TOOLS = [
|
|
145
|
+
{
|
|
146
|
+
name: 'read_file',
|
|
147
|
+
description: 'Read a file. Text comes back with line numbers (use offset/limit for large files); images (png, jpg, gif, webp) come back as the image itself so you can look at them; PDFs come back as text (use pages for long ones); Jupyter notebooks (.ipynb) come back as numbered cells with their outputs. Reading a directory lists its entries.',
|
|
148
|
+
parameters: {
|
|
149
|
+
type: 'object',
|
|
150
|
+
properties: {
|
|
151
|
+
path: { type: 'string', description: 'File path, absolute or relative to the working directory' },
|
|
152
|
+
offset: { type: 'integer', description: '1-based line to start from (default 1)' },
|
|
153
|
+
limit: { type: 'integer', description: 'Max lines to return (default 2000)' },
|
|
154
|
+
pages: { type: 'string', description: 'PDF only: page range like "3" or "10-20"' },
|
|
155
|
+
},
|
|
156
|
+
required: ['path'],
|
|
157
|
+
},
|
|
158
|
+
summary: (a) => a.path,
|
|
159
|
+
run(a, ctx) {
|
|
160
|
+
const p = resolvePath(ctx, a.path);
|
|
161
|
+
const stat = fs.statSync(p);
|
|
162
|
+
if (stat.isDirectory()) {
|
|
163
|
+
const entries = fs.readdirSync(p, { withFileTypes: true }).map((e) => (e.isDirectory() ? `${e.name}/` : e.name));
|
|
164
|
+
return entries.sort().join('\n') || '(empty directory)';
|
|
165
|
+
}
|
|
166
|
+
const mime = IMAGE_MIME[path.extname(p).toLowerCase()];
|
|
167
|
+
if (mime) {
|
|
168
|
+
if (stat.size > 5 * 1024 * 1024) return `${rel(ctx, p)} is an image larger than 5 MB; it can't be shown.`;
|
|
169
|
+
const kb = Math.round(stat.size / 1024);
|
|
170
|
+
return { content: `Image ${rel(ctx, p)} (${kb} KB). It is attached so you can look at it.`, display: `image · ${kb} KB`, images: [`data:${mime};base64,${fs.readFileSync(p).toString('base64')}`] };
|
|
171
|
+
}
|
|
172
|
+
const ext = path.extname(p).toLowerCase();
|
|
173
|
+
if (ext === '.pdf') return readPdf(p, { pages: a.pages, native: ctx.agent?.config?.provider === 'anthropic' && process.env.LETO_ANTHROPIC_COMPAT !== '1' });
|
|
174
|
+
if (ext === '.ipynb') return readNotebook(p);
|
|
175
|
+
const buf = fs.readFileSync(p);
|
|
176
|
+
if (isBinary(buf)) return `${rel(ctx, p)} is a binary file (${stat.size} bytes).`;
|
|
177
|
+
const lines = buf.toString('utf8').split('\n');
|
|
178
|
+
const offset = Math.max(1, a.offset || 1);
|
|
179
|
+
const limit = Math.max(1, a.limit || 2000);
|
|
180
|
+
const slice = lines.slice(offset - 1, offset - 1 + limit);
|
|
181
|
+
const body = slice.map((l, i) => `${offset + i}\t${l.length > 2000 ? l.slice(0, 2000) + '…' : l}`).join('\n');
|
|
182
|
+
const more = offset - 1 + limit < lines.length ? `\n… (${lines.length - (offset - 1 + limit)} more lines; use offset to read further)` : '';
|
|
183
|
+
return (body || '(empty file)') + more;
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
name: 'write_file',
|
|
188
|
+
writes: true,
|
|
189
|
+
description: 'Create a new file or completely overwrite an existing one. Prefer edit_file for changes to existing files.',
|
|
190
|
+
parameters: {
|
|
191
|
+
type: 'object',
|
|
192
|
+
properties: {
|
|
193
|
+
path: { type: 'string', description: 'File path' },
|
|
194
|
+
content: { type: 'string', description: 'Full file content' },
|
|
195
|
+
},
|
|
196
|
+
required: ['path', 'content'],
|
|
197
|
+
},
|
|
198
|
+
needsPermission: true,
|
|
199
|
+
summary: (a) => a.path,
|
|
200
|
+
preview(a, ctx) {
|
|
201
|
+
const p = resolvePath(ctx, a.path);
|
|
202
|
+
const exists = fs.existsSync(p);
|
|
203
|
+
const lines = String(a.content ?? '').split('\n');
|
|
204
|
+
return {
|
|
205
|
+
title: `${exists ? 'Overwrite' : 'Create'} ${rel(ctx, p)} (${lines.length} lines)`,
|
|
206
|
+
lines: lines.slice(0, 16).map((text) => ({ sign: '+', text })).concat(lines.length > 16 ? [{ sign: ' ', text: `… ${lines.length - 16} more lines` }] : []),
|
|
207
|
+
};
|
|
208
|
+
},
|
|
209
|
+
run(a, ctx) {
|
|
210
|
+
const p = resolvePath(ctx, a.path);
|
|
211
|
+
fs.mkdirSync(path.dirname(p), { recursive: true });
|
|
212
|
+
const content = String(a.content ?? '');
|
|
213
|
+
ctx.checkpoints?.record(p);
|
|
214
|
+
fs.writeFileSync(p, content);
|
|
215
|
+
const all = content.split('\n');
|
|
216
|
+
const msg = `Wrote ${all.length} lines to ${rel(ctx, p)}`;
|
|
217
|
+
const lines = all.slice(0, 8).map((text, i) => ({ sign: '+', text, n: i + 1 }));
|
|
218
|
+
if (all.length > 8) lines.push({ sign: ' ', text: `… ${all.length - 8} more lines` });
|
|
219
|
+
return { content: msg, display: msg, lines, file: p };
|
|
220
|
+
},
|
|
221
|
+
},
|
|
222
|
+
{
|
|
223
|
+
name: 'edit_file',
|
|
224
|
+
writes: true,
|
|
225
|
+
description: 'Replace exact text in a file. old_string must match the file exactly (including whitespace) and be unique unless replace_all is true. Read the file first.',
|
|
226
|
+
parameters: {
|
|
227
|
+
type: 'object',
|
|
228
|
+
properties: {
|
|
229
|
+
path: { type: 'string', description: 'File path' },
|
|
230
|
+
old_string: { type: 'string', description: 'Exact text to replace' },
|
|
231
|
+
new_string: { type: 'string', description: 'Replacement text' },
|
|
232
|
+
replace_all: { type: 'boolean', description: 'Replace every occurrence (default false)' },
|
|
233
|
+
},
|
|
234
|
+
required: ['path', 'old_string', 'new_string'],
|
|
235
|
+
},
|
|
236
|
+
needsPermission: true,
|
|
237
|
+
summary: (a) => a.path,
|
|
238
|
+
preview(a, ctx) {
|
|
239
|
+
return { title: `Edit ${rel(ctx, resolvePath(ctx, a.path))}`, lines: diffPreview(String(a.old_string ?? ''), String(a.new_string ?? '')) };
|
|
240
|
+
},
|
|
241
|
+
validate(a, ctx) {
|
|
242
|
+
const p = resolvePath(ctx, a.path);
|
|
243
|
+
if (!fs.existsSync(p)) throw new Error(`${a.path} does not exist. Use write_file to create it.`);
|
|
244
|
+
if (!a.old_string) throw new Error('old_string must not be empty. Use write_file to create or overwrite a file.');
|
|
245
|
+
if (a.old_string === a.new_string) throw new Error('old_string and new_string are identical.');
|
|
246
|
+
const text = fs.readFileSync(p, 'utf8');
|
|
247
|
+
const r = applyEdit(text, a);
|
|
248
|
+
return { p, text, count: r.count, updated: r.text, fuzzy: r.fuzzy, index: r.index };
|
|
249
|
+
},
|
|
250
|
+
run(a, ctx) {
|
|
251
|
+
const { p, text, count, updated, fuzzy, index } = this.validate(a, ctx);
|
|
252
|
+
ctx.checkpoints?.record(p);
|
|
253
|
+
fs.writeFileSync(p, updated);
|
|
254
|
+
const startLine = text.slice(0, index).split('\n').length;
|
|
255
|
+
const oldLines = a.old_string.split('\n');
|
|
256
|
+
const newLines = a.new_string.split('\n');
|
|
257
|
+
const lines = [
|
|
258
|
+
...oldLines.slice(0, 12).map((t, i) => ({ sign: '-', text: t, n: startLine + i })),
|
|
259
|
+
...newLines.slice(0, 12).map((t, i) => ({ sign: '+', text: t, n: startLine + i })),
|
|
260
|
+
];
|
|
261
|
+
return {
|
|
262
|
+
content: `Edited ${rel(ctx, p)} (${a.replace_all ? count : 1} replacement${count > 1 && a.replace_all ? 's' : ''})${fuzzy ? '. old_string matched after normalizing whitespace/indentation; new_string was re-indented to fit. Check the result if indentation matters.' : ''}`,
|
|
263
|
+
display: `Updated ${rel(ctx, p)} with ${newLines.length} addition${newLines.length === 1 ? '' : 's'} and ${oldLines.length} removal${oldLines.length === 1 ? '' : 's'}${a.replace_all && count > 1 ? ` (${count} places)` : ''}`,
|
|
264
|
+
lines,
|
|
265
|
+
file: p,
|
|
266
|
+
};
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
{
|
|
270
|
+
name: 'multi_edit',
|
|
271
|
+
writes: true,
|
|
272
|
+
description: 'Make several edits to one file in one step. Edits apply in order, each to the result of the previous one, and all must succeed or none are written. Each old_string must match exactly and be unique unless replace_all is set. Prefer this over repeated edit_file calls on the same file.',
|
|
273
|
+
parameters: {
|
|
274
|
+
type: 'object',
|
|
275
|
+
properties: {
|
|
276
|
+
path: { type: 'string', description: 'File path' },
|
|
277
|
+
edits: {
|
|
278
|
+
type: 'array',
|
|
279
|
+
items: {
|
|
280
|
+
type: 'object',
|
|
281
|
+
properties: { old_string: { type: 'string' }, new_string: { type: 'string' }, replace_all: { type: 'boolean' } },
|
|
282
|
+
required: ['old_string', 'new_string'],
|
|
283
|
+
},
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
required: ['path', 'edits'],
|
|
287
|
+
},
|
|
288
|
+
needsPermission: true,
|
|
289
|
+
summary: (a) => `${a.path} (${Array.isArray(a.edits) ? a.edits.length : 0} edits)`,
|
|
290
|
+
plan(a, ctx) {
|
|
291
|
+
const p = resolvePath(ctx, a.path);
|
|
292
|
+
if (!fs.existsSync(p)) throw new Error(`${a.path} does not exist. Use write_file to create it.`);
|
|
293
|
+
if (!Array.isArray(a.edits) || !a.edits.length) throw new Error('edits must be a non-empty array.');
|
|
294
|
+
let text = fs.readFileSync(p, 'utf8');
|
|
295
|
+
const lines = [];
|
|
296
|
+
a.edits.forEach((e, i) => {
|
|
297
|
+
if (!e.old_string) throw new Error(`Edit ${i + 1}: old_string must not be empty.`);
|
|
298
|
+
let r;
|
|
299
|
+
try {
|
|
300
|
+
r = applyEdit(text, e, `Edit ${i + 1}: old_string`);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
throw new Error(`${err.message} (after the edits before it). Nothing was changed.`);
|
|
303
|
+
}
|
|
304
|
+
const start = text.slice(0, r.index).split('\n').length;
|
|
305
|
+
e.old_string.split('\n').slice(0, 6).forEach((t, j) => lines.push({ sign: '-', text: t, n: start + j }));
|
|
306
|
+
e.new_string.split('\n').slice(0, 6).forEach((t, j) => lines.push({ sign: '+', text: t, n: start + j }));
|
|
307
|
+
text = r.text;
|
|
308
|
+
});
|
|
309
|
+
return { p, text, lines };
|
|
310
|
+
},
|
|
311
|
+
validate(a, ctx) {
|
|
312
|
+
this.plan(a, ctx);
|
|
313
|
+
},
|
|
314
|
+
preview(a, ctx) {
|
|
315
|
+
const { lines } = this.plan(a, ctx);
|
|
316
|
+
return { title: `Edit ${rel(ctx, resolvePath(ctx, a.path))} (${a.edits.length} changes)`, lines };
|
|
317
|
+
},
|
|
318
|
+
run(a, ctx) {
|
|
319
|
+
const { p, text, lines } = this.plan(a, ctx);
|
|
320
|
+
ctx.checkpoints?.record(p);
|
|
321
|
+
fs.writeFileSync(p, text);
|
|
322
|
+
return { content: `Applied ${a.edits.length} edits to ${rel(ctx, p)}.`, display: `Updated ${rel(ctx, p)} · ${a.edits.length} edits`, lines, file: p };
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
name: 'apply_patch',
|
|
327
|
+
writes: true,
|
|
328
|
+
description: 'Apply a unified diff (git diff format) to one or more files at once: create, change, rename or delete files. Use it for large or multi-file changes; use edit_file for small ones. Hunks are located by their context lines, so line numbers in @@ headers may be approximate. All files change or none do.',
|
|
329
|
+
parameters: {
|
|
330
|
+
type: 'object',
|
|
331
|
+
properties: { patch: { type: 'string', description: 'The diff: "--- a/path" / "+++ b/path" headers (use /dev/null to create or delete), then @@ hunks with " ", "-" and "+" lines' } },
|
|
332
|
+
required: ['patch'],
|
|
333
|
+
},
|
|
334
|
+
needsPermission: true,
|
|
335
|
+
summary: (a) => {
|
|
336
|
+
try {
|
|
337
|
+
return parsePatch(a.patch).map((f) => f.to ?? f.from).join(', ');
|
|
338
|
+
} catch {
|
|
339
|
+
return 'patch';
|
|
340
|
+
}
|
|
341
|
+
},
|
|
342
|
+
validate(a, ctx) {
|
|
343
|
+
return planPatch(a.patch, (r) => resolvePath(ctx, r));
|
|
344
|
+
},
|
|
345
|
+
preview(a, ctx) {
|
|
346
|
+
const plan = this.validate(a, ctx);
|
|
347
|
+
const lines = String(a.patch).split('\n').filter((l) => /^[-+ ]/.test(l) && !/^(---|\+\+\+) /.test(l)).slice(0, 30).map((l) => ({ sign: l[0] === ' ' ? ' ' : l[0], text: l.slice(1) }));
|
|
348
|
+
return { title: `Patch ${plan.map((f) => `${f.op === 'create' ? '+' : f.op === 'delete' ? '−' : ''}${f.rel}`).join(', ')}`, lines };
|
|
349
|
+
},
|
|
350
|
+
run(a, ctx) {
|
|
351
|
+
const plan = this.validate(a, ctx);
|
|
352
|
+
writePlan(plan, (p) => ctx.checkpoints?.record(p));
|
|
353
|
+
const summary = plan.map((f) => `${f.op} ${f.rel} (+${f.added} −${f.removed})`).join('\n');
|
|
354
|
+
return { content: `Applied the patch:\n${summary}`, display: `Patched ${plan.length} file${plan.length === 1 ? '' : 's'}: ${plan.map((f) => f.rel).join(', ')}`, files: plan.filter((f) => f.op !== 'delete').map((f) => f.p) };
|
|
355
|
+
},
|
|
356
|
+
},
|
|
357
|
+
{
|
|
358
|
+
name: 'notebook_edit',
|
|
359
|
+
writes: true,
|
|
360
|
+
description: 'Change a Jupyter notebook (.ipynb) cell: replace its source, insert a new cell before cell_index, or delete it. Read the notebook first to see cell indexes. Replacing a code cell clears its old outputs.',
|
|
361
|
+
parameters: {
|
|
362
|
+
type: 'object',
|
|
363
|
+
properties: {
|
|
364
|
+
path: { type: 'string', description: 'Notebook path' },
|
|
365
|
+
cell_index: { type: 'integer', description: '0-based cell index (for insert: the new cell goes at this index)' },
|
|
366
|
+
new_source: { type: 'string', description: 'The cell source (not needed for delete)' },
|
|
367
|
+
cell_type: { type: 'string', enum: ['code', 'markdown'], description: 'Cell type (insert, or to change a cell\'s type)' },
|
|
368
|
+
edit_mode: { type: 'string', enum: ['replace', 'insert', 'delete'], description: 'Default replace' },
|
|
369
|
+
},
|
|
370
|
+
required: ['path', 'cell_index'],
|
|
371
|
+
},
|
|
372
|
+
needsPermission: true,
|
|
373
|
+
summary: (a) => `${a.path} · ${a.edit_mode || 'replace'} cell ${a.cell_index}`,
|
|
374
|
+
preview: (a, ctx) => ({
|
|
375
|
+
title: `${a.edit_mode === 'delete' ? 'Delete' : a.edit_mode === 'insert' ? 'Insert' : 'Replace'} cell ${a.cell_index} in ${rel(ctx, resolvePath(ctx, a.path))}`,
|
|
376
|
+
lines: a.edit_mode === 'delete' ? [] : String(a.new_source ?? '').split('\n').slice(0, 16).map((text) => ({ sign: '+', text })),
|
|
377
|
+
}),
|
|
378
|
+
run(a, ctx) {
|
|
379
|
+
const p = resolvePath(ctx, a.path);
|
|
380
|
+
if (!p.endsWith('.ipynb')) throw new Error('notebook_edit only edits .ipynb files; use edit_file for other files.');
|
|
381
|
+
ctx.checkpoints?.record(p);
|
|
382
|
+
const { n } = editNotebook(p, a);
|
|
383
|
+
const verb = a.edit_mode === 'delete' ? 'Deleted' : a.edit_mode === 'insert' ? 'Inserted' : 'Replaced';
|
|
384
|
+
const msg = `${verb} cell ${a.cell_index} in ${rel(ctx, p)} (${n} cells now)`;
|
|
385
|
+
return { content: msg, display: msg, file: p };
|
|
386
|
+
},
|
|
387
|
+
},
|
|
388
|
+
{
|
|
389
|
+
name: 'bash',
|
|
390
|
+
writes: true,
|
|
391
|
+
description: 'Run a shell command and return its combined stdout/stderr. The working directory and exported variables carry over between calls, like a terminal (cd once and stay there); file tools still resolve paths from the project root. No stdin: avoid interactive commands. For servers, watchers and other long-running commands, set run_in_background and check on them with bash_output.',
|
|
392
|
+
parameters: {
|
|
393
|
+
type: 'object',
|
|
394
|
+
properties: {
|
|
395
|
+
command: { type: 'string', description: 'The command to run' },
|
|
396
|
+
timeout_ms: { type: 'integer', description: 'Timeout in milliseconds (default 120000, max 600000)' },
|
|
397
|
+
run_in_background: { type: 'boolean', description: 'Start it and return immediately (dev servers, watchers, long builds). Read output with bash_output, stop with kill_process.' },
|
|
398
|
+
unsandboxed: { type: 'boolean', description: 'Only when the sandbox is on: run outside it (the user is asked first). Use only after a command failed because the sandbox blocked it, e.g. it needs the network or to write outside the project.' },
|
|
399
|
+
},
|
|
400
|
+
required: ['command'],
|
|
401
|
+
},
|
|
402
|
+
// Sandboxed commands can't touch anything outside the project, so they don't ask.
|
|
403
|
+
needsPermissionFor: (a, ctx) => !(ctx?.permissions?.sandbox && !a.unsandboxed && sandboxAvailable()),
|
|
404
|
+
summary: (a) => a.command,
|
|
405
|
+
preview: (a) => ({ title: a.unsandboxed ? 'Run command outside the sandbox' : 'Run command', lines: String(a.command).split('\n').map((text) => ({ sign: '$', text })) }),
|
|
406
|
+
async run(a, ctx) {
|
|
407
|
+
const timeoutMs = Math.min(Math.max(a.timeout_ms || 120000, 1000), 600000);
|
|
408
|
+
const shellPath = fs.existsSync('/bin/bash') ? '/bin/bash' : '/bin/sh';
|
|
409
|
+
const onOutput = (ctx.depth ?? 0) === 0 ? (line) => ctx.ui.spinnerDetail?.(line) : undefined;
|
|
410
|
+
// The shell's directory and variables from earlier calls (per agent).
|
|
411
|
+
const state = (ctx.agent ? (ctx.agent.shell ??= { cwd: ctx.cwd, env: {}, unset: [] }) : { cwd: ctx.cwd, env: {}, unset: [] });
|
|
412
|
+
if (!fs.existsSync(state.cwd)) state.cwd = ctx.cwd;
|
|
413
|
+
const baseEnv = { ...process.env, LETO: '1', ...state.env };
|
|
414
|
+
for (const k of state.unset) delete baseEnv[k];
|
|
415
|
+
const wrap = (command) => (ctx.permissions?.sandbox && !a.unsandboxed ? sandboxCommand(command, { cwd: ctx.cwd, network: ctx.permissions.sandboxNetwork, shell: shellPath }) : { cmd: shellPath, args: ['-c', command] });
|
|
416
|
+
if (a.run_in_background) {
|
|
417
|
+
const { cmd, args } = wrap(String(a.command));
|
|
418
|
+
const p = startProcess({ cmd, args, cwd: state.cwd, env: baseEnv, command: String(a.command) });
|
|
419
|
+
await new Promise((r) => setTimeout(r, 800)); // catch an immediate failure
|
|
420
|
+
const { text } = readProcess(p.id);
|
|
421
|
+
return { content: `Started in the background as ${p.id}.\n${text}\nRead more output with bash_output {"id":"${p.id}"}; stop it with kill_process.`, display: `background ${p.id} · ${p.code === null ? 'running' : `exited ${p.code}`}` };
|
|
422
|
+
}
|
|
423
|
+
const stateFile = stateFileFor();
|
|
424
|
+
const boxed = ctx.permissions?.sandbox && !a.unsandboxed;
|
|
425
|
+
const { cmd, args } = wrap(withState(String(a.command), stateFile));
|
|
426
|
+
const { out, code, timedOut, aborted, error } = await runProcess(cmd, args, { cwd: state.cwd, signal: ctx.signal, timeoutMs, onOutput, env: baseEnv });
|
|
427
|
+
if (error) throw error;
|
|
428
|
+
const next = readState(stateFile, baseEnv);
|
|
429
|
+
let moved = '';
|
|
430
|
+
if (next.cwd && next.cwd !== state.cwd && fs.existsSync(next.cwd)) {
|
|
431
|
+
state.cwd = next.cwd;
|
|
432
|
+
moved = `\n[working directory is now ${next.cwd}]`;
|
|
433
|
+
}
|
|
434
|
+
if (next.env) {
|
|
435
|
+
Object.assign(state.env, next.env);
|
|
436
|
+
state.unset = [...new Set([...state.unset.filter((k) => !(k in next.env)), ...next.unset])];
|
|
437
|
+
for (const k of next.unset) delete state.env[k];
|
|
438
|
+
}
|
|
439
|
+
let result = (truncate(out.trimEnd()) || '(no output)') + moved;
|
|
440
|
+
if (timedOut) result += `\n[timed out after ${timeoutMs / 1000}s]`;
|
|
441
|
+
else if (aborted) result += '\n[interrupted by user]';
|
|
442
|
+
else if (code !== 0) result += `\n[exit code ${code}]`;
|
|
443
|
+
if (boxed && code !== 0 && looksBlocked(out)) {
|
|
444
|
+
result += `\n[This ran in the sandbox, which allows writes only inside the project and temp folders${ctx.permissions.sandboxNetwork ? '' : ', has no network'}, and hides credentials. If the failure is from the sandbox, call bash again with unsandboxed: true and the user will be asked.]`;
|
|
445
|
+
}
|
|
446
|
+
return boxed ? { content: result, display: undefined, sandboxed: true } : result;
|
|
447
|
+
},
|
|
448
|
+
},
|
|
449
|
+
{
|
|
450
|
+
name: 'bash_output',
|
|
451
|
+
description: 'Read output from a background process started with bash run_in_background: what it printed since you last looked (or all of it), and whether it is still running.',
|
|
452
|
+
parameters: {
|
|
453
|
+
type: 'object',
|
|
454
|
+
properties: {
|
|
455
|
+
id: { type: 'string', description: 'Process id, e.g. p1 (omit to list all background processes)' },
|
|
456
|
+
filter: { type: 'string', description: 'Only lines matching this regular expression' },
|
|
457
|
+
all: { type: 'boolean', description: 'Everything it printed, not just what is new' },
|
|
458
|
+
},
|
|
459
|
+
},
|
|
460
|
+
summary: (a) => a.id || 'list',
|
|
461
|
+
run(a) {
|
|
462
|
+
if (!a.id) {
|
|
463
|
+
const list = listProcesses();
|
|
464
|
+
return list.length ? list.map((p) => `${p.id} \`${p.command}\` ${p.code === null ? 'running' : `exited ${p.code}`}`).join('\n') : 'No background processes.';
|
|
465
|
+
}
|
|
466
|
+
const { text, p } = readProcess(a.id, { filter: a.filter, all: a.all });
|
|
467
|
+
return { content: text, display: `${p.id} · ${p.code === null ? 'running' : `exited ${p.code}`}` };
|
|
468
|
+
},
|
|
469
|
+
},
|
|
470
|
+
{
|
|
471
|
+
name: 'kill_process',
|
|
472
|
+
description: 'Stop a background process started with bash run_in_background.',
|
|
473
|
+
parameters: { type: 'object', properties: { id: { type: 'string', description: 'Process id, e.g. p1' } }, required: ['id'] },
|
|
474
|
+
summary: (a) => a.id,
|
|
475
|
+
run(a) {
|
|
476
|
+
return stopProcess(a.id);
|
|
477
|
+
},
|
|
478
|
+
},
|
|
479
|
+
{
|
|
480
|
+
name: 'grep',
|
|
481
|
+
description: 'Search file contents with a regular expression. Returns matching lines as path:line:text. Skips .git and node_modules.',
|
|
482
|
+
parameters: {
|
|
483
|
+
type: 'object',
|
|
484
|
+
properties: {
|
|
485
|
+
pattern: { type: 'string', description: 'Regular expression' },
|
|
486
|
+
path: { type: 'string', description: 'File or directory to search (default: working directory)' },
|
|
487
|
+
glob: { type: 'string', description: 'Only search files matching this glob, e.g. "*.ts"' },
|
|
488
|
+
ignore_case: { type: 'boolean', description: 'Case-insensitive search' },
|
|
489
|
+
},
|
|
490
|
+
required: ['pattern'],
|
|
491
|
+
},
|
|
492
|
+
summary: (a) => `${a.pattern}${a.glob ? ` (${a.glob})` : ''}`,
|
|
493
|
+
async run(a, ctx) {
|
|
494
|
+
const root = resolvePath(ctx, a.path || '.');
|
|
495
|
+
const limit = 200;
|
|
496
|
+
if (hasRipgrep()) {
|
|
497
|
+
const args = ['-n', '--no-heading', '--color', 'never', '--max-columns', '400'];
|
|
498
|
+
if (a.ignore_case) args.push('-i');
|
|
499
|
+
if (a.glob) args.push('-g', a.glob);
|
|
500
|
+
args.push('-e', a.pattern);
|
|
501
|
+
if (root !== ctx.cwd) args.push(rel(ctx, root));
|
|
502
|
+
const { out, code } = await runProcess('rg', args, { cwd: ctx.cwd, signal: ctx.signal, timeoutMs: 60000 });
|
|
503
|
+
if (code === 1) return 'No matches.';
|
|
504
|
+
if (code !== 0) throw new Error(out.trim() || `rg exited with code ${code}`);
|
|
505
|
+
const lines = out.trimEnd().split('\n');
|
|
506
|
+
return lines.slice(0, limit).join('\n') + (lines.length > limit ? `\n… (${lines.length - limit} more matches)` : '');
|
|
507
|
+
}
|
|
508
|
+
const re = new RegExp(a.pattern, a.ignore_case ? 'i' : '');
|
|
509
|
+
const globRe = a.glob ? globToRegExp(a.glob) : null;
|
|
510
|
+
const files = fs.statSync(root).isFile() ? [root] : walk(root);
|
|
511
|
+
const results = [];
|
|
512
|
+
let total = 0;
|
|
513
|
+
for (const f of files) {
|
|
514
|
+
if (globRe && !globRe.test(path.relative(root, f).split(path.sep).join('/'))) continue;
|
|
515
|
+
let buf;
|
|
516
|
+
try {
|
|
517
|
+
if (fs.statSync(f).size > 2_000_000) continue;
|
|
518
|
+
buf = fs.readFileSync(f);
|
|
519
|
+
} catch {
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
if (isBinary(buf)) continue;
|
|
523
|
+
const lines = buf.toString('utf8').split('\n');
|
|
524
|
+
for (let i = 0; i < lines.length; i++) {
|
|
525
|
+
if (re.test(lines[i])) {
|
|
526
|
+
total++;
|
|
527
|
+
if (results.length < limit) results.push(`${rel(ctx, f)}:${i + 1}:${lines[i].slice(0, 400)}`);
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (!total) return 'No matches.';
|
|
532
|
+
return results.join('\n') + (total > limit ? `\n… (${total - limit} more matches)` : '');
|
|
533
|
+
},
|
|
534
|
+
},
|
|
535
|
+
{
|
|
536
|
+
name: 'list_files',
|
|
537
|
+
description: 'Find files by glob pattern, e.g. "**/*.py" or "src/**/*.ts". Skips .git and node_modules.',
|
|
538
|
+
parameters: {
|
|
539
|
+
type: 'object',
|
|
540
|
+
properties: {
|
|
541
|
+
pattern: { type: 'string', description: 'Glob pattern (default "**/*")' },
|
|
542
|
+
path: { type: 'string', description: 'Directory to search (default: working directory)' },
|
|
543
|
+
},
|
|
544
|
+
},
|
|
545
|
+
summary: (a) => a.pattern || '**/*',
|
|
546
|
+
run(a, ctx) {
|
|
547
|
+
const root = resolvePath(ctx, a.path || '.');
|
|
548
|
+
const re = globToRegExp(a.pattern || '**/*');
|
|
549
|
+
const limit = 500;
|
|
550
|
+
const results = [];
|
|
551
|
+
let total = 0;
|
|
552
|
+
for (const f of walk(root)) {
|
|
553
|
+
const r = path.relative(root, f).split(path.sep).join('/');
|
|
554
|
+
if (!re.test(r)) continue;
|
|
555
|
+
total++;
|
|
556
|
+
if (results.length < limit) results.push(rel(ctx, f));
|
|
557
|
+
}
|
|
558
|
+
if (!total) return 'No files found.';
|
|
559
|
+
return results.join('\n') + (total > limit ? `\n… (${total - limit} more files)` : '');
|
|
560
|
+
},
|
|
561
|
+
},
|
|
562
|
+
];
|
|
563
|
+
|
|
564
|
+
TOOLS.push(
|
|
565
|
+
repoMapTool,
|
|
566
|
+
lspTool,
|
|
567
|
+
memoryTool,
|
|
568
|
+
selfTool,
|
|
569
|
+
{
|
|
570
|
+
name: 'web_search',
|
|
571
|
+
description: 'Search the web. Returns titles, links and snippets for the top results. Follow up with web_fetch (or the browser) to read the pages that matter. Use specific queries; run several searches for different angles.',
|
|
572
|
+
parameters: {
|
|
573
|
+
type: 'object',
|
|
574
|
+
properties: {
|
|
575
|
+
query: { type: 'string', description: 'What to search for' },
|
|
576
|
+
count: { type: 'integer', description: 'How many results (default 8, max 20)' },
|
|
577
|
+
},
|
|
578
|
+
required: ['query'],
|
|
579
|
+
},
|
|
580
|
+
summary: (a) => a.query,
|
|
581
|
+
async run(a, ctx) {
|
|
582
|
+
const results = await webSearch(String(a.query), Math.min(20, Math.max(1, a.count || 8)), ctx.signal);
|
|
583
|
+
if (!results.length) return { content: `No results for "${a.query}".`, display: 'no results' };
|
|
584
|
+
const body = results.map((r, i) => `${i + 1}. ${r.title}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`).join('\n\n');
|
|
585
|
+
return { content: `Results for "${a.query}":\n\n${body}`, display: `${results.length} results` };
|
|
586
|
+
},
|
|
587
|
+
},
|
|
588
|
+
browserTool,
|
|
589
|
+
{
|
|
590
|
+
name: 'web_fetch',
|
|
591
|
+
description: 'Fetch a URL and return its content as text (HTML is converted to readable text). Use it for documentation, issues, API references and other pages the task needs.',
|
|
592
|
+
parameters: {
|
|
593
|
+
type: 'object',
|
|
594
|
+
properties: {
|
|
595
|
+
url: { type: 'string', description: 'Full http(s) URL' },
|
|
596
|
+
max_chars: { type: 'integer', description: 'Max characters to return (default 30000)' },
|
|
597
|
+
},
|
|
598
|
+
required: ['url'],
|
|
599
|
+
},
|
|
600
|
+
needsPermission: true,
|
|
601
|
+
summary: (a) => a.url,
|
|
602
|
+
preview: (a) => ({ title: `Fetch ${a.url}`, lines: [] }),
|
|
603
|
+
async run(a, ctx) {
|
|
604
|
+
const url = new URL(a.url);
|
|
605
|
+
if (!/^https?:$/.test(url.protocol)) throw new Error('Only http and https URLs are supported.');
|
|
606
|
+
const res = await fetch(url, {
|
|
607
|
+
signal: anySignal([ctx.signal, AbortSignal.timeout(30000)]),
|
|
608
|
+
redirect: 'follow',
|
|
609
|
+
headers: { 'user-agent': 'leto-cli', accept: 'text/html,text/plain,application/json;q=0.9,*/*;q=0.5' },
|
|
610
|
+
});
|
|
611
|
+
const type = res.headers.get('content-type') || '';
|
|
612
|
+
if (/^(image|audio|video)\/|application\/(pdf|zip|octet-stream)/.test(type)) {
|
|
613
|
+
return { content: `URL: ${res.url}\nStatus: ${res.status}\nContent-Type: ${type}\n(binary content not shown)`, display: `${res.status} · ${type}` };
|
|
614
|
+
}
|
|
615
|
+
let text = (await res.text()).slice(0, 5_000_000);
|
|
616
|
+
if (/html/i.test(type) || /^\s*<(!doctype|html)/i.test(text)) text = htmlToText(text);
|
|
617
|
+
const body = truncate(text, a.max_chars || MAX_OUTPUT);
|
|
618
|
+
return { content: `URL: ${res.url}\nStatus: ${res.status}\n\n${body}`, display: `${res.status} · ${text.length.toLocaleString()} characters` };
|
|
619
|
+
},
|
|
620
|
+
},
|
|
621
|
+
{
|
|
622
|
+
name: 'todo_write',
|
|
623
|
+
description: 'Create or update your task list for work with several steps. Send the whole list every time. Keep exactly one item in_progress while you work, and mark each item completed as soon as it is done. Skip this for simple one-step requests.',
|
|
624
|
+
parameters: {
|
|
625
|
+
type: 'object',
|
|
626
|
+
properties: {
|
|
627
|
+
todos: {
|
|
628
|
+
type: 'array',
|
|
629
|
+
items: {
|
|
630
|
+
type: 'object',
|
|
631
|
+
properties: {
|
|
632
|
+
content: { type: 'string', description: 'What to do, in a few words' },
|
|
633
|
+
status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
|
|
634
|
+
},
|
|
635
|
+
required: ['content', 'status'],
|
|
636
|
+
},
|
|
637
|
+
},
|
|
638
|
+
},
|
|
639
|
+
required: ['todos'],
|
|
640
|
+
},
|
|
641
|
+
summary: (a) => {
|
|
642
|
+
const list = Array.isArray(a.todos) ? a.todos : [];
|
|
643
|
+
return `${list.filter((t) => t.status === 'completed').length}/${list.length} done`;
|
|
644
|
+
},
|
|
645
|
+
run(a, ctx) {
|
|
646
|
+
if (!Array.isArray(a.todos)) throw new Error('todos must be an array');
|
|
647
|
+
const todos = a.todos.map((t) => ({ content: String(t.content ?? ''), status: ['pending', 'in_progress', 'completed'].includes(t.status) ? t.status : 'pending' }));
|
|
648
|
+
if (ctx.agent) {
|
|
649
|
+
ctx.agent.todos = todos;
|
|
650
|
+
ctx.agent.session.append?.({ type: 'todos', todos }); // so the list survives a resume
|
|
651
|
+
}
|
|
652
|
+
ctx.ui.todos(todos);
|
|
653
|
+
return { content: 'Todo list updated. Keep it current as you work.', display: null };
|
|
654
|
+
},
|
|
655
|
+
},
|
|
656
|
+
{
|
|
657
|
+
name: 'ask_user',
|
|
658
|
+
label: 'Question',
|
|
659
|
+
description:
|
|
660
|
+
'Ask the user questions and wait for their answers. Use it when the request is ambiguous in a way that changes what you build (scope, approach, tech choices, tradeoffs they care about), before starting large work, or when you need a decision only they can make. Give 2-6 concrete options per question, recommended one first (say so in its description); the user can always type their own answer instead. Ask up to 4 questions in one call rather than one at a time. Don\'t ask what you can find out yourself by reading the code or running commands.',
|
|
661
|
+
parameters: {
|
|
662
|
+
type: 'object',
|
|
663
|
+
properties: {
|
|
664
|
+
questions: {
|
|
665
|
+
type: 'array',
|
|
666
|
+
description: '1 to 4 questions, asked one after another',
|
|
667
|
+
items: {
|
|
668
|
+
type: 'object',
|
|
669
|
+
properties: {
|
|
670
|
+
question: { type: 'string', description: 'The full question, ending with a question mark' },
|
|
671
|
+
header: { type: 'string', description: 'A 1-3 word label, e.g. "Language" or "Scope"' },
|
|
672
|
+
options: {
|
|
673
|
+
type: 'array',
|
|
674
|
+
description: '2-6 choices',
|
|
675
|
+
items: {
|
|
676
|
+
type: 'object',
|
|
677
|
+
properties: { label: { type: 'string', description: 'The choice, in a few words' }, description: { type: 'string', description: 'What it means or its tradeoff' } },
|
|
678
|
+
required: ['label'],
|
|
679
|
+
},
|
|
680
|
+
},
|
|
681
|
+
multi_select: { type: 'boolean', description: 'Let the user pick more than one option' },
|
|
682
|
+
},
|
|
683
|
+
required: ['question', 'options'],
|
|
684
|
+
},
|
|
685
|
+
},
|
|
686
|
+
},
|
|
687
|
+
required: ['questions'],
|
|
688
|
+
},
|
|
689
|
+
summary: (a) => (Array.isArray(a.questions) ? a.questions.map((q) => q.header || q.question).join(' · ') : ''),
|
|
690
|
+
validate(a) {
|
|
691
|
+
if (!Array.isArray(a.questions) || !a.questions.length) throw new Error('questions must be a non-empty array.');
|
|
692
|
+
if (a.questions.length > 4) throw new Error('Ask at most 4 questions at a time.');
|
|
693
|
+
for (const q of a.questions) {
|
|
694
|
+
if (!q?.question) throw new Error('Each question needs question text.');
|
|
695
|
+
if (!Array.isArray(q.options) || q.options.length < 2) throw new Error(`"${q.question}" needs at least 2 options.`);
|
|
696
|
+
}
|
|
697
|
+
},
|
|
698
|
+
async run(a, ctx) {
|
|
699
|
+
if (typeof ctx.ui.ask !== 'function') return 'Nobody can answer questions here. Make a reasonable assumption, say what you assumed, and continue.';
|
|
700
|
+
const answers = [];
|
|
701
|
+
for (const [i, q] of a.questions.entries()) {
|
|
702
|
+
if (ctx.signal?.aborted) break;
|
|
703
|
+
const options = q.options.slice(0, 6).map((o) => (typeof o === 'string' ? { label: o } : { label: String(o.label ?? ''), description: o.description ? String(o.description) : '' }));
|
|
704
|
+
const r = await ctx.ui.ask({ question: q.question, header: q.header, options, multiSelect: Boolean(q.multi_select), index: i, total: a.questions.length });
|
|
705
|
+
if (r === null && ctx.ui.print) {
|
|
706
|
+
return { content: 'The user is not available to answer (this is a non-interactive run). Make a reasonable assumption for each question, state what you assumed, and continue.', display: 'no one to ask (non-interactive)' };
|
|
707
|
+
}
|
|
708
|
+
answers.push({ q: q.question, a: r?.answer ?? null });
|
|
709
|
+
}
|
|
710
|
+
const text = answers.map((x, i) => `${i + 1}. ${x.q}\n → ${x.a ?? '(skipped: use your best judgment and say what you chose)'}`).join('\n');
|
|
711
|
+
return { content: `The user answered:\n${text}`, display: null };
|
|
712
|
+
},
|
|
713
|
+
},
|
|
714
|
+
{
|
|
715
|
+
name: 'task',
|
|
716
|
+
description:
|
|
717
|
+
'Hand a self-contained job to a sub-agent that has its own fresh context window. Use it to explore or search large codebases, research a question, or do independent pieces of work in parallel: call it several times in one response and the sub-agents run at the same time. The sub-agent cannot see this conversation, so put everything it needs in prompt. It returns a report, which only you see; summarize it for the user. agent_type "explore" is read-only (search and read); "general" can also edit files and run commands.',
|
|
718
|
+
parameters: {
|
|
719
|
+
type: 'object',
|
|
720
|
+
properties: {
|
|
721
|
+
description: { type: 'string', description: 'A 3-6 word label for the job' },
|
|
722
|
+
prompt: { type: 'string', description: 'Full instructions: the goal, relevant paths, what to report back' },
|
|
723
|
+
agent_type: { type: 'string', enum: ['explore', 'general'], description: 'explore (default): read-only. general: can edit and run commands.' },
|
|
724
|
+
isolation: { type: 'string', enum: ['none', 'worktree'], description: 'worktree: the sub-agent works in its own git worktree and branch, so several can change code in parallel without conflicts; its changes come back as a branch to merge. Only for agents that edit, in a git repository. Default none (works in the current checkout).' },
|
|
725
|
+
},
|
|
726
|
+
required: ['description', 'prompt'],
|
|
727
|
+
},
|
|
728
|
+
summary: (a) => `${a.worker ? `${a.worker} · ` : ''}${a.agent_type || 'explore'}${a.isolation === 'worktree' ? ' · worktree' : ''}: ${a.description}`,
|
|
729
|
+
async run(a, ctx) {
|
|
730
|
+
if (!ctx.agent?.runSubagent) throw new Error('Sub-agents are not available here.');
|
|
731
|
+
return ctx.agent.runSubagent(a, ctx.signal);
|
|
732
|
+
},
|
|
733
|
+
},
|
|
734
|
+
);
|
|
735
|
+
|
|
736
|
+
export const READ_ONLY_TOOLS = new Set(['read_file', 'grep', 'list_files', 'repo_map', 'lsp', 'web_fetch', 'web_search', 'skill']);
|
|
737
|
+
export const PARALLEL_SAFE = new Set(['read_file', 'grep', 'list_files', 'repo_map', 'lsp', 'web_fetch', 'web_search', 'skill', 'task']);
|
|
738
|
+
|
|
739
|
+
// Web search: Tavily or Brave when you have an API key for them, otherwise
|
|
740
|
+
// DuckDuckGo's plain-HTML results page (no key needed).
|
|
741
|
+
async function webSearch(query, count, signal) {
|
|
742
|
+
const timeout = anySignal([signal, AbortSignal.timeout(20000)]);
|
|
743
|
+
if (process.env.TAVILY_API_KEY) {
|
|
744
|
+
const res = await fetch('https://api.tavily.com/search', {
|
|
745
|
+
method: 'POST',
|
|
746
|
+
signal: timeout,
|
|
747
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${process.env.TAVILY_API_KEY}` },
|
|
748
|
+
body: JSON.stringify({ query, max_results: count }),
|
|
749
|
+
});
|
|
750
|
+
if (!res.ok) throw new Error(`Tavily search failed: HTTP ${res.status}`);
|
|
751
|
+
return ((await res.json()).results ?? []).map((r) => ({ title: r.title, url: r.url, snippet: (r.content ?? '').slice(0, 300) }));
|
|
752
|
+
}
|
|
753
|
+
if (process.env.BRAVE_SEARCH_API_KEY) {
|
|
754
|
+
const res = await fetch(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(query)}&count=${count}`, {
|
|
755
|
+
signal: timeout,
|
|
756
|
+
headers: { accept: 'application/json', 'x-subscription-token': process.env.BRAVE_SEARCH_API_KEY },
|
|
757
|
+
});
|
|
758
|
+
if (!res.ok) throw new Error(`Brave search failed: HTTP ${res.status}`);
|
|
759
|
+
return ((await res.json()).web?.results ?? []).map((r) => ({ title: r.title, url: r.url, snippet: htmlToText(r.description ?? '') }));
|
|
760
|
+
}
|
|
761
|
+
const res = await fetch(process.env.LETO_SEARCH_URL || 'https://html.duckduckgo.com/html/', {
|
|
762
|
+
method: 'POST',
|
|
763
|
+
signal: timeout,
|
|
764
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Mozilla/5.0 (compatible; leto-cli)' },
|
|
765
|
+
body: `q=${encodeURIComponent(query)}`,
|
|
766
|
+
});
|
|
767
|
+
if (!res.ok) throw new Error(`Search failed: HTTP ${res.status}. Set TAVILY_API_KEY or BRAVE_SEARCH_API_KEY for a dedicated search API.`);
|
|
768
|
+
return parseDuckDuckGo(await res.text()).slice(0, count);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
export function parseDuckDuckGo(html) {
|
|
772
|
+
const out = [];
|
|
773
|
+
const blocks = html.split(/<div[^>]+class="[^"]*\bresult\b[^"]*"/).slice(1);
|
|
774
|
+
for (const b of blocks) {
|
|
775
|
+
const a = b.match(/<a[^>]+class="[^"]*result__a[^"]*"[^>]+href="([^"]+)"[^>]*>([\s\S]*?)<\/a>/);
|
|
776
|
+
if (!a) continue;
|
|
777
|
+
let url = a[1].replace(/&/g, '&');
|
|
778
|
+
const uddg = url.match(/[?&]uddg=([^&]+)/);
|
|
779
|
+
if (uddg) url = decodeURIComponent(uddg[1]);
|
|
780
|
+
if (url.startsWith('//')) url = `https:${url}`;
|
|
781
|
+
if (/duckduckgo\.com\/y\.js|\/\/duckduckgo\.com\/\?/.test(url)) continue; // ads
|
|
782
|
+
const snippet = b.match(/class="[^"]*result__snippet[^"]*"[^>]*>([\s\S]*?)<\/(a|div)>/);
|
|
783
|
+
out.push({ title: htmlToText(a[2]).replace(/^# /, ''), url, snippet: snippet ? htmlToText(snippet[1]).slice(0, 300) : '' });
|
|
784
|
+
}
|
|
785
|
+
return out;
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
function anySignal(signals) {
|
|
789
|
+
const list = signals.filter(Boolean);
|
|
790
|
+
if (AbortSignal.any) return AbortSignal.any(list);
|
|
791
|
+
const ac = new AbortController();
|
|
792
|
+
for (const s of list) {
|
|
793
|
+
if (s.aborted) ac.abort(s.reason);
|
|
794
|
+
else s.addEventListener('abort', () => ac.abort(s.reason), { once: true });
|
|
795
|
+
}
|
|
796
|
+
return ac.signal;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
export function htmlToText(html) {
|
|
800
|
+
const title = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1]?.trim();
|
|
801
|
+
let t = html
|
|
802
|
+
.replace(/<(script|style|noscript|svg|template|iframe)[\s\S]*?<\/\1>/gi, '')
|
|
803
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
804
|
+
.replace(/<head[\s\S]*?<\/head>/i, '')
|
|
805
|
+
.replace(/<h([1-6])[^>]*>/gi, (_, n) => '\n\n' + '#'.repeat(Number(n)) + ' ')
|
|
806
|
+
.replace(/<li[^>]*>/gi, '\n- ')
|
|
807
|
+
.replace(/<(br|hr)\s*\/?>/gi, '\n')
|
|
808
|
+
.replace(/<\/(p|div|section|article|header|footer|h[1-6]|li|tr|table|ul|ol|pre|blockquote)>/gi, '\n')
|
|
809
|
+
.replace(/<(td|th)[^>]*>/gi, ' | ')
|
|
810
|
+
.replace(/<a [^>]*href="([^"#][^"]*)"[^>]*>([\s\S]*?)<\/a>/gi, (_, href, text) => `${text.replace(/<[^>]+>/g, '')} (${href})`)
|
|
811
|
+
.replace(/<[^>]+>/g, '')
|
|
812
|
+
.replace(/ /g, ' ')
|
|
813
|
+
.replace(/&/g, '&')
|
|
814
|
+
.replace(/</g, '<')
|
|
815
|
+
.replace(/>/g, '>')
|
|
816
|
+
.replace(/"/g, '"')
|
|
817
|
+
.replace(/'|'/g, "'")
|
|
818
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)))
|
|
819
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16)));
|
|
820
|
+
t = t
|
|
821
|
+
.split('\n')
|
|
822
|
+
.map((l) => l.replace(/[ \t]+/g, ' ').trim())
|
|
823
|
+
.join('\n')
|
|
824
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
825
|
+
.trim();
|
|
826
|
+
return title ? `# ${title}\n\n${t}` : t;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Custom agents become extra agent_type values on the task tool. Called once
|
|
830
|
+
// at startup, before the first request, so the tool list stays fixed.
|
|
831
|
+
export function setAgentTypes(defs) {
|
|
832
|
+
const task = TOOLS.find((t) => t.name === 'task');
|
|
833
|
+
const prop = task.parameters.properties.agent_type;
|
|
834
|
+
prop.enum = ['explore', 'general', ...defs.map((d) => d.name)];
|
|
835
|
+
prop.description = `explore (default): read-only. general: can edit and run commands.${defs.map((d) => ` ${d.name}: ${d.description}`).join('')}`;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// Orchestrator mode: the task tool gets a worker option naming a team member.
|
|
839
|
+
export function setWorkers(team) {
|
|
840
|
+
const task = TOOLS.find((t) => t.name === 'task');
|
|
841
|
+
if (!team?.length) {
|
|
842
|
+
delete task.parameters.properties.worker;
|
|
843
|
+
return;
|
|
844
|
+
}
|
|
845
|
+
task.parameters.properties.worker = {
|
|
846
|
+
type: 'string',
|
|
847
|
+
enum: team.map((m) => m.name),
|
|
848
|
+
description: `Orchestrator mode: the team member (model) to run this job. ${team.map((m) => `${m.name} = ${m.model}`).join('; ')}. See the team's strengths in the system prompt.`,
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Tools added at runtime (MCP servers).
|
|
853
|
+
let extraTools = [];
|
|
854
|
+
export const setExtraTools = (list) => {
|
|
855
|
+
extraTools = list;
|
|
856
|
+
};
|
|
857
|
+
export const allTools = () => (extraTools.length ? [...TOOLS, ...extraTools] : TOOLS);
|
|
858
|
+
|
|
859
|
+
export const toolSchemas = (filter = () => true) =>
|
|
860
|
+
allTools().filter((t) => filter(t.name)).map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }));
|
|
861
|
+
|
|
862
|
+
export const findTool = (name) => allTools().find((t) => t.name === name);
|
|
863
|
+
|
|
864
|
+
// Run one tool call from the model. Always returns a string for the tool message.
|
|
865
|
+
// ctx: { cwd, signal, ui, permissions, agent, depth, label, allowed }
|
|
866
|
+
export async function executeToolCall(call, ctx) {
|
|
867
|
+
const tool = findTool(call.function?.name);
|
|
868
|
+
if (!tool || (ctx.allowed && !ctx.allowed(tool.name))) {
|
|
869
|
+
return `Error: unknown tool "${call.function?.name}".`;
|
|
870
|
+
}
|
|
871
|
+
let args;
|
|
872
|
+
try {
|
|
873
|
+
args = call.function.arguments ? JSON.parse(call.function.arguments) : {};
|
|
874
|
+
} catch {
|
|
875
|
+
// Models sometimes send slightly broken JSON; fix what can be fixed safely.
|
|
876
|
+
args = repairJson(call.function.arguments);
|
|
877
|
+
if (!args || typeof args !== 'object') return `Error: tool arguments were not valid JSON: ${String(call.function.arguments).slice(0, 200)}. Send the arguments as one valid JSON object.`;
|
|
878
|
+
}
|
|
879
|
+
// Tool input may arrive malformed or cut short; check it against the schema first.
|
|
880
|
+
const problem = checkArgs(tool.parameters, args);
|
|
881
|
+
if (problem) return `Error: invalid input for ${tool.name}: ${problem}. Fix the arguments and call the tool again.`;
|
|
882
|
+
const sub = (ctx.depth ?? 0) > 0;
|
|
883
|
+
const tag = { id: call.id ?? null };
|
|
884
|
+
ctx.ui.toolStart(tool.label ?? tool.name, safe(() => tool.summary?.(args)) ?? '', { prefix: sub ? `${ctx.label}` : '', id: call.id ?? null, name: tool.name, input: args });
|
|
885
|
+
try {
|
|
886
|
+
if (tool.validate) tool.validate(args, ctx);
|
|
887
|
+
const writes = tool.writes || tool.writesFor?.(args);
|
|
888
|
+
if (writes && ctx.permissions.planMode) {
|
|
889
|
+
if (!sub) ctx.ui.toolResult('Blocked: plan mode is on', true, tag);
|
|
890
|
+
return 'Blocked: plan mode is on, so files cannot be changed and commands cannot run. Finish investigating with the read-only tools, then present your plan. The user turns plan mode off with /plan when they approve.';
|
|
891
|
+
}
|
|
892
|
+
if (ctx.hooks) {
|
|
893
|
+
const pre = await ctx.hooks.run('PreToolUse', { tool: tool.name, input: args, sessionId: ctx.sessionId });
|
|
894
|
+
if (pre.blocked) {
|
|
895
|
+
if (!sub) ctx.ui.toolResult(`Blocked by hook: ${pre.reason.split('\n')[0]}`, true, tag);
|
|
896
|
+
return `Blocked by a PreToolUse hook: ${pre.reason}`;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
let preview = null;
|
|
900
|
+
if (tool.needsPermission || tool.needsPermissionFor?.(args, ctx)) {
|
|
901
|
+
preview = safe(() => tool.preview?.(args, ctx));
|
|
902
|
+
if (preview && sub) preview.title = `[${ctx.label}] ${preview.title}`;
|
|
903
|
+
const allowed = await ctx.permissions.check(tool.name, preview, args);
|
|
904
|
+
if (!allowed) {
|
|
905
|
+
ctx.ui.toolResult('Denied', true, tag);
|
|
906
|
+
return 'Permission denied: the user declined this tool call. Do not retry it; ask the user how to proceed.';
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
if (!sub) ctx.ui.startSpinner(tool.name === 'task' ? 'Agents working' : 'Running');
|
|
910
|
+
// With an editor connected, remember each file's content before the edit to show a diff.
|
|
911
|
+
const originals = new Map();
|
|
912
|
+
let runCtx = ctx;
|
|
913
|
+
if (ctx.ide && tool.writes && tool.name !== 'bash') {
|
|
914
|
+
const cp = ctx.checkpoints;
|
|
915
|
+
runCtx = { ...ctx, checkpoints: { record: (p) => {
|
|
916
|
+
if (!originals.has(p)) originals.set(p, fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : '');
|
|
917
|
+
cp?.record(p);
|
|
918
|
+
} } };
|
|
919
|
+
}
|
|
920
|
+
const raw = await tool.run(args, runCtx);
|
|
921
|
+
for (const [p, before] of originals) if (fs.existsSync(p)) ctx.ide.showDiff(p, before, tool.name.replace('_', ' '));
|
|
922
|
+
let { content, display, lines } = raw && typeof raw === 'object' ? raw : { content: String(raw) };
|
|
923
|
+
// Edited a file: note it for the project check, and parse it right away.
|
|
924
|
+
for (const file of raw?.files ?? (raw?.file ? [raw.file] : [])) {
|
|
925
|
+
ctx.agent?.changedFiles?.add(file);
|
|
926
|
+
const problem = ctx.agent?.config?.syntaxCheck === false ? null : syntaxCheck(file);
|
|
927
|
+
if (problem) {
|
|
928
|
+
content = `${content}\n\n${rel(ctx, file)}: ${problem}\nThe file was written, but it no longer parses. Fix this before moving on.`;
|
|
929
|
+
display = `${display ?? content.split('\n')[0]} · ⚠ ${problem.split('\n').slice(0, 2).join(' ').slice(0, 120)}`;
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
// A language server already running for this file reports type errors too.
|
|
933
|
+
const errors = await diagnosticsAfterEdit(file, ctx.cwd).catch(() => null);
|
|
934
|
+
if (errors) {
|
|
935
|
+
const n = errors.split('\n').length;
|
|
936
|
+
content = `${content}\n\nThe language server reports ${n} error${n === 1 ? '' : 's'} in this file now:\n${errors}`;
|
|
937
|
+
display = `${display ?? content.split('\n')[0]} · ⚠ ${n} error${n === 1 ? '' : 's'}`;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
if (ctx.hooks) await ctx.hooks.run('PostToolUse', { tool: tool.name, input: args, result: truncate(String(content), 10000), sessionId: ctx.sessionId });
|
|
941
|
+
// Skip the diff when the user just saw it in the approval prompt.
|
|
942
|
+
if (!sub && display !== null) ctx.ui.toolResult(display ?? content, false, { ...tag, lines: preview?.shown ? null : lines, diff: lines, images: raw?.images });
|
|
943
|
+
if (raw?.images?.length || raw?.documents?.length) return { text: truncate(String(content)), images: raw.images, documents: raw.documents };
|
|
944
|
+
return truncate(String(content));
|
|
945
|
+
} catch (err) {
|
|
946
|
+
const msg = `Error: ${err.name === 'AbortError' || err.name === 'TimeoutError' ? (ctx.signal?.aborted ? 'interrupted by the user' : 'timed out') : err.message}`;
|
|
947
|
+
if (!sub) ctx.ui.toolResult(msg, true, tag);
|
|
948
|
+
return msg;
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function checkArgs(schema, args) {
|
|
953
|
+
if (!args || typeof args !== 'object' || Array.isArray(args)) return 'arguments must be a JSON object';
|
|
954
|
+
for (const key of schema?.required ?? []) if (args[key] === undefined || args[key] === null) return `missing required "${key}"`;
|
|
955
|
+
for (const [key, spec] of Object.entries(schema?.properties ?? {})) {
|
|
956
|
+
const v = args[key];
|
|
957
|
+
if (v === undefined || v === null || !spec?.type) continue;
|
|
958
|
+
const ok = spec.type === 'string' ? typeof v === 'string'
|
|
959
|
+
: spec.type === 'integer' ? Number.isInteger(v)
|
|
960
|
+
: spec.type === 'number' ? typeof v === 'number'
|
|
961
|
+
: spec.type === 'boolean' ? typeof v === 'boolean'
|
|
962
|
+
: spec.type === 'array' ? Array.isArray(v)
|
|
963
|
+
: spec.type === 'object' ? typeof v === 'object' && !Array.isArray(v)
|
|
964
|
+
: true;
|
|
965
|
+
if (!ok) return `"${key}" must be ${spec.type === 'integer' ? 'an integer' : `a ${spec.type}`}`;
|
|
966
|
+
}
|
|
967
|
+
return null;
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
function safe(fn) {
|
|
971
|
+
try {
|
|
972
|
+
return fn();
|
|
973
|
+
} catch {
|
|
974
|
+
return undefined;
|
|
975
|
+
}
|
|
976
|
+
}
|