@mumbrane/leto 0.0.0-stage → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/serve.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
// `leto serve`: one long-lived session for another program to drive, such as the
|
|
2
|
+
// Leto desktop app. It reads commands from stdin and writes events to stdout, one JSON
|
|
3
|
+
// object per line each way.
|
|
4
|
+
//
|
|
5
|
+
// In (stdin):
|
|
6
|
+
// {"type":"send","text":"…"} start a turn (an error event if one is running)
|
|
7
|
+
// {"type":"interrupt"} stop the running turn
|
|
8
|
+
// {"type":"permission","id":"p1","answer":"yes"} answer a permission_request: yes | always | no
|
|
9
|
+
// {"type":"answer","id":"q1","answer":"…"} answer a question (null or "" skips it)
|
|
10
|
+
// {"type":"set_mode","mode":"acceptEdits"} ask | acceptEdits | plan | yolo
|
|
11
|
+
// {"type":"set_model","model":"…"}
|
|
12
|
+
// {"type":"set_effort","level":"high"} low | medium | high | xhigh | max (Claude models that support it)
|
|
13
|
+
// {"type":"shutdown"} (closing stdin does the same)
|
|
14
|
+
//
|
|
15
|
+
// Out (stdout): `ready` once set up, then the events `--stream-json` prints (text, thinking,
|
|
16
|
+
// tool_start, tool_result, todos, info, error) plus `permission_request` and `question`, which
|
|
17
|
+
// carry an id to answer with, and a `result` at the end of every turn. While the model is still
|
|
18
|
+
// writing a tool call (a whole file can take a minute), `tool_pending` names the tool and
|
|
19
|
+
// `progress` reports the tokens written so far, at most four times a second.
|
|
20
|
+
import readline from 'node:readline';
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import path from 'node:path';
|
|
23
|
+
import { HOME_DIR } from './config.js';
|
|
24
|
+
import { isNativeAnthropic, modelTraits } from './anthropic.js';
|
|
25
|
+
import { EventUI, resultEvent } from './sdk.js';
|
|
26
|
+
import { buildMessage } from './input.js';
|
|
27
|
+
import { checkModel, policyForbidsYolo } from './policy.js';
|
|
28
|
+
import { closeBrowser } from './browser.js';
|
|
29
|
+
import { flushUsage } from './usage.js';
|
|
30
|
+
import { VERSION } from './version.js';
|
|
31
|
+
|
|
32
|
+
export const SERVE_MODES = ['ask', 'acceptEdits', 'plan', 'yolo'];
|
|
33
|
+
|
|
34
|
+
// An EventUI whose permission prompts and questions wait for an answer on stdin.
|
|
35
|
+
export class ServeUI extends EventUI {
|
|
36
|
+
constructor(write = (ev) => process.stdout.write(JSON.stringify(ev) + '\n')) {
|
|
37
|
+
super(write);
|
|
38
|
+
this.print = false;
|
|
39
|
+
this.pending = new Map(); // id -> resolve
|
|
40
|
+
this.seq = 0;
|
|
41
|
+
this.writing = null; // the tool call being written: { name, tokens, sent }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
toolPending(name) {
|
|
45
|
+
this.writing = { name, tokens: 0, sent: 0 };
|
|
46
|
+
this.emit({ type: 'tool_pending', name });
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
addTokens(n) {
|
|
50
|
+
const w = this.writing;
|
|
51
|
+
if (!w) return;
|
|
52
|
+
w.tokens += n;
|
|
53
|
+
const now = Date.now();
|
|
54
|
+
if (now - w.sent < 250) return;
|
|
55
|
+
w.sent = now;
|
|
56
|
+
this.emit({ type: 'progress', name: w.name, tokens: Math.round(w.tokens) });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
text(s) {
|
|
60
|
+
this.writing = null;
|
|
61
|
+
super.text(s);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
request(prefix, event) {
|
|
65
|
+
const id = `${prefix}${++this.seq}`;
|
|
66
|
+
return new Promise((resolve) => {
|
|
67
|
+
this.pending.set(id, resolve);
|
|
68
|
+
this.emit({ ...event, id });
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
resolve(id, value) {
|
|
73
|
+
const done = this.pending.get(id);
|
|
74
|
+
if (!done) return false;
|
|
75
|
+
this.pending.delete(id);
|
|
76
|
+
done(value);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// An interrupt answers every open prompt with "no".
|
|
81
|
+
cancelRead() {
|
|
82
|
+
for (const id of [...this.pending.keys()]) this.resolve(id, null);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
toolStart(tool, summary, { prefix = '', id = null, name = null, input = null } = {}) {
|
|
86
|
+
this.writing = null;
|
|
87
|
+
this.emit({ type: 'tool_start', tool, summary: String(summary ?? ''), agent: prefix || null, id, name, input });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
toolResult(result, isError = false, { id = null, lines = null, diff = null, images = null } = {}) {
|
|
91
|
+
const shown = diff ?? lines;
|
|
92
|
+
const files = (images ?? []).map((url) => saveImage(url)).filter(Boolean);
|
|
93
|
+
this.emit({ type: 'tool_result', result: String(result ?? ''), is_error: Boolean(isError), id, lines: shown?.length ? shown : null, images: files.length ? files : null });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async confirm(preview, tool, { args, prefix } = {}) {
|
|
97
|
+
const answer = await this.request('p', {
|
|
98
|
+
type: 'permission_request',
|
|
99
|
+
tool,
|
|
100
|
+
title: preview?.title ?? tool,
|
|
101
|
+
input: args ?? {},
|
|
102
|
+
lines: preview?.lines ?? [],
|
|
103
|
+
prefix: prefix ?? null,
|
|
104
|
+
once: tool === 'exit_plan_mode' || tool === 'leto',
|
|
105
|
+
});
|
|
106
|
+
return answer === 'yes' || answer === 'always' || answer === 'prefix' ? answer : 'no';
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async ask(q) {
|
|
110
|
+
const answer = await this.request('q', {
|
|
111
|
+
type: 'question',
|
|
112
|
+
question: q.question,
|
|
113
|
+
header: q.header ?? null,
|
|
114
|
+
options: q.options ?? [],
|
|
115
|
+
multi_select: Boolean(q.multiSelect),
|
|
116
|
+
});
|
|
117
|
+
if (answer == null || answer === '') return null;
|
|
118
|
+
return { answer: Array.isArray(answer) ? answer.join(', ') : String(answer) };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Images a tool returns (screenshots, pictures it read) go to files, so events stay small.
|
|
123
|
+
let imageSeq = 0;
|
|
124
|
+
export function saveImage(url) {
|
|
125
|
+
const m = /^data:image\/(png|jpe?g|gif|webp);base64,(.+)$/s.exec(String(url));
|
|
126
|
+
if (!m) return null;
|
|
127
|
+
try {
|
|
128
|
+
const dir = path.join(HOME_DIR, 'images');
|
|
129
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
130
|
+
const file = path.join(dir, `${Date.now()}-${process.pid}-${++imageSeq}.${m[1] === 'jpeg' ? 'jpg' : m[1]}`);
|
|
131
|
+
fs.writeFileSync(file, Buffer.from(m[2], 'base64'));
|
|
132
|
+
return file;
|
|
133
|
+
} catch {
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'];
|
|
139
|
+
|
|
140
|
+
export function setEffort(agent, level) {
|
|
141
|
+
if (!EFFORTS.includes(level)) throw new Error(`effort must be one of: ${EFFORTS.join(', ')}`);
|
|
142
|
+
const cfg = agent.config;
|
|
143
|
+
if (!isNativeAnthropic(cfg) || !modelTraits(cfg.model).effort) throw new Error(`Effort can't be set for ${cfg.model}.`);
|
|
144
|
+
cfg.effort = level;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function setMode(agent, mode) {
|
|
148
|
+
if (!SERVE_MODES.includes(mode)) throw new Error(`mode must be one of: ${SERVE_MODES.join(', ')}`);
|
|
149
|
+
if (mode === 'yolo' && policyForbidsYolo()) throw new Error("yolo is turned off by your organization's leto policy.");
|
|
150
|
+
const p = agent.permissions;
|
|
151
|
+
p.mode = mode === 'yolo' ? 'yolo' : 'ask';
|
|
152
|
+
p.acceptEdits = mode === 'acceptEdits';
|
|
153
|
+
if (Boolean(p.planMode) !== (mode === 'plan')) agent.setPlanMode(mode === 'plan');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Runs the session until stdin closes or a shutdown arrives.
|
|
157
|
+
export async function serve({ agent, ui, cwd, mcpServers = [], mode = 'ask' }) {
|
|
158
|
+
const emit = (ev) => ui.emit(ev);
|
|
159
|
+
setMode(agent, mode);
|
|
160
|
+
let turn = null;
|
|
161
|
+
|
|
162
|
+
const runTurn = async (text) => {
|
|
163
|
+
const started = Date.now();
|
|
164
|
+
const { content, errors } = buildMessage(text, cwd);
|
|
165
|
+
for (const e of errors) ui.error(e);
|
|
166
|
+
let ok = false;
|
|
167
|
+
try {
|
|
168
|
+
ok = await agent.send(content);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
ui.error(err.message);
|
|
171
|
+
}
|
|
172
|
+
emit(resultEvent(agent, ok, { started }));
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
const handle = (msg) => {
|
|
176
|
+
switch (msg.type) {
|
|
177
|
+
case 'send': {
|
|
178
|
+
if (turn) return ui.error('A turn is already running; interrupt it or wait for its result.');
|
|
179
|
+
const text = String(msg.text ?? '').trim();
|
|
180
|
+
if (!text) return ui.error('send needs text.');
|
|
181
|
+
turn = runTurn(text).finally(() => (turn = null));
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
case 'interrupt':
|
|
185
|
+
ui.cancelRead();
|
|
186
|
+
return agent.interrupt();
|
|
187
|
+
case 'permission':
|
|
188
|
+
case 'answer':
|
|
189
|
+
if (!ui.resolve(String(msg.id), msg.answer ?? null)) ui.error(`Nothing is waiting on ${msg.id}.`);
|
|
190
|
+
return;
|
|
191
|
+
case 'set_mode':
|
|
192
|
+
setMode(agent, msg.mode);
|
|
193
|
+
return emit({ type: 'mode', mode: msg.mode });
|
|
194
|
+
case 'set_effort':
|
|
195
|
+
setEffort(agent, String(msg.level));
|
|
196
|
+
return emit({ type: 'effort', level: agent.config.effort });
|
|
197
|
+
case 'set_model':
|
|
198
|
+
checkModel(String(msg.model));
|
|
199
|
+
agent.config.model = String(msg.model);
|
|
200
|
+
return emit({ type: 'model', model: agent.config.model });
|
|
201
|
+
default:
|
|
202
|
+
return ui.error(`Unknown command type "${msg.type}".`);
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
|
|
206
|
+
emit({ type: 'ready', version: VERSION, session_id: agent.session.id, model: agent.config.model, cwd, mode });
|
|
207
|
+
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
208
|
+
for await (const line of rl) {
|
|
209
|
+
if (!line.trim()) continue;
|
|
210
|
+
let msg;
|
|
211
|
+
try {
|
|
212
|
+
msg = JSON.parse(line);
|
|
213
|
+
} catch {
|
|
214
|
+
ui.error(`Not JSON: ${line.slice(0, 200)}`);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (msg.type === 'shutdown') break;
|
|
218
|
+
try {
|
|
219
|
+
handle(msg);
|
|
220
|
+
} catch (err) {
|
|
221
|
+
ui.error(err.message);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
// stdin closed: stop whatever is running and let it wind down.
|
|
225
|
+
if (turn) {
|
|
226
|
+
ui.cancelRead();
|
|
227
|
+
agent.interrupt();
|
|
228
|
+
await turn;
|
|
229
|
+
}
|
|
230
|
+
mcpServers.forEach((s) => s.close());
|
|
231
|
+
closeBrowser();
|
|
232
|
+
await flushUsage();
|
|
233
|
+
}
|
package/src/session.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// Sessions are append-only JSONL event logs in ~/.leto/sessions/<id>.jsonl.
|
|
2
|
+
// Each event is written (and flushed) as it happens, so a crash loses at most
|
|
3
|
+
// the line being written. Resuming replays the log to rebuild the conversation.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { SESSIONS_DIR } from './config.js';
|
|
8
|
+
import { VERSION } from './version.js';
|
|
9
|
+
|
|
10
|
+
function newId() {
|
|
11
|
+
const d = new Date();
|
|
12
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
13
|
+
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}-${crypto.randomBytes(2).toString('hex')}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function readEvents(file) {
|
|
17
|
+
const events = [];
|
|
18
|
+
for (const line of fs.readFileSync(file, 'utf8').split('\n')) {
|
|
19
|
+
if (!line.trim()) continue;
|
|
20
|
+
try {
|
|
21
|
+
events.push(JSON.parse(line));
|
|
22
|
+
} catch {
|
|
23
|
+
// A torn final line from a crash: skip it.
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return events;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class Session {
|
|
30
|
+
constructor({ id, file, meta, messages = [] }) {
|
|
31
|
+
this.id = id;
|
|
32
|
+
this.file = file;
|
|
33
|
+
this.meta = meta;
|
|
34
|
+
this.messages = messages;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
static create({ cwd, model }) {
|
|
38
|
+
fs.mkdirSync(SESSIONS_DIR, { recursive: true });
|
|
39
|
+
const id = newId();
|
|
40
|
+
const file = path.join(SESSIONS_DIR, `${id}.jsonl`);
|
|
41
|
+
const meta = { type: 'meta', id, cwd, model, version: VERSION, created: new Date().toISOString() };
|
|
42
|
+
const session = new Session({ id, file, meta });
|
|
43
|
+
session.append(meta);
|
|
44
|
+
return session;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
static load(idOrPrefix) {
|
|
48
|
+
const file = findSessionFile(idOrPrefix);
|
|
49
|
+
const events = readEvents(file);
|
|
50
|
+
const meta = events.find((e) => e.type === 'meta') ?? { id: path.basename(file, '.jsonl') };
|
|
51
|
+
let messages = [];
|
|
52
|
+
let todos = [];
|
|
53
|
+
for (const e of events) {
|
|
54
|
+
if (e.type === 'message') messages.push(e.message);
|
|
55
|
+
else if (e.type === 'compact') messages = e.messages;
|
|
56
|
+
else if (e.type === 'clear') messages = [];
|
|
57
|
+
else if (e.type === 'todos') todos = e.todos;
|
|
58
|
+
else if (e.type === 'title') meta.title = e.title;
|
|
59
|
+
}
|
|
60
|
+
const session = new Session({ id: meta.id, file, meta, messages });
|
|
61
|
+
session.todos = todos;
|
|
62
|
+
session.repair();
|
|
63
|
+
return session;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// A session that lives only in memory (used by sub-agents).
|
|
67
|
+
static memory() {
|
|
68
|
+
return new Session({ id: 'memory', file: null, meta: {} });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
static latest(cwd) {
|
|
72
|
+
const s = listSessions().find((x) => x.cwd === cwd);
|
|
73
|
+
return s ? Session.load(s.id) : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
append(event) {
|
|
77
|
+
if (!this.file) return;
|
|
78
|
+
const line = JSON.stringify({ ...event, t: event.t ?? Date.now() }) + '\n';
|
|
79
|
+
const fd = fs.openSync(this.file, 'a', 0o600);
|
|
80
|
+
try {
|
|
81
|
+
fs.writeSync(fd, line);
|
|
82
|
+
fs.fsyncSync(fd);
|
|
83
|
+
} finally {
|
|
84
|
+
fs.closeSync(fd);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
add(message) {
|
|
89
|
+
this.messages.push(message);
|
|
90
|
+
this.append({ type: 'message', message });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
compact(summary, keepFrom) {
|
|
94
|
+
this.messages = [
|
|
95
|
+
{ role: 'user', content: `[Summary of the earlier conversation, written when the context was compacted]\n\n${summary}` },
|
|
96
|
+
{ role: 'assistant', content: 'Understood. I have the summary and will continue from there.' },
|
|
97
|
+
...this.messages.slice(keepFrom),
|
|
98
|
+
];
|
|
99
|
+
this.append({ type: 'compact', messages: this.messages });
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
replace(messages) {
|
|
103
|
+
this.messages = messages;
|
|
104
|
+
this.append({ type: 'compact', messages });
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Every assistant tool call needs a matching tool result, or the API rejects
|
|
108
|
+
// the history. After an interrupt or crash, fill in the missing ones.
|
|
109
|
+
repair() {
|
|
110
|
+
for (let i = this.messages.length - 1; i >= 0; i--) {
|
|
111
|
+
const m = this.messages[i];
|
|
112
|
+
if (m.role !== 'assistant' || !m.tool_calls?.length) continue;
|
|
113
|
+
const answered = new Set(this.messages.slice(i + 1).filter((x) => x.role === 'tool').map((x) => x.tool_call_id));
|
|
114
|
+
const missing = m.tool_calls.filter((c) => !answered.has(c.id));
|
|
115
|
+
if (!missing.length) break;
|
|
116
|
+
// Tool results must directly follow their assistant message.
|
|
117
|
+
const fill = missing.map((c) => ({ role: 'tool', tool_call_id: c.id, content: 'Interrupted: this tool call did not finish.' }));
|
|
118
|
+
let at = i + 1;
|
|
119
|
+
while (at < this.messages.length && this.messages[at].role === 'tool') at++;
|
|
120
|
+
this.messages.splice(at, 0, ...fill);
|
|
121
|
+
this.append({ type: 'compact', messages: this.messages });
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function findSessionFile(idOrPrefix) {
|
|
128
|
+
const exact = path.join(SESSIONS_DIR, `${idOrPrefix}.jsonl`);
|
|
129
|
+
if (fs.existsSync(exact)) return exact;
|
|
130
|
+
const matches = fs.existsSync(SESSIONS_DIR) ? fs.readdirSync(SESSIONS_DIR).filter((f) => f.startsWith(idOrPrefix) && f.endsWith('.jsonl')) : [];
|
|
131
|
+
if (matches.length === 1) return path.join(SESSIONS_DIR, matches[0]);
|
|
132
|
+
if (matches.length > 1) throw new Error(`Session id "${idOrPrefix}" is ambiguous (${matches.length} matches).`);
|
|
133
|
+
throw new Error(`No session "${idOrPrefix}". List sessions with: leto sessions`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The first thing the user typed, without attached files or leto's notes.
|
|
137
|
+
function cleanTitle(text) {
|
|
138
|
+
return text
|
|
139
|
+
.replace(/\n\n<(file|directory) path=[\s\S]*$/, '')
|
|
140
|
+
.replace(/\n\n<hook-context>[\s\S]*$/, '')
|
|
141
|
+
.replace(/\n\n\[[^\]]*\]\s*$/g, '')
|
|
142
|
+
.replace(/\s+/g, ' ')
|
|
143
|
+
.trim()
|
|
144
|
+
.slice(0, 70);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function listSessions() {
|
|
148
|
+
if (!fs.existsSync(SESSIONS_DIR)) return [];
|
|
149
|
+
const out = [];
|
|
150
|
+
for (const f of fs.readdirSync(SESSIONS_DIR)) {
|
|
151
|
+
if (!f.endsWith('.jsonl')) continue;
|
|
152
|
+
const file = path.join(SESSIONS_DIR, f);
|
|
153
|
+
const events = readEvents(file);
|
|
154
|
+
const meta = events.find((e) => e.type === 'meta') ?? {};
|
|
155
|
+
const firstUser = events.find((e) => e.type === 'message' && e.message.role === 'user');
|
|
156
|
+
const named = events.filter((e) => e.type === 'title').at(-1)?.title;
|
|
157
|
+
const count = events.filter((e) => e.type === 'message').length;
|
|
158
|
+
out.push({
|
|
159
|
+
id: meta.id ?? f.replace(/\.jsonl$/, ''),
|
|
160
|
+
cwd: meta.cwd,
|
|
161
|
+
model: meta.model,
|
|
162
|
+
updated: fs.statSync(file).mtimeMs,
|
|
163
|
+
messages: count,
|
|
164
|
+
title: named || cleanTitle(typeof firstUser?.message.content === 'string' ? firstUser.message.content : Array.isArray(firstUser?.message.content) ? firstUser.message.content.find((p) => p.type === 'text')?.text ?? '' : ''),
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return out.sort((a, b) => b.updated - a.updated);
|
|
168
|
+
}
|
package/src/setup.js
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// First-run setup and switching: choose a provider, paste a key, pick a model.
|
|
2
|
+
import { PROVIDERS, getProvider } from './providers.js';
|
|
3
|
+
import { listModels } from './client.js';
|
|
4
|
+
import { loadConfig, saveProvider, savedProviderSettings, maskSecret } from './config.js';
|
|
5
|
+
|
|
6
|
+
// Returns the new config, or null if the user cancelled.
|
|
7
|
+
export async function runSetup({ ui, prompts, welcome = false }) {
|
|
8
|
+
const c = ui.c;
|
|
9
|
+
if (welcome) {
|
|
10
|
+
ui.write(ui.out, `\n${c.accent(c.bold(' ◆ Welcome to leto'))}\n`);
|
|
11
|
+
ui.write(ui.out, c.dim(' Pick the AI provider to use. You can switch any time with /provider.\n\n'));
|
|
12
|
+
}
|
|
13
|
+
let current = null;
|
|
14
|
+
try {
|
|
15
|
+
current = loadConfig().provider;
|
|
16
|
+
} catch {}
|
|
17
|
+
|
|
18
|
+
const providerId = await prompts.select({
|
|
19
|
+
title: 'Provider',
|
|
20
|
+
items: PROVIDERS.map((p) => ({
|
|
21
|
+
label: p.name,
|
|
22
|
+
value: p.id,
|
|
23
|
+
hint: savedProviderSettings(p.id).apiKey ? 'key saved' : p.id === current ? 'current' : '',
|
|
24
|
+
})),
|
|
25
|
+
initial: Math.max(0, PROVIDERS.findIndex((p) => p.id === current)),
|
|
26
|
+
});
|
|
27
|
+
if (!providerId) return null;
|
|
28
|
+
const provider = getProvider(providerId);
|
|
29
|
+
const saved = savedProviderSettings(providerId);
|
|
30
|
+
|
|
31
|
+
let baseUrl = provider.baseUrl;
|
|
32
|
+
if (provider.custom) {
|
|
33
|
+
while (true) {
|
|
34
|
+
const hint = saved.baseUrl ? c.dim(` [${saved.baseUrl}]`) : '';
|
|
35
|
+
const answer = await prompts.input(`API base URL, e.g. https://api.example.com/v1${hint}: `);
|
|
36
|
+
if (answer === null) return null;
|
|
37
|
+
baseUrl = (answer || saved.baseUrl || '').replace(/\/+$/, '');
|
|
38
|
+
if (/^https?:\/\/\S+$/.test(baseUrl)) break;
|
|
39
|
+
ui.write(ui.out, c.red(' Enter a URL starting with http:// or https://\n'));
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
let apiKey = '';
|
|
44
|
+
let models = null;
|
|
45
|
+
let keepKey = false;
|
|
46
|
+
for (let attempt = 0; ; attempt++) {
|
|
47
|
+
if (!provider.noKey && !keepKey) {
|
|
48
|
+
const reuse = saved.apiKey && attempt === 0
|
|
49
|
+
? await prompts.select({
|
|
50
|
+
title: 'API key',
|
|
51
|
+
items: [
|
|
52
|
+
{ label: `Use saved key ${maskSecret(saved.apiKey)}`, value: 'reuse' },
|
|
53
|
+
{ label: 'Enter a new key', value: 'new' },
|
|
54
|
+
],
|
|
55
|
+
})
|
|
56
|
+
: 'new';
|
|
57
|
+
if (reuse === null) return null;
|
|
58
|
+
if (reuse === 'reuse') apiKey = saved.apiKey;
|
|
59
|
+
else {
|
|
60
|
+
if (provider.keyUrl) ui.write(ui.out, c.dim(` Get a key at ${provider.keyUrl}\n`));
|
|
61
|
+
const label = provider.custom ? 'API key (Enter if none): ' : `Paste your ${provider.name} API key: `;
|
|
62
|
+
const key = await prompts.secret(label);
|
|
63
|
+
if (key === null) return null;
|
|
64
|
+
if (!key && !provider.custom) {
|
|
65
|
+
ui.write(ui.out, c.red(' A key is required for this provider.\n'));
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
apiKey = key;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
ui.write(ui.out, c.dim(' Checking…'));
|
|
73
|
+
try {
|
|
74
|
+
models = await listModels({ provider: providerId, baseUrl, apiKey });
|
|
75
|
+
ui.write(ui.out, `\r${c.green(' ✓')} Connected${models.length ? ` · ${models.length} models available` : ''}\n`);
|
|
76
|
+
break;
|
|
77
|
+
} catch (err) {
|
|
78
|
+
ui.write(ui.out, '\r');
|
|
79
|
+
if (err.status === 401 || err.status === 403) {
|
|
80
|
+
ui.write(ui.out, c.red(` ✗ ${provider.name} rejected that key (${err.status}). Check it and try again.\n`));
|
|
81
|
+
if (provider.noKey || attempt >= 4) return null;
|
|
82
|
+
keepKey = false;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (err.unreachable) {
|
|
86
|
+
const msg = provider.id === 'ollama' ? 'Ollama is not running. Start it with: ollama serve' : `Could not reach ${baseUrl}.`;
|
|
87
|
+
ui.write(ui.out, c.red(` ✗ ${msg}\n`));
|
|
88
|
+
} else {
|
|
89
|
+
ui.write(ui.out, c.yellow(` ! Couldn't list models (${err.status ?? err.message}). You can type a model name instead.\n`));
|
|
90
|
+
models = [];
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
const next = await prompts.select({
|
|
94
|
+
title: 'What now?',
|
|
95
|
+
items: [
|
|
96
|
+
{ label: 'Try again', value: 'retry' },
|
|
97
|
+
{ label: 'Continue anyway and type a model name', value: 'skip' },
|
|
98
|
+
{ label: 'Cancel', value: 'cancel' },
|
|
99
|
+
],
|
|
100
|
+
});
|
|
101
|
+
if (next === null || next === 'cancel') return null;
|
|
102
|
+
if (next === 'retry') {
|
|
103
|
+
keepKey = true;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
models = [];
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const model = await pickModel({ ui, prompts, provider, models, current: saved.model });
|
|
112
|
+
if (!model) return null;
|
|
113
|
+
|
|
114
|
+
saveProvider(providerId, {
|
|
115
|
+
baseUrl: provider.custom ? baseUrl : undefined,
|
|
116
|
+
apiKey: apiKey || undefined,
|
|
117
|
+
model: model.id,
|
|
118
|
+
contextWindow: model.contextWindow || undefined,
|
|
119
|
+
});
|
|
120
|
+
ui.write(ui.out, `${c.green(' ✓')} Using ${c.bold(model.id)} from ${provider.name}. ${c.dim('Saved to ~/.leto/config.json')}\n\n`);
|
|
121
|
+
return loadConfig();
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Choose a model from the provider's list (or type one when there's no list).
|
|
125
|
+
export async function pickModel({ ui, prompts, provider, models, current }) {
|
|
126
|
+
if (!models?.length) {
|
|
127
|
+
const name = await prompts.input(`Model name${current ? ui.c.dim(` [${current}]`) : ''}: `);
|
|
128
|
+
if (name === null) return null;
|
|
129
|
+
const id = name || current;
|
|
130
|
+
return id ? { id } : null;
|
|
131
|
+
}
|
|
132
|
+
const preferred = [current, provider?.defaultModel].filter(Boolean);
|
|
133
|
+
let initial = 0;
|
|
134
|
+
for (const p of preferred) {
|
|
135
|
+
const i = models.findIndex((m) => m.id === p);
|
|
136
|
+
if (i >= 0) {
|
|
137
|
+
initial = i;
|
|
138
|
+
break;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
const id = await prompts.select({
|
|
142
|
+
title: 'Model',
|
|
143
|
+
items: models.map((m) => ({
|
|
144
|
+
label: m.id,
|
|
145
|
+
value: m.id,
|
|
146
|
+
hint: [m.name && m.name !== m.id ? m.name : '', m.contextWindow ? `${formatTokens(m.contextWindow)} context` : '', m.id === current ? 'current' : '']
|
|
147
|
+
.filter(Boolean)
|
|
148
|
+
.join(' · '),
|
|
149
|
+
})),
|
|
150
|
+
initial,
|
|
151
|
+
});
|
|
152
|
+
return id ? models.find((m) => m.id === id) : null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function formatTokens(n) {
|
|
156
|
+
return n >= 1_000_000 ? `${+(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${Math.round(n / 1000)}K` : String(n);
|
|
157
|
+
}
|
package/src/skills.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Skills: folders of instructions (and optional scripts/templates) the model
|
|
2
|
+
// loads when a task calls for them. Each skill is a directory with a SKILL.md:
|
|
3
|
+
//
|
|
4
|
+
// ---
|
|
5
|
+
// name: release
|
|
6
|
+
// description: Cut a release: bump the version, update the changelog, tag and publish.
|
|
7
|
+
// ---
|
|
8
|
+
// Step-by-step instructions…
|
|
9
|
+
//
|
|
10
|
+
// Only the name and description go into the system prompt; the model reads
|
|
11
|
+
// the full instructions with the `skill` tool. Skills are found in:
|
|
12
|
+
// ~/.leto/skills, ~/.claude/skills (yours, everywhere)
|
|
13
|
+
// <project>/.leto/skills, <project>/.claude/skills (this 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 { pluginDirs } from './plugins.js';
|
|
19
|
+
import { policyDisablesPlugins } from './policy.js';
|
|
20
|
+
import { projectDir } from './legacy.js';
|
|
21
|
+
|
|
22
|
+
export function skillDirs(cwd) {
|
|
23
|
+
return {
|
|
24
|
+
user: [path.join(HOME_DIR, 'skills'), path.join(os.homedir(), '.claude', 'skills'), ...(policyDisablesPlugins() ? [] : pluginDirs('skills'))],
|
|
25
|
+
project: [path.join(projectDir(cwd), 'skills'), path.join(cwd, '.claude', 'skills')],
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function parseSkill(text) {
|
|
30
|
+
const m = text.match(/^---\s*\n([\s\S]*?)\n---\s*\n?([\s\S]*)$/);
|
|
31
|
+
const meta = {};
|
|
32
|
+
let body = text;
|
|
33
|
+
if (m) {
|
|
34
|
+
body = m[2];
|
|
35
|
+
for (const line of m[1].split('\n')) {
|
|
36
|
+
const kv = line.match(/^([\w-]+):\s*(.*)$/);
|
|
37
|
+
if (kv) meta[kv[1].toLowerCase()] = kv[2].trim().replace(/^["']|["']$/g, '');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return { meta, body: body.trim() };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function projectHasSkills(cwd) {
|
|
44
|
+
return skillDirs(cwd).project.some((d) => {
|
|
45
|
+
try {
|
|
46
|
+
return fs.readdirSync(d).some((n) => fs.existsSync(path.join(d, n, 'SKILL.md')));
|
|
47
|
+
} catch {
|
|
48
|
+
return false;
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Later sources override earlier ones with the same name (project beats user).
|
|
54
|
+
export function loadSkills(cwd, { includeProject = true } = {}) {
|
|
55
|
+
const { user, project } = skillDirs(cwd);
|
|
56
|
+
const skills = new Map();
|
|
57
|
+
for (const [dirs, source] of [[user, 'user'], [includeProject ? project : [], 'project']]) {
|
|
58
|
+
for (const dir of dirs) {
|
|
59
|
+
let names = [];
|
|
60
|
+
try {
|
|
61
|
+
names = fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory() || e.isSymbolicLink()).map((e) => e.name);
|
|
62
|
+
} catch {
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
for (const n of names) {
|
|
66
|
+
const file = path.join(dir, n, 'SKILL.md');
|
|
67
|
+
if (!fs.existsSync(file)) continue;
|
|
68
|
+
try {
|
|
69
|
+
const { meta } = parseSkill(fs.readFileSync(file, 'utf8'));
|
|
70
|
+
const name = (meta.name || n).toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
|
|
71
|
+
skills.set(name, { name, description: meta.description || '(no description)', dir: path.dirname(file), file, source });
|
|
72
|
+
} catch {}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return [...skills.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// What the model gets when it loads a skill: the instructions plus the
|
|
80
|
+
// skill's other files, which it can read or run.
|
|
81
|
+
export function readSkill(skill) {
|
|
82
|
+
const { body } = parseSkill(fs.readFileSync(skill.file, 'utf8'));
|
|
83
|
+
const files = [];
|
|
84
|
+
const walk = (dir, rel) => {
|
|
85
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
86
|
+
if (e.name.startsWith('.')) continue;
|
|
87
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
88
|
+
if (e.isDirectory()) walk(path.join(dir, e.name), r);
|
|
89
|
+
else if (r !== 'SKILL.md') files.push(r);
|
|
90
|
+
if (files.length > 100) return;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
walk(skill.dir, '');
|
|
94
|
+
return `# Skill: ${skill.name}\nFolder: ${skill.dir}\n${files.length ? `Files in this skill (read or run them by path):\n${files.map((f) => `- ${path.join(skill.dir, f)}`).join('\n')}\n` : ''}\n${body}`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function createSkill({ name, description, where = 'user', cwd }) {
|
|
98
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-|-$/g, '');
|
|
99
|
+
if (!slug) throw new Error('A skill needs a name.');
|
|
100
|
+
const base = where === 'project' ? path.join(projectDir(cwd), 'skills') : path.join(HOME_DIR, 'skills');
|
|
101
|
+
const dir = path.join(base, slug);
|
|
102
|
+
if (fs.existsSync(path.join(dir, 'SKILL.md'))) throw new Error(`A skill named "${slug}" already exists at ${dir}.`);
|
|
103
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
104
|
+
fs.writeFileSync(
|
|
105
|
+
path.join(dir, 'SKILL.md'),
|
|
106
|
+
`---\nname: ${slug}\ndescription: ${description || 'Describe when this skill should be used.'}\n---\n\n# ${name}\n\nWrite the steps leto should follow when this skill is used.\n\n1. …\n2. …\n\nPut any scripts or templates next to this file and mention them here by name.\n`,
|
|
107
|
+
);
|
|
108
|
+
return path.join(dir, 'SKILL.md');
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function skillTool(getSkills) {
|
|
112
|
+
return {
|
|
113
|
+
name: 'skill',
|
|
114
|
+
description:
|
|
115
|
+
'Load one of the available skills (listed in the system prompt under "Skills") to get its full instructions. Load a skill whenever the task matches its description, before starting the work, then follow its instructions.',
|
|
116
|
+
parameters: { type: 'object', properties: { name: { type: 'string', description: 'The skill name' } }, required: ['name'] },
|
|
117
|
+
summary: (a) => a.name,
|
|
118
|
+
run(a) {
|
|
119
|
+
const skills = getSkills();
|
|
120
|
+
const s = skills.find((x) => x.name === String(a.name).toLowerCase());
|
|
121
|
+
if (!s) throw new Error(`No skill "${a.name}". Available: ${skills.map((x) => x.name).join(', ') || 'none'}`);
|
|
122
|
+
return { content: readSkill(s), display: `loaded ${s.name}` };
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|