@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/agent.js
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
1
|
+
import { streamChat, completeText } from './client.js';
|
|
2
|
+
import { toolSchemas, executeToolCall, truncate, READ_ONLY_TOOLS, PARALLEL_SAFE } from './tools.js';
|
|
3
|
+
import { buildSystemPrompt } from './prompt.js';
|
|
4
|
+
import { Session } from './session.js';
|
|
5
|
+
import { isNativeAnthropic, streamAnthropic, completeAnthropic, serverCompaction } from './anthropic.js';
|
|
6
|
+
import { Usage } from './pricing.js';
|
|
7
|
+
import { runCheck, condense } from './verify.js';
|
|
8
|
+
import { parseToolCalls, toTextHistory, MarkupFilter } from './toolcalls.js';
|
|
9
|
+
import { createWorktree, finishWorktree } from './worktree.js';
|
|
10
|
+
import { sandboxAvailable } from './sandbox.js';
|
|
11
|
+
import { workerConfig, orchestratorPrompt } from './orchestrator.js';
|
|
12
|
+
import { formatCost } from './pricing.js';
|
|
13
|
+
import { unreportedExits } from './processes.js';
|
|
14
|
+
import { policyDisablesTool } from './policy.js';
|
|
15
|
+
import { readNotes } from './memory.js';
|
|
16
|
+
|
|
17
|
+
const MAX_STEPS = 1500;
|
|
18
|
+
const MAX_SUB_STEPS = 300;
|
|
19
|
+
const COMPACT_AT = 0.8;
|
|
20
|
+
const KEEP_RECENT = 6;
|
|
21
|
+
const MAX_CHECK_ROUNDS = 3;
|
|
22
|
+
const MAX_RETRIES = 5;
|
|
23
|
+
|
|
24
|
+
// Errors worth retrying: rate limits, overload, server errors, dropped connections.
|
|
25
|
+
export function isTransient(err) {
|
|
26
|
+
if (!err || err.name === 'AbortError') return false;
|
|
27
|
+
if ([408, 409, 429, 500, 502, 503, 504, 529].includes(err.status)) return true;
|
|
28
|
+
// Can't connect at all (wrong URL, offline): the client already retried; fail fast.
|
|
29
|
+
if (err.unreachable || /ECONNREFUSED|ENOTFOUND/.test(String(err.message))) return false;
|
|
30
|
+
if (err.name === 'APIConnectionError' || err.name === 'APIConnectionTimeoutError') return true;
|
|
31
|
+
return /ECONNRESET|ETIMEDOUT|EPIPE|socket hang up|terminated|other side closed|fetch failed|overloaded|network/i.test(String(err.message));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function wait(ms, signal) {
|
|
35
|
+
return new Promise((resolve, reject) => {
|
|
36
|
+
const t = setTimeout(resolve, ms);
|
|
37
|
+
signal?.addEventListener('abort', () => {
|
|
38
|
+
clearTimeout(t);
|
|
39
|
+
reject(new DOMException('Interrupted', 'AbortError'));
|
|
40
|
+
}, { once: true });
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Rough token count: ~4 characters per token, ~1600 tokens per image.
|
|
45
|
+
export function estimateTokens(messages) {
|
|
46
|
+
let chars = 0;
|
|
47
|
+
for (const m of messages) {
|
|
48
|
+
if (Array.isArray(m.content)) for (const p of m.content) chars += p.type === 'image_url' ? 6400 : String(p.text ?? '').length;
|
|
49
|
+
else chars += String(m.content ?? '').length;
|
|
50
|
+
if (m.tool_calls) chars += JSON.stringify(m.tool_calls).length;
|
|
51
|
+
if (m.images) chars += m.images.length * 6400;
|
|
52
|
+
if (m.documents) for (const d of m.documents) chars += d.length / 2;
|
|
53
|
+
chars += 16;
|
|
54
|
+
}
|
|
55
|
+
return Math.ceil(chars / 4);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const textOf = (content) => (Array.isArray(content) ? content.map((p) => (p.type === 'text' ? p.text : '[image]')).join('\n') : String(content ?? ''));
|
|
59
|
+
|
|
60
|
+
export class Agent {
|
|
61
|
+
// depth 0 is the agent the user talks to; sub-agents have depth >= 1.
|
|
62
|
+
constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null, checkpoints = null, hooks = null, usage = null }) {
|
|
63
|
+
this.config = config;
|
|
64
|
+
this.session = session;
|
|
65
|
+
this.ui = ui;
|
|
66
|
+
this.permissions = permissions;
|
|
67
|
+
this.cwd = cwd;
|
|
68
|
+
this.depth = depth;
|
|
69
|
+
this.label = label;
|
|
70
|
+
this.toolFilter = toolFilter;
|
|
71
|
+
this.checkpoints = checkpoints;
|
|
72
|
+
this.hooks = hooks;
|
|
73
|
+
this.notes = []; // things to tell the model with the next message (e.g. an undo)
|
|
74
|
+
this.usage = usage ?? new Usage();
|
|
75
|
+
// The system prompt is built once and then frozen: changing it mid-session
|
|
76
|
+
// invalidates the prompt cache (and, on Claude, earlier thinking blocks).
|
|
77
|
+
this.systemPrompt = null;
|
|
78
|
+
this.abort = null;
|
|
79
|
+
this.todos = [];
|
|
80
|
+
this.toolCount = 0;
|
|
81
|
+
this.lastError = null;
|
|
82
|
+
this.changedFiles = new Set(); // files edited since the last project check
|
|
83
|
+
this.checkRounds = 0;
|
|
84
|
+
this.contextMark = null; // exact token count from the last API response
|
|
85
|
+
this.agentDefs = new Map(); // custom sub-agents (.leto/agents/*.md)
|
|
86
|
+
this.orchestrator = null; // { brain, team } when orchestrator mode is on
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
get busy() {
|
|
90
|
+
return this.abort !== null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get silent() {
|
|
94
|
+
return this.depth > 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
allowsTool(name) {
|
|
98
|
+
if (policyDisablesTool(name)) return false;
|
|
99
|
+
// Sub-agents don't spawn sub-agents, keep the task list, or share the one browser.
|
|
100
|
+
if (this.depth > 0 && (name === 'task' || name === 'todo_write' || name === 'browser' || name === 'leto' || name === 'ask_user' || name === 'memory')) return false;
|
|
101
|
+
return this.toolFilter ? this.toolFilter(name) : true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interrupt() {
|
|
105
|
+
if (!this.abort) return;
|
|
106
|
+
this.abort.abort();
|
|
107
|
+
this.ui.cancelRead();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Run one user turn to completion. Returns true on success.
|
|
111
|
+
async send(input, { parentSignal } = {}) {
|
|
112
|
+
let content = input;
|
|
113
|
+
if (this.depth === 0 && this.hooks) {
|
|
114
|
+
const text = typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '';
|
|
115
|
+
const hook = await this.hooks.run('UserPromptSubmit', { prompt: text, sessionId: this.session.id });
|
|
116
|
+
if (hook.blocked) {
|
|
117
|
+
this.ui.error(`Message blocked by a hook: ${hook.reason}`);
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
if (hook.output) this.notes.push(`<hook-context>\n${hook.output}\n</hook-context>`);
|
|
121
|
+
}
|
|
122
|
+
if (this.notes.length) {
|
|
123
|
+
const note = this.notes.splice(0).join('\n');
|
|
124
|
+
content = typeof input === 'string' ? `${input}\n\n${note}` : [...input, { type: 'text', text: note }];
|
|
125
|
+
}
|
|
126
|
+
this.session.add({ role: 'user', content });
|
|
127
|
+
if (this.depth === 0) this.checkpoints?.beginTurn(typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '(message)', this.session.messages.length - 1);
|
|
128
|
+
this.checkRounds = 0;
|
|
129
|
+
this.abort = new AbortController();
|
|
130
|
+
const signal = this.abort.signal;
|
|
131
|
+
const onParentAbort = () => this.abort?.abort();
|
|
132
|
+
parentSignal?.addEventListener('abort', onParentAbort, { once: true });
|
|
133
|
+
if (!this.silent) this.ui.setBusy(true);
|
|
134
|
+
try {
|
|
135
|
+
const limit = this.depth > 0 ? MAX_SUB_STEPS : MAX_STEPS;
|
|
136
|
+
for (let step = 0; step < limit; step++) {
|
|
137
|
+
// The model can ask to compact (leto tool); it happens here, between steps.
|
|
138
|
+
if (this.pendingCompact != null) {
|
|
139
|
+
const focus = this.pendingCompact;
|
|
140
|
+
this.pendingCompact = null;
|
|
141
|
+
await this.maybeCompact(signal, true, focus);
|
|
142
|
+
} else await this.maybeCompact(signal);
|
|
143
|
+
const msg = await this.callModelWithRetry(signal);
|
|
144
|
+
if (this.depth === 0 && this.budget && this.usage.cost >= this.budget) {
|
|
145
|
+
this.lastError = 'Budget reached.';
|
|
146
|
+
this.ui.error(`Budget reached: about $${this.usage.cost.toFixed(2)} of your $${this.budget.toFixed(2)} limit. Raise it with /budget <dollars>, or /budget off.`);
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
if (!msg.tool_calls?.length) {
|
|
150
|
+
if (await this.runProjectCheck(signal)) continue;
|
|
151
|
+
if (this.depth === 0 && this.hooks) await this.hooks.run('Stop', { sessionId: this.session.id });
|
|
152
|
+
if (this.depth === 0) this.warnContext();
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
await this.runTools(msg.tool_calls, signal);
|
|
156
|
+
if (signal.aborted) throw new DOMException('Interrupted', 'AbortError');
|
|
157
|
+
}
|
|
158
|
+
this.lastError = `Stopped after ${limit} steps.`;
|
|
159
|
+
if (!this.silent) this.ui.error(this.lastError);
|
|
160
|
+
return false;
|
|
161
|
+
} catch (err) {
|
|
162
|
+
this.lastError = err.name === 'AbortError' ? 'Interrupted.' : err.message;
|
|
163
|
+
if (this.silent) return false;
|
|
164
|
+
if (err.name === 'AbortError') this.ui.info('Interrupted. Tell leto what to do differently, or keep going.');
|
|
165
|
+
else if (err.status === 401 || err.status === 403) this.ui.error(`${err.message}\nYour API key was rejected. Run /provider to update it.`);
|
|
166
|
+
else if (err.status === 404) this.ui.error(`${err.message}\nThe model may not exist for this provider. Pick another with /model.`);
|
|
167
|
+
else this.ui.error(err.message);
|
|
168
|
+
return false;
|
|
169
|
+
} finally {
|
|
170
|
+
parentSignal?.removeEventListener('abort', onParentAbort);
|
|
171
|
+
if (this.depth === 0) this.checkpoints?.endTurn();
|
|
172
|
+
if (!this.silent) {
|
|
173
|
+
this.ui.stopSpinner();
|
|
174
|
+
this.ui.endText();
|
|
175
|
+
this.ui.setBusy(false);
|
|
176
|
+
}
|
|
177
|
+
this.abort = null;
|
|
178
|
+
this.session.repair();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async runTools(calls, signal) {
|
|
183
|
+
const ctx = {
|
|
184
|
+
cwd: this.cwd,
|
|
185
|
+
signal,
|
|
186
|
+
ui: this.ui,
|
|
187
|
+
permissions: this.permissions,
|
|
188
|
+
agent: this,
|
|
189
|
+
depth: this.depth,
|
|
190
|
+
label: this.label,
|
|
191
|
+
allowed: (name) => this.allowsTool(name),
|
|
192
|
+
checkpoints: this.checkpoints,
|
|
193
|
+
hooks: this.hooks,
|
|
194
|
+
sessionId: this.session.id,
|
|
195
|
+
ide: this.depth === 0 && this.ide?.connected ? this.ide : null,
|
|
196
|
+
};
|
|
197
|
+
this.toolCount += calls.length;
|
|
198
|
+
const parallel = calls.length > 1 && calls.every((c) => PARALLEL_SAFE.has(c.function?.name));
|
|
199
|
+
let results;
|
|
200
|
+
if (parallel) {
|
|
201
|
+
results = await Promise.all(calls.map((call) => executeToolCall(call, ctx)));
|
|
202
|
+
} else {
|
|
203
|
+
results = [];
|
|
204
|
+
for (const call of calls) {
|
|
205
|
+
results.push(signal.aborted ? 'Interrupted by the user before this tool ran.' : await executeToolCall(call, ctx));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (!this.silent) this.ui.stopSpinner();
|
|
209
|
+
// A background process that ended is news: tell the model with these results.
|
|
210
|
+
const exits = this.depth === 0 ? unreportedExits() : [];
|
|
211
|
+
if (exits.length) {
|
|
212
|
+
const k = results.length - 1;
|
|
213
|
+
const note = `\n\n${exits.join('\n')}`;
|
|
214
|
+
results[k] = typeof results[k] === 'object' && results[k] ? { ...results[k], text: results[k].text + note } : `${results[k]}${note}`;
|
|
215
|
+
}
|
|
216
|
+
calls.forEach((call, i) => {
|
|
217
|
+
const r = results[i];
|
|
218
|
+
if (r && typeof r === 'object') this.session.add({ role: 'tool', tool_call_id: call.id, content: r.text, ...(r.images ? { images: r.images } : {}), ...(r.documents ? { documents: r.documents } : {}) });
|
|
219
|
+
else this.session.add({ role: 'tool', tool_call_id: call.id, content: r });
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async runSubagent({ description = 'sub-task', prompt, agent_type = 'explore', isolation = 'none', worker }, signal) {
|
|
224
|
+
if (!prompt) throw new Error('prompt is required');
|
|
225
|
+
let member = null;
|
|
226
|
+
if (worker) {
|
|
227
|
+
member = this.orchestrator?.team.find((m) => m.name === worker);
|
|
228
|
+
if (!member) throw new Error(this.orchestrator ? `No team member "${worker}". Team: ${this.orchestrator.team.map((m) => m.name).join(', ')}` : 'worker is only available in orchestrator mode.');
|
|
229
|
+
}
|
|
230
|
+
const memberConfig = member ? workerConfig(member, this.config) : null;
|
|
231
|
+
const def = this.agentDefs.get(agent_type);
|
|
232
|
+
if (!def && !['explore', 'general'].includes(agent_type)) {
|
|
233
|
+
throw new Error(`Unknown agent_type "${agent_type}". Available: explore, general${[...this.agentDefs.keys()].map((k) => `, ${k}`).join('')}`);
|
|
234
|
+
}
|
|
235
|
+
const readOnly = def ? def.tools?.every((t) => READ_ONLY_TOOLS.has(t)) ?? false : agent_type !== 'general';
|
|
236
|
+
let toolFilter = readOnly && !def ? (name) => READ_ONLY_TOOLS.has(name) : null;
|
|
237
|
+
if (def?.tools) toolFilter = (name) => def.tools.includes(name) || def.tools.some((t) => t.endsWith('*') && name.startsWith(t.slice(0, -1)));
|
|
238
|
+
const model = def?.model && def.model !== 'inherit' ? def.model : this.config.subagentModel || this.config.model;
|
|
239
|
+
// A worktree gives an agent that edits its own checkout and branch.
|
|
240
|
+
let wt = null;
|
|
241
|
+
if (isolation === 'worktree') {
|
|
242
|
+
if (readOnly) throw new Error('isolation "worktree" is for agents that change files; read-only agents share the working copy.');
|
|
243
|
+
wt = createWorktree(this.cwd, description);
|
|
244
|
+
}
|
|
245
|
+
const sub = new Agent({
|
|
246
|
+
config: memberConfig ?? { ...this.config, model },
|
|
247
|
+
session: Session.memory(),
|
|
248
|
+
ui: this.ui,
|
|
249
|
+
permissions: this.permissions,
|
|
250
|
+
cwd: wt ? wt.workDir : this.cwd,
|
|
251
|
+
depth: this.depth + 1,
|
|
252
|
+
label: member ? `${member.name}: ${description}` : description,
|
|
253
|
+
toolFilter,
|
|
254
|
+
checkpoints: wt ? null : this.checkpoints,
|
|
255
|
+
hooks: this.hooks,
|
|
256
|
+
usage: this.usage,
|
|
257
|
+
});
|
|
258
|
+
sub.subagentType = def ? 'custom' : readOnly ? 'explore' : 'general';
|
|
259
|
+
sub.agentDef = def ?? null;
|
|
260
|
+
sub.worktree = wt;
|
|
261
|
+
const started = Date.now();
|
|
262
|
+
const costBefore = this.usage.cost;
|
|
263
|
+
let ok;
|
|
264
|
+
try {
|
|
265
|
+
ok = await sub.send(prompt, { parentSignal: signal });
|
|
266
|
+
} finally {
|
|
267
|
+
if (wt) wt.result = finishWorktree(wt, description);
|
|
268
|
+
}
|
|
269
|
+
const secs = Math.round((Date.now() - started) / 1000);
|
|
270
|
+
let report = [...sub.session.messages].reverse().find((m) => m.role === 'assistant' && m.content)?.content ?? '';
|
|
271
|
+
const spent = this.usage.cost - costBefore;
|
|
272
|
+
const stats = `${member ? `${member.model} · ` : ''}${sub.toolCount} tool use${sub.toolCount === 1 ? '' : 's'} · ${secs}s${member && spent > 0 ? ` · ${formatCost(spent)}` : ''}`;
|
|
273
|
+
let display = `${member ? `${member.name}: ` : ''}${description}: ${ok ? 'done' : `stopped, ${sub.lastError}`} (${stats})`;
|
|
274
|
+
if (member) report = `[Report from ${member.name} (${member.model})]\n${report}`;
|
|
275
|
+
if (wt) {
|
|
276
|
+
report += `\n\n[Worktree] ${wt.result.summary}${wt.result.stat ? `\n${wt.result.stat}` : ''}`;
|
|
277
|
+
if (wt.result.branch) display += ` → ${wt.result.branch}`;
|
|
278
|
+
}
|
|
279
|
+
if (!ok) return { content: `Sub-agent "${description}" did not finish: ${sub.lastError}\n\nPartial report:\n${report || '(none)'}`, display };
|
|
280
|
+
return { content: report || '(The sub-agent returned no report.)', display };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Turn plan mode on or off. Told to the model as a note on the next message,
|
|
284
|
+
// so the system prompt (and the prompt cache) stays unchanged.
|
|
285
|
+
setPlanMode(on) {
|
|
286
|
+
if (this.permissions.planMode === on) return;
|
|
287
|
+
this.permissions.planMode = on;
|
|
288
|
+
this.notes.push(
|
|
289
|
+
on
|
|
290
|
+
? '[Plan mode is ON. The user wants a plan before any changes. Investigate with read-only tools (read_file, grep, list_files, web_fetch, explore sub-agents). Do not edit files or run commands; those tools are blocked. Then present a concise, concrete plan: files to change, what changes, how you will verify it, and stop.]'
|
|
291
|
+
: '[Plan mode is OFF. You may make changes now.]',
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
get system() {
|
|
296
|
+
this.systemPrompt ??= buildSystemPrompt({
|
|
297
|
+
cwd: this.cwd,
|
|
298
|
+
model: this.config.model,
|
|
299
|
+
subagent: this.depth > 0 ? { type: this.subagentType, def: this.agentDef, worktree: this.worktree } : null,
|
|
300
|
+
agents: this.depth === 0 ? [...this.agentDefs.values()] : [],
|
|
301
|
+
sandbox: this.permissions.sandbox ? sandboxAvailable() : null,
|
|
302
|
+
self: this.depth === 0,
|
|
303
|
+
notes: this.depth === 0 ? readNotes(this.cwd) : [],
|
|
304
|
+
orchestrator: this.depth === 0 && this.orchestrator ? orchestratorPrompt(this.orchestrator) : null,
|
|
305
|
+
});
|
|
306
|
+
return this.systemPrompt;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Rate limits, overload and dropped connections are retried with backoff.
|
|
310
|
+
// The session only changes once a response is complete, so a retry is clean.
|
|
311
|
+
async callModelWithRetry(signal) {
|
|
312
|
+
for (let attempt = 0; ; attempt++) {
|
|
313
|
+
try {
|
|
314
|
+
return await this.callModel(signal);
|
|
315
|
+
} catch (err) {
|
|
316
|
+
if (signal.aborted || attempt >= MAX_RETRIES || !isTransient(err)) throw err;
|
|
317
|
+
const secs = Math.min(60, 2 * 2 ** attempt);
|
|
318
|
+
const why = err.status === 429 ? 'Rate limited' : err.status === 529 || /overloaded/i.test(err.message) ? 'The API is overloaded' : err.status >= 500 ? `Server error ${err.status}` : 'Connection dropped';
|
|
319
|
+
if (!this.silent) this.ui.info(` ${why}; retrying in ${secs}s (${attempt + 1}/${MAX_RETRIES})`);
|
|
320
|
+
await wait(secs * 1000, signal);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// Before a turn ends, run the project's check command if files changed.
|
|
326
|
+
// A failure goes back to the model, which keeps working.
|
|
327
|
+
async runProjectCheck(signal) {
|
|
328
|
+
const cmd = this.config.checkCommand;
|
|
329
|
+
if (!cmd || this.depth > 0 || !this.changedFiles.size) return false;
|
|
330
|
+
this.changedFiles.clear();
|
|
331
|
+
if (this.checkRounds >= MAX_CHECK_ROUNDS) {
|
|
332
|
+
this.ui.info(` The check still fails after ${MAX_CHECK_ROUNDS} rounds of fixes; stopping here so you can look.`);
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
this.checkRounds++;
|
|
336
|
+
this.ui.toolStart('check', cmd);
|
|
337
|
+
this.ui.startSpinner('Checking');
|
|
338
|
+
const started = Date.now();
|
|
339
|
+
const r = await runCheck(cmd, { cwd: this.cwd, signal });
|
|
340
|
+
this.ui.stopSpinner();
|
|
341
|
+
if (signal.aborted) throw new DOMException('Interrupted', 'AbortError');
|
|
342
|
+
const secs = ((Date.now() - started) / 1000).toFixed(1);
|
|
343
|
+
if (r.ok) {
|
|
344
|
+
this.ui.toolResult(`passed · ${secs}s`, false);
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
const why = r.timedOut ? 'timed out' : `exit code ${r.code}`;
|
|
348
|
+
const errors = condense(r.output);
|
|
349
|
+
this.ui.toolResult(`failed (${why}) · ${secs}s · sending the errors back`, true, { lines: errors.split('\n').slice(-6).map((text) => ({ sign: ' ', text })) });
|
|
350
|
+
this.session.add({
|
|
351
|
+
role: 'user',
|
|
352
|
+
content: `<check command="${cmd}">\n${errors || '(no output)'}\n</check>\n\n[Automatic check: \`${cmd}\` failed (${why}) after your changes. Fix what your changes broke, then finish. If a failure was already there before your changes and is unrelated, say so instead of fixing it.]`,
|
|
353
|
+
});
|
|
354
|
+
return true;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Context used, in tokens: exact from the last response, plus an estimate
|
|
358
|
+
// for messages added since.
|
|
359
|
+
contextTokens() {
|
|
360
|
+
const msgs = this.session.messages;
|
|
361
|
+
const m = this.contextMark;
|
|
362
|
+
if (m && m.count <= msgs.length && msgs[m.count - 1] === m.ref) return m.tokens + estimateTokens(msgs.slice(m.count));
|
|
363
|
+
return estimateTokens(msgs);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
markContext(u) {
|
|
367
|
+
if (!u) return;
|
|
368
|
+
const tokens = (u.input_tokens ?? u.prompt_tokens ?? 0) + (u.input_tokens != null ? (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : 0) + (u.output_tokens ?? u.completion_tokens ?? 0);
|
|
369
|
+
if (!tokens) return;
|
|
370
|
+
const msgs = this.session.messages;
|
|
371
|
+
this.contextMark = { tokens, count: msgs.length, ref: msgs.at(-1) };
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
async callModel(signal) {
|
|
375
|
+
const history = [{ role: 'system', content: this.system }, ...this.session.messages];
|
|
376
|
+
const tools = toolSchemas((n) => this.allowsTool(n));
|
|
377
|
+
if (!this.silent) {
|
|
378
|
+
this.ui.startResponse();
|
|
379
|
+
this.ui.startSpinner();
|
|
380
|
+
}
|
|
381
|
+
try {
|
|
382
|
+
return isNativeAnthropic(this.config) ? await this.callAnthropic(history, tools, signal) : await this.callOpenAI(history, tools, signal);
|
|
383
|
+
} finally {
|
|
384
|
+
if (!this.silent) this.ui.endText();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async callAnthropic(history, tools, signal) {
|
|
389
|
+
let final = null;
|
|
390
|
+
for await (const ev of streamAnthropic({ config: this.config, history, tools, signal })) {
|
|
391
|
+
if (ev.type === 'done') final = ev.message;
|
|
392
|
+
if (this.silent) continue;
|
|
393
|
+
if (ev.type === 'text') this.ui.text(ev.text);
|
|
394
|
+
else if (ev.type === 'thinking') this.ui.thinking(ev.text);
|
|
395
|
+
else if (ev.type === 'tool') this.ui.toolPending?.(ev.name);
|
|
396
|
+
else if (ev.type === 'tool_input') this.ui.addTokens?.(ev.text.length / 4);
|
|
397
|
+
else if (ev.type === 'retry') this.ui.info(' (Claude sent a malformed tool call; retrying)');
|
|
398
|
+
}
|
|
399
|
+
this.usage.add(final.model ?? this.config.model, final.usage);
|
|
400
|
+
let blocks = final.content ?? [];
|
|
401
|
+
if (blocks.some((b) => b.type === 'compaction') && !this.silent) this.ui.info(' Claude summarized the earlier conversation to free up context.');
|
|
402
|
+
const text = blocks.filter((b) => b.type === 'text').map((b) => b.text).join('');
|
|
403
|
+
let toolUses = blocks.filter((b) => b.type === 'tool_use');
|
|
404
|
+
// Never run a tool call that was cut off or declined part-way.
|
|
405
|
+
if (final.stop_reason === 'refusal' || (final.stop_reason === 'max_tokens' && toolUses.length)) {
|
|
406
|
+
blocks = blocks.filter((b) => b.type !== 'tool_use');
|
|
407
|
+
toolUses = [];
|
|
408
|
+
const why = final.stop_reason === 'refusal'
|
|
409
|
+
? `Claude declined to continue${final.stop_details?.category ? ` (${final.stop_details.category})` : ''}. Try rephrasing the request.`
|
|
410
|
+
: 'The response hit the output limit in the middle of a tool call. Ask for smaller steps, or raise it with: leto config set maxTokens 128000';
|
|
411
|
+
this.lastError = why;
|
|
412
|
+
if (!this.silent) this.ui.error(why);
|
|
413
|
+
}
|
|
414
|
+
const msg = { role: 'assistant', content: text || (toolUses.length ? null : ''), anthropic: blocks };
|
|
415
|
+
if (toolUses.length) {
|
|
416
|
+
msg.tool_calls = toolUses.map((b) => ({ id: b.id, type: 'function', function: { name: b.name, arguments: JSON.stringify(b.input ?? {}) } }));
|
|
417
|
+
}
|
|
418
|
+
this.session.add(msg);
|
|
419
|
+
this.markContext(final.usage);
|
|
420
|
+
return msg;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
async callOpenAI(history, tools, signal) {
|
|
424
|
+
const textMode = this.config.toolMode === 'text';
|
|
425
|
+
const names = new Set(tools.map((t) => t.function.name));
|
|
426
|
+
if (textMode) history = toTextHistory(history, tools);
|
|
427
|
+
// OpenAI-style APIs only take text in tool messages, so images from a run
|
|
428
|
+
// of tool results go in one user message right after that run.
|
|
429
|
+
const messages = [];
|
|
430
|
+
let pending = [];
|
|
431
|
+
const flush = () => {
|
|
432
|
+
if (!pending.length) return;
|
|
433
|
+
messages.push({ role: 'user', content: [{ type: 'text', text: '(Images returned by the tool calls above.)' }, ...pending.map((url) => ({ type: 'image_url', image_url: { url } }))] });
|
|
434
|
+
pending = [];
|
|
435
|
+
};
|
|
436
|
+
for (const m of history) {
|
|
437
|
+
if (m.role === 'tool') {
|
|
438
|
+
const { images, documents, ...rest } = m;
|
|
439
|
+
messages.push(rest);
|
|
440
|
+
if (images?.length) pending.push(...images);
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
flush();
|
|
444
|
+
messages.push(m);
|
|
445
|
+
}
|
|
446
|
+
flush();
|
|
447
|
+
let content = '';
|
|
448
|
+
const calls = [];
|
|
449
|
+
let lastUsage = null;
|
|
450
|
+
// Tool-call markup written as text is hidden from the screen as it streams.
|
|
451
|
+
const filter = new MarkupFilter((s) => {
|
|
452
|
+
if (!this.silent) this.ui.text(s);
|
|
453
|
+
});
|
|
454
|
+
for await (const event of streamChat({ config: this.config, messages, tools: textMode ? [] : tools, signal })) {
|
|
455
|
+
if (event.usage) {
|
|
456
|
+
this.usage.add(this.config.model, event.usage);
|
|
457
|
+
lastUsage = event.usage;
|
|
458
|
+
}
|
|
459
|
+
const delta = event.choices?.[0]?.delta;
|
|
460
|
+
if (!delta) continue;
|
|
461
|
+
const reasoning = delta.reasoning_content ?? delta.reasoning;
|
|
462
|
+
if (reasoning && !this.silent) this.ui.thinking(reasoning);
|
|
463
|
+
if (delta.content) {
|
|
464
|
+
content += delta.content;
|
|
465
|
+
filter.push(delta.content);
|
|
466
|
+
}
|
|
467
|
+
for (const tc of delta.tool_calls ?? []) {
|
|
468
|
+
const idx = tc.index ?? (tc.id ? calls.length : Math.max(0, calls.length - 1));
|
|
469
|
+
const c = (calls[idx] ??= { id: '', type: 'function', function: { name: '', arguments: '' } });
|
|
470
|
+
if (tc.id) c.id = tc.id;
|
|
471
|
+
if (tc.function?.name && !c.function.name) {
|
|
472
|
+
c.function.name = tc.function.name;
|
|
473
|
+
if (!this.silent) this.ui.toolPending?.(tc.function.name);
|
|
474
|
+
}
|
|
475
|
+
if (tc.function?.arguments) {
|
|
476
|
+
c.function.arguments += tc.function.arguments;
|
|
477
|
+
if (!this.silent) this.ui.addTokens?.(tc.function.arguments.length / 4);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
filter.end();
|
|
482
|
+
let toolCalls = calls.filter(Boolean).map((c, i) => ({ ...c, id: c.id || `call_${Date.now()}_${i}` }));
|
|
483
|
+
// No tool calls in the API field: look for ones the model wrote as text.
|
|
484
|
+
if (!toolCalls.length && names.size && content) {
|
|
485
|
+
const parsed = parseToolCalls(content, names);
|
|
486
|
+
if (parsed.calls.length) {
|
|
487
|
+
toolCalls = parsed.calls;
|
|
488
|
+
content = parsed.text;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
const msg = { role: 'assistant', content: content || (toolCalls.length ? null : '') };
|
|
492
|
+
if (toolCalls.length) msg.tool_calls = toolCalls;
|
|
493
|
+
this.session.add(msg);
|
|
494
|
+
this.markContext(lastUsage);
|
|
495
|
+
return msg;
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
complete(messages, signal) {
|
|
499
|
+
return isNativeAnthropic(this.config) ? completeAnthropic({ config: this.config, messages, signal }) : completeText({ config: this.config, messages, signal });
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Once per session, say when the context is getting full.
|
|
503
|
+
warnContext() {
|
|
504
|
+
const used = this.contextTokens() / this.config.contextWindow;
|
|
505
|
+
if (used >= 0.65 && !this.warnedContext) {
|
|
506
|
+
this.warnedContext = true;
|
|
507
|
+
this.ui.info(` Context is ${Math.round(used * 100)}% full. At 80% leto summarizes older turns automatically; run /compact <what to keep> to do it now and choose what matters.`);
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
async maybeCompact(signal, force = false, focus = '') {
|
|
512
|
+
const messages = this.session.messages;
|
|
513
|
+
if (!force && this.contextTokens() < this.config.contextWindow * COMPACT_AT) return false;
|
|
514
|
+
// Claude compacts on its side for these models; only /compact asks leto to do it.
|
|
515
|
+
if (!force && serverCompaction(this.config)) return false;
|
|
516
|
+
// Cut at a user message so tool calls stay paired with their results.
|
|
517
|
+
const keep = force ? 2 : KEEP_RECENT;
|
|
518
|
+
let cut = -1;
|
|
519
|
+
for (let i = messages.length - 1; i > 0; i--) {
|
|
520
|
+
if (messages[i].role === 'user' && messages.length - i >= Math.min(keep, messages.length - 1)) {
|
|
521
|
+
cut = i;
|
|
522
|
+
break;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (cut <= 0) {
|
|
526
|
+
for (let i = messages.length - 1; i > 0; i--) if (messages[i].role === 'user') { cut = i; break; }
|
|
527
|
+
}
|
|
528
|
+
if (cut <= 0) return this.trimToolResults();
|
|
529
|
+
if (!this.silent) this.ui.info('Compacting conversation history to free up context…');
|
|
530
|
+
const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
|
|
531
|
+
const summary = await this.complete(
|
|
532
|
+
[
|
|
533
|
+
{ role: 'system', content: 'You summarize coding-agent conversations so the work can continue with less context.' },
|
|
534
|
+
{
|
|
535
|
+
role: 'user',
|
|
536
|
+
content: `Summarize this conversation between a user and a coding agent. Keep: the user's goals and instructions, decisions made, files read or changed (with paths), commands run and their important results, errors hit, the current task list, and what is left to do. Be specific and concise.${focus ? `\n\nThe user asked you to make sure the summary keeps: ${focus}` : ''}${this.todos.length ? `\n\nCurrent task list:\n${this.todos.map((t) => `- [${t.status}] ${t.content}`).join('\n')}` : ''}\n\n<conversation>\n${truncate(transcript, 400000)}\n</conversation>`,
|
|
537
|
+
},
|
|
538
|
+
],
|
|
539
|
+
signal,
|
|
540
|
+
);
|
|
541
|
+
this.session.compact(summary.trim() || '(no summary produced)', cut);
|
|
542
|
+
this.warnedContext = false;
|
|
543
|
+
if (estimateTokens(this.session.messages) >= this.config.contextWindow * COMPACT_AT) this.trimToolResults();
|
|
544
|
+
return true;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// One long turn with no user message to cut at: shorten old tool results.
|
|
548
|
+
trimToolResults() {
|
|
549
|
+
const messages = this.session.messages;
|
|
550
|
+
const recent = Math.max(0, messages.length - 8);
|
|
551
|
+
let changed = false;
|
|
552
|
+
const next = messages.map((m, i) => {
|
|
553
|
+
if (i < recent && m.role === 'tool' && typeof m.content === 'string' && m.content.length > 600) {
|
|
554
|
+
changed = true;
|
|
555
|
+
return { ...m, content: `${m.content.slice(0, 500)}\n… [older tool output trimmed to save context; re-run the tool if you need it]` };
|
|
556
|
+
}
|
|
557
|
+
return m;
|
|
558
|
+
});
|
|
559
|
+
if (changed) {
|
|
560
|
+
this.session.replace(next);
|
|
561
|
+
if (!this.silent) this.ui.info('Trimmed old tool output to free up context.');
|
|
562
|
+
}
|
|
563
|
+
return changed;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function renderForSummary(m) {
|
|
568
|
+
if (m.role === 'tool') return `[tool result]\n${truncate(String(m.content ?? ''), 2000)}`;
|
|
569
|
+
let s = `[${m.role}]\n${textOf(m.content)}`;
|
|
570
|
+
for (const c of m.tool_calls ?? []) s += `\n(called ${c.function.name} ${truncate(c.function.arguments, 1000)})`;
|
|
571
|
+
return s;
|
|
572
|
+
}
|
package/src/agents.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// Custom sub-agents: named specialists the main agent can hand work to.
|
|
2
|
+
// Each is a markdown file with frontmatter; the body is its instructions.
|
|
3
|
+
//
|
|
4
|
+
// ---
|
|
5
|
+
// name: reviewer
|
|
6
|
+
// description: Reviews a diff for bugs and risky changes. Use after making changes.
|
|
7
|
+
// tools: read_file, grep, list_files, bash (optional; default: all tools)
|
|
8
|
+
// model: claude-haiku-5-5 (optional; default: subagentModel or the main model)
|
|
9
|
+
// ---
|
|
10
|
+
// You are a careful code reviewer…
|
|
11
|
+
//
|
|
12
|
+
// Found in ~/.leto/agents and ~/.claude/agents (yours), and
|
|
13
|
+
// .leto/agents and .claude/agents in the project (trusted folders only).
|
|
14
|
+
import fs from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import { HOME_DIR } from './config.js';
|
|
18
|
+
import { parseSkill } from './skills.js';
|
|
19
|
+
import { pluginDirs } from './plugins.js';
|
|
20
|
+
import { policyDisablesPlugins } from './policy.js';
|
|
21
|
+
import { projectDir } from './legacy.js';
|
|
22
|
+
|
|
23
|
+
export function agentDirs(cwd) {
|
|
24
|
+
return {
|
|
25
|
+
user: [path.join(HOME_DIR, 'agents'), path.join(os.homedir(), '.claude', 'agents'), ...(policyDisablesPlugins() ? [] : pluginDirs('agents'))],
|
|
26
|
+
project: [path.join(projectDir(cwd), 'agents'), path.join(cwd, '.claude', 'agents')],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function loadAgents(cwd, { includeProject = true } = {}) {
|
|
31
|
+
const { user, project } = agentDirs(cwd);
|
|
32
|
+
const out = new Map();
|
|
33
|
+
for (const [dirs, source] of [[user, 'user'], [includeProject ? project : [], 'project']]) {
|
|
34
|
+
for (const dir of dirs) {
|
|
35
|
+
let files = [];
|
|
36
|
+
try {
|
|
37
|
+
files = fs.readdirSync(dir).filter((f) => f.endsWith('.md'));
|
|
38
|
+
} catch {
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
for (const f of files) {
|
|
42
|
+
try {
|
|
43
|
+
const file = path.join(dir, f);
|
|
44
|
+
const { meta, body } = parseSkill(fs.readFileSync(file, 'utf8'));
|
|
45
|
+
const name = (meta.name || f.slice(0, -3)).toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
|
|
46
|
+
if (['explore', 'general'].includes(name)) continue;
|
|
47
|
+
const tools = meta.tools ? meta.tools.split(/[,\s]+/).map((t) => t.trim()).filter(Boolean) : null;
|
|
48
|
+
out.set(name, { name, description: meta.description || '(no description)', tools, model: meta.model || '', prompt: body, file, source });
|
|
49
|
+
} catch {}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return [...out.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function createAgent({ name, description, where = 'project', cwd }) {
|
|
57
|
+
const slug = String(name).toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-|-$/g, '');
|
|
58
|
+
if (!slug) throw new Error('An agent needs a name.');
|
|
59
|
+
const dir = where === 'user' ? path.join(HOME_DIR, 'agents') : path.join(projectDir(cwd), 'agents');
|
|
60
|
+
const file = path.join(dir, `${slug}.md`);
|
|
61
|
+
if (fs.existsSync(file)) throw new Error(`An agent named "${slug}" already exists at ${file}.`);
|
|
62
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
63
|
+
fs.writeFileSync(
|
|
64
|
+
file,
|
|
65
|
+
`---\nname: ${slug}\ndescription: ${description || 'Say what this agent does and when to use it.'}\n# tools: read_file, grep, list_files, repo_map, bash\n# model: claude-haiku-5-5\n---\n\nYou are ${slug}, a specialist sub-agent.\n\nDescribe how it should work and what it should report back.\n`,
|
|
66
|
+
);
|
|
67
|
+
return file;
|
|
68
|
+
}
|