@mumbrane/leto 0.0.0-stage → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +395 -2
  2. package/bin/leto.js +8 -0
  3. package/evals/core/suite.json +249 -0
  4. package/index.js +12 -0
  5. package/package.json +43 -4
  6. package/src/agent.js +572 -0
  7. package/src/agents.js +68 -0
  8. package/src/anthropic.js +204 -0
  9. package/src/browser.js +427 -0
  10. package/src/btw.js +56 -0
  11. package/src/checkpoints.js +90 -0
  12. package/src/ci.js +115 -0
  13. package/src/cli.js +1926 -0
  14. package/src/client.js +111 -0
  15. package/src/config.js +205 -0
  16. package/src/documents.js +198 -0
  17. package/src/eval.js +289 -0
  18. package/src/hooks.js +115 -0
  19. package/src/ide.js +231 -0
  20. package/src/input.js +148 -0
  21. package/src/jobs.js +97 -0
  22. package/src/legacy.js +41 -0
  23. package/src/lsp.js +401 -0
  24. package/src/markdown.js +153 -0
  25. package/src/mcp.js +346 -0
  26. package/src/memory.js +136 -0
  27. package/src/orchestrator.js +141 -0
  28. package/src/patching.js +185 -0
  29. package/src/permissions.js +75 -0
  30. package/src/plugins.js +118 -0
  31. package/src/policy.js +74 -0
  32. package/src/pricing.js +67 -0
  33. package/src/processes.js +139 -0
  34. package/src/prompt.js +134 -0
  35. package/src/prompts.js +189 -0
  36. package/src/providers.js +59 -0
  37. package/src/repomap.js +211 -0
  38. package/src/sandbox.js +90 -0
  39. package/src/sdk.js +220 -0
  40. package/src/selftool.js +238 -0
  41. package/src/serve.js +233 -0
  42. package/src/session.js +168 -0
  43. package/src/setup.js +157 -0
  44. package/src/skills.js +125 -0
  45. package/src/theme.js +185 -0
  46. package/src/toolcalls.js +257 -0
  47. package/src/tools.js +976 -0
  48. package/src/tui.js +1179 -0
  49. package/src/ui.js +454 -0
  50. package/src/update.js +33 -0
  51. package/src/usage.js +83 -0
  52. package/src/verify.js +131 -0
  53. package/src/version.js +3 -0
  54. package/src/worktree.js +87 -0
  55. package/vscode/extension.js +132 -0
  56. package/vscode/package.json +21 -0
package/src/ui.js ADDED
@@ -0,0 +1,454 @@
1
+ import readline from 'node:readline';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import { MarkdownStream, visibleLength } from './markdown.js';
5
+ import { makeTheme, GLYPH } from './theme.js';
6
+
7
+ const colorOn = (stream) => Boolean(stream.isTTY) && !process.env.NO_COLOR;
8
+
9
+ export function colors(stream = process.stdout) {
10
+ return makeTheme(colorOn(stream));
11
+ }
12
+
13
+ const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
14
+ const VERBS = ['Thinking', 'Reading the sands', 'Harvesting spice', 'Folding space', 'Charting the dunes', 'Working', 'Considering'];
15
+
16
+ export const TOOL_LABELS = {
17
+ read_file: 'Read', write_file: 'Write', edit_file: 'Edit', multi_edit: 'Edit', bash: 'Bash', grep: 'Search',
18
+ list_files: 'List', task: 'Agent', todo_write: 'Todos', web_fetch: 'Fetch', web_search: 'Web search',
19
+ repo_map: 'Map', notebook_edit: 'Notebook', check: 'Check', skill: 'Skill', browser: 'Browser',
20
+ };
21
+
22
+ const tildify = (p) => (p.startsWith(os.homedir()) ? '~' + p.slice(os.homedir().length) : p);
23
+
24
+ // Terminal I/O. In print mode (-p) the answer goes to stdout and everything
25
+ // else (tool activity, notices, spinner) to stderr, so output can be piped.
26
+ // "Fancy" mode (a real terminal) adds the spinner, input chrome and Markdown.
27
+ export class UI {
28
+ constructor({ print = false, quiet = false } = {}) {
29
+ this.print = print;
30
+ this.quiet = quiet; // --json: no streamed reply text
31
+ this.out = process.stdout;
32
+ this.log = print ? process.stderr : process.stdout;
33
+ this.c = colors(this.out);
34
+ this.lc = colors(this.log);
35
+ this.fancy = !print && Boolean(process.stdout.isTTY && process.stdin.isTTY);
36
+ this.markdown = Boolean(this.out.isTTY);
37
+ this.rl = null;
38
+ this.queue = [];
39
+ this.waiter = null;
40
+ this.closed = false;
41
+ this.atLineStart = true;
42
+ this.mode = null; // 'text' | 'thinking'
43
+ this.md = null;
44
+ this.spinner = null;
45
+ this.muted = false;
46
+ this.statusLine = () => '';
47
+ this.onEscape = null;
48
+ }
49
+
50
+ // Rebuild colors after a theme change.
51
+ retheme() {
52
+ this.c = colors(this.out);
53
+ this.lc = colors(this.log);
54
+ }
55
+
56
+ get width() {
57
+ return Math.max(40, (this.out.columns || 100) - 1);
58
+ }
59
+
60
+ // ---- line input -------------------------------------------------------
61
+
62
+ start() {
63
+ if (this.rl || this.closed) return;
64
+ const rl = readline.createInterface({
65
+ input: process.stdin,
66
+ output: process.stdout,
67
+ terminal: !!process.stdin.isTTY,
68
+ historySize: 1000,
69
+ removeHistoryDuplicates: true,
70
+ completer: this.completer ? (line) => this.completer(line) : undefined,
71
+ });
72
+ this.rl = rl;
73
+ if (this.history) rl.history = this.history;
74
+ else if (this.historyFile && this.fancy) {
75
+ try {
76
+ rl.history = fs.readFileSync(this.historyFile, 'utf8').split('\n').filter(Boolean).reverse().slice(0, 1000);
77
+ } catch {}
78
+ }
79
+ // While the agent works, typed text is queued but not echoed over its output.
80
+ if (typeof rl._writeToOutput === 'function') {
81
+ const write = rl._writeToOutput.bind(rl);
82
+ rl._writeToOutput = (s) => {
83
+ if (!this.muted) write(s);
84
+ };
85
+ }
86
+ rl.on('line', (line) => {
87
+ if (this.waiter) {
88
+ const w = this.waiter;
89
+ this.waiter = null;
90
+ w(line);
91
+ } else this.queue.push(line);
92
+ });
93
+ rl.on('close', () => {
94
+ if (rl.suspended) return;
95
+ this.closed = true;
96
+ this.cancelRead();
97
+ });
98
+ if (this.interruptHandler) rl.on('SIGINT', this.interruptHandler);
99
+ if (this.fancy && !this.keypressBound) {
100
+ this.keypressBound = true;
101
+ process.stdin.on('keypress', (_s, key) => {
102
+ if (key?.name === 'escape' && this.onEscape) this.onEscape();
103
+ });
104
+ }
105
+ }
106
+
107
+ // Hand the terminal to a raw-mode prompt (picker, secret input) and back.
108
+ suspend() {
109
+ if (!this.rl) return;
110
+ this.history = this.rl.history;
111
+ this.rl.suspended = true;
112
+ this.rl.close();
113
+ this.rl = null;
114
+ }
115
+
116
+ resume() {
117
+ this.start();
118
+ }
119
+
120
+ onInterrupt(handler) {
121
+ this.interruptHandler = handler;
122
+ if (this.rl) this.rl.on('SIGINT', handler);
123
+ process.on('SIGINT', handler);
124
+ }
125
+
126
+ close() {
127
+ this.stopSpinner();
128
+ this.rl?.close();
129
+ }
130
+
131
+ setBusy(busy) {
132
+ this.busy = busy;
133
+ this.muted = busy && this.fancy;
134
+ }
135
+
136
+ readLine(promptText) {
137
+ if (!this.rl) return Promise.resolve(null);
138
+ const wasMuted = this.muted;
139
+ this.muted = false;
140
+ this.stopSpinner();
141
+ const restore = (v) => {
142
+ this.muted = wasMuted;
143
+ return v;
144
+ };
145
+ if (this.closed) {
146
+ if (!this.queue.length) return Promise.resolve(restore(null));
147
+ this.out.write(promptText);
148
+ } else {
149
+ this.rl.setPrompt(promptText);
150
+ this.rl.prompt();
151
+ }
152
+ if (this.queue.length) {
153
+ const line = this.queue.shift();
154
+ if (!process.stdin.isTTY) this.out.write(line + '\n');
155
+ return Promise.resolve(restore(line));
156
+ }
157
+ if (this.closed) return Promise.resolve(restore(null));
158
+ return new Promise((resolve) => {
159
+ this.waiter = (line) => {
160
+ if (line !== null && !process.stdin.isTTY) this.out.write(line + '\n');
161
+ resolve(restore(line));
162
+ };
163
+ });
164
+ }
165
+
166
+ cancelRead() {
167
+ if (this.waiter) {
168
+ const w = this.waiter;
169
+ this.waiter = null;
170
+ w(null);
171
+ }
172
+ }
173
+
174
+ // The main "› " prompt, with a rule above and a status line below.
175
+ async prompt() {
176
+ const c = this.c;
177
+ const queued = this.queue.length > 0;
178
+ if (this.fancy && !queued) {
179
+ this.newlineIfNeeded(this.out);
180
+ // A blank line, then a rule that carries the status, then the input line.
181
+ const status = this.statusLine();
182
+ const label = status ? ` ${status} ` : '';
183
+ const rest = Math.max(4, this.width - 2 - visibleLength(label));
184
+ this.out.write(`\n${c.gray('──' + label + '─'.repeat(rest))}\n`);
185
+ }
186
+ let text = await this.readLine(c.accent('› '));
187
+ while (text !== null && text.endsWith('\\')) {
188
+ const next = await this.readLine(c.gray(' '));
189
+ if (next === null) break;
190
+ text = text.slice(0, -1) + '\n' + next;
191
+ }
192
+ if (text !== null && this.fancy) this.echoUser(text, queued);
193
+ if (text?.trim() && this.historyFile && this.fancy) {
194
+ try {
195
+ fs.appendFileSync(this.historyFile, text.replace(/\n/g, ' ') + '\n', { mode: 0o600 });
196
+ } catch {}
197
+ }
198
+ this.atLineStart = true;
199
+ return text;
200
+ }
201
+
202
+ // Replace the raw prompt line with a highlighted copy of what was sent.
203
+ echoUser(text, queued) {
204
+ const c = this.c;
205
+ if (!queued) {
206
+ // The cursor is just below the input now. Go back over the input and the rule.
207
+ const rows = text.split('\n').reduce((n, l) => n + Math.max(1, Math.ceil((visibleLength(l) + 2) / (this.width + 1))), 0);
208
+ this.out.write(`\x1b[${rows + 1}A\r\x1b[J`);
209
+ }
210
+ const lines = text.split('\n');
211
+ for (const [i, l] of lines.entries()) {
212
+ const body = `${i === 0 ? '› ' : ' '}${l}`;
213
+ const pad = Math.max(0, this.width - visibleLength(body));
214
+ this.out.write(`${c.userBg(body + ' '.repeat(pad))}\n`);
215
+ }
216
+ this.out.write('\n');
217
+ }
218
+
219
+ // ---- output ----------------------------------------------------------
220
+
221
+ write(stream, s) {
222
+ if (!s) return;
223
+ if (this.spinner && stream === this.spinner.stream) this.clearSpinnerLine();
224
+ stream.write(s);
225
+ this.atLineStart = s.endsWith('\n');
226
+ }
227
+
228
+ newlineIfNeeded(stream = this.log) {
229
+ if (!this.atLineStart) this.write(stream, '\n');
230
+ }
231
+
232
+ startSpinner(label) {
233
+ const stream = this.log;
234
+ if (!stream.isTTY) return;
235
+ if (this.spinner) {
236
+ if (label) this.spinner.label = label;
237
+ return;
238
+ }
239
+ this.newlineIfNeeded(stream);
240
+ const lc = this.lc;
241
+ const spinner = {
242
+ stream,
243
+ label: label ?? VERBS[Math.floor(Math.random() * VERBS.length)],
244
+ started: Date.now(),
245
+ frame: 0,
246
+ drawn: false,
247
+ };
248
+ const draw = () => {
249
+ const secs = Math.floor((Date.now() - spinner.started) / 1000);
250
+ let line = `${lc.orchid(SPINNER[spinner.frame % SPINNER.length])} ${lc.shimmer(spinner.label + '…', spinner.frame++)} ${lc.faint(`${secs}s · esc to interrupt`)}`;
251
+ if (spinner.detail) line += lc.gray(` ${spinner.detail}`);
252
+ stream.write(`\r\x1b[2K${truncate(line, this.width)}`);
253
+ spinner.drawn = true;
254
+ };
255
+ spinner.timer = setInterval(draw, 90);
256
+ spinner.timer.unref?.();
257
+ this.spinner = spinner;
258
+ draw();
259
+ }
260
+
261
+ spinnerDetail(text) {
262
+ if (this.spinner) this.spinner.detail = String(text).replace(/\x1b\[[0-9;]*[A-Za-z]/g, '').slice(0, 200);
263
+ }
264
+
265
+ clearSpinnerLine() {
266
+ if (this.spinner?.drawn) {
267
+ this.spinner.stream.write('\r\x1b[2K');
268
+ this.spinner.drawn = false;
269
+ }
270
+ }
271
+
272
+ stopSpinner() {
273
+ if (!this.spinner) return;
274
+ clearInterval(this.spinner.timer);
275
+ this.clearSpinnerLine();
276
+ this.spinner = null;
277
+ }
278
+
279
+ startResponse() {
280
+ this.mode = null;
281
+ }
282
+
283
+ thinking(s) {
284
+ this.stopSpinner();
285
+ if (this.mode !== 'thinking') {
286
+ this.newlineIfNeeded(this.log);
287
+ this.mode = 'thinking';
288
+ }
289
+ this.write(this.log, this.lc.gray(this.lc.italic(s)));
290
+ }
291
+
292
+ text(s) {
293
+ if (this.quiet) return;
294
+ this.stopSpinner();
295
+ if (this.mode === 'thinking') this.write(this.log, '\n\n');
296
+ else if (this.mode !== 'text') {
297
+ this.newlineIfNeeded(this.out);
298
+ if (this.markdown) this.md = new MarkdownStream(this.c, { width: this.width });
299
+ }
300
+ this.mode = 'text';
301
+ if (this.md) this.write(this.out, this.md.push(s));
302
+ else this.write(this.out, s);
303
+ }
304
+
305
+ endText() {
306
+ if (this.md) {
307
+ this.write(this.out, this.md.flush());
308
+ this.md = null;
309
+ }
310
+ if (this.mode) this.newlineIfNeeded(this.mode === 'text' ? this.out : this.log);
311
+ this.mode = null;
312
+ }
313
+
314
+ toolStart(name, summary, { prefix = '' } = {}) {
315
+ this.endText();
316
+ const t = this.lc;
317
+ const sum = String(summary ?? '').split('\n')[0];
318
+ const label = TOOL_LABELS[name] ?? name;
319
+ if (prefix) {
320
+ // A sub-agent's tool call, nested under its parent.
321
+ this.write(this.log, truncate(` ${t.faint('│')} ${t.mist(prefix)} ${t.faint('·')} ${t.lilac(label)}${sum ? ` ${t.mist(sum)}` : ''}`, this.width) + '\n');
322
+ return;
323
+ }
324
+ const lead = this.atLineStart ? '' : '\n';
325
+ this.write(this.log, truncate(`${lead}${t.violet(GLYPH.tool)} ${t.bold(t.lilac(label))}${sum ? ` ${t.mist(sum)}` : ''}`, this.width) + '\n');
326
+ }
327
+
328
+ toolResult(result, isError = false, { lines: extra } = {}) {
329
+ const t = this.lc;
330
+ const all = String(result).split('\n');
331
+ this.lastOutput = String(result);
332
+ const shown = all.slice(0, 4).map((l) => truncate(l, this.width - 6));
333
+ const color = isError ? t.rose : t.mist;
334
+ let body = shown.map((l, i) => ` ${i === 0 ? t.faint(GLYPH.result) : ' '} ${color(l)}`).join('\n');
335
+ if (all.length > 4) body += `\n ${t.faint(`+${all.length - 4} more lines${this.fancy ? ' · ctrl+o to show all' : ''}`)}`;
336
+ this.write(this.log, body + '\n');
337
+ if (extra?.length) this.diff(extra);
338
+ }
339
+
340
+ // Diff lines on tinted backgrounds, with line numbers.
341
+ diff(lines, { indent = ' ', width } = {}) {
342
+ const t = this.lc;
343
+ const w = Math.max(20, (width ?? this.width) - indent.length - 6);
344
+ for (const { sign, text, n } of lines) {
345
+ const num = n !== undefined ? t.faint(String(n).padStart(4)) : ' ';
346
+ const body = truncate(`${sign === ' ' ? ' ' : sign} ${text}`, w);
347
+ const padded = body + ' '.repeat(Math.max(0, w - visibleLength(body)));
348
+ const line =
349
+ sign === '+' ? t.addBg(t.mint(padded))
350
+ : sign === '-' ? t.delBg(t.rose(padded))
351
+ : sign === '$' ? t.panelBg(t.lilac(padded))
352
+ : t.mist(body);
353
+ this.write(this.log, `${indent}${num} ${line}\n`);
354
+ }
355
+ }
356
+
357
+ todos(list) {
358
+ const t = this.lc;
359
+ for (const item of list) {
360
+ const g = GLYPH.todo[item.status] ?? GLYPH.todo.pending;
361
+ const line =
362
+ item.status === 'completed' ? `${t.mint(g)} ${t.mist(t.strike(item.content))}`
363
+ : item.status === 'in_progress' ? `${t.orchid(g)} ${t.bold(t.lilac(item.content))}`
364
+ : `${t.mist(g)} ${t.lilac(item.content)}`;
365
+ this.write(this.log, ` ${line}\n`);
366
+ }
367
+ }
368
+
369
+ async confirm(preview, toolName, { prefix } = {}) {
370
+ this.stopSpinner();
371
+ const t = this.lc;
372
+ if (preview) {
373
+ this.write(this.log, ` ${t.orchid(GLYPH.user)} ${t.bold(t.lilac(preview.title))}\n`);
374
+ if (preview.lines?.length) this.diff(preview.lines);
375
+ }
376
+ const once = toolName === 'exit_plan_mode' || toolName === 'leto';
377
+ const choices = prefix ? `[y]es [p] always allow "${prefix}" here [a]lways this session [n]o` : once ? '[y]es [n]o' : '[y]es [a]lways this session [n]o';
378
+ const answer = await this.readLine(` ${t.orchid(GLYPH.user)} ${t.bold('Allow?')} ${t.mist(choices)} `);
379
+ const a = (answer ?? 'n').trim().toLowerCase();
380
+ if (prefix && a === 'p') return 'prefix';
381
+ if ((a === 'a' || a === 'always') && !once) return 'always';
382
+ if (a === 'y' || a === 'yes' || a === '') return 'yes';
383
+ return 'no';
384
+ }
385
+
386
+ // A question from the model. Print mode can't ask, so it returns null.
387
+ async ask({ question, header, options = [], multiSelect = false, index = 0, total = 1 }) {
388
+ if (this.print) return null;
389
+ this.stopSpinner();
390
+ const t = this.lc;
391
+ this.write(this.log, `\n ${t.orchid('?')} ${t.bold(header ? `${header}: ${question}` : question)}${total > 1 ? t.faint(` (${index + 1} of ${total})`) : ''}\n`);
392
+ options.forEach((o, i) => this.write(this.log, ` ${t.faint(`${i + 1}.`)} ${t.lilac(o.label)}${o.description ? ` ${t.mist(o.description)}` : ''}\n`));
393
+ const hint = multiSelect ? 'numbers separated by commas, or type an answer' : 'a number, or type an answer';
394
+ const line = await this.readLine(` ${t.orchid('❯')} ${t.mist(`(${hint}, Enter to skip)`)} `);
395
+ const a = (line ?? '').trim();
396
+ if (!a) return null;
397
+ const nums = a.split(/[\s,]+/).map(Number);
398
+ if (nums.every((x) => Number.isInteger(x) && x >= 1 && x <= options.length)) {
399
+ return { answer: (multiSelect ? nums : nums.slice(0, 1)).map((x) => options[x - 1].label).join(', ') };
400
+ }
401
+ return { answer: a };
402
+ }
403
+
404
+ banner({ version, model, provider, cwd }) {
405
+ const t = this.c;
406
+ this.write(this.out, `\n ${t.gradient('◆ leto')} ${t.mist(`v${version}`)}\n`);
407
+ this.write(this.out, t.mist(` ${model} · ${provider} · ${cwd}\n`));
408
+ this.write(this.out, t.mist(' /help for commands · Ctrl-C to interrupt · Ctrl-D to quit\n\n'));
409
+ }
410
+
411
+ // Clear the screen and the scrollback.
412
+ clearScreen() {
413
+ this.endText();
414
+ if (this.out.isTTY) this.out.write('\x1b[2J\x1b[3J\x1b[H');
415
+ this.atLineStart = true;
416
+ }
417
+
418
+ info(msg) {
419
+ this.endText();
420
+ this.write(this.log, this.lc.mist(msg) + '\n');
421
+ }
422
+
423
+ success(msg) {
424
+ this.endText();
425
+ this.write(this.log, `${this.lc.mint(GLYPH.ok)} ${this.lc.lilac(msg)}\n`);
426
+ }
427
+
428
+ error(msg) {
429
+ this.endText();
430
+ const [first, ...rest] = String(msg).split('\n');
431
+ this.write(this.log, `${this.lc.rose(GLYPH.fail)} ${this.lc.rose(first)}${rest.length ? '\n' + rest.map((l) => ` ${this.lc.mist(l)}`).join('\n') : ''}\n`);
432
+ }
433
+ }
434
+
435
+ export function truncate(s, width) {
436
+ if (visibleLength(s) <= width) return s;
437
+ // Walk the string keeping ANSI codes, cutting visible characters.
438
+ let out = '';
439
+ let seen = 0;
440
+ for (let i = 0; i < s.length; i++) {
441
+ if (s[i] === '\x1b') {
442
+ const m = s.slice(i).match(/^\x1b\[[0-9;]*m/);
443
+ if (m) {
444
+ out += m[0];
445
+ i += m[0].length - 1;
446
+ continue;
447
+ }
448
+ }
449
+ if (seen >= width - 1) break;
450
+ out += s[i];
451
+ seen++;
452
+ }
453
+ return out + (s.includes('\x1b') ? '…\x1b[0m' : '…');
454
+ }
package/src/update.js ADDED
@@ -0,0 +1,33 @@
1
+ // Once a day, check npm for a newer leto and tell the user.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { HOME_DIR } from './config.js';
5
+ import { VERSION } from './version.js';
6
+
7
+ const STATE = path.join(HOME_DIR, 'state.json');
8
+ const DAY = 24 * 60 * 60 * 1000;
9
+
10
+ const newer = (a, b) => {
11
+ const pa = a.split(/[.-]/).map(Number);
12
+ const pb = b.split(/[.-]/).map(Number);
13
+ for (let i = 0; i < 3; i++) if ((pa[i] || 0) !== (pb[i] || 0)) return (pa[i] || 0) > (pb[i] || 0);
14
+ return false;
15
+ };
16
+
17
+ export async function checkForUpdate() {
18
+ if (process.env.LETO_NO_UPDATE_CHECK || process.env.CI) return null;
19
+ let state = {};
20
+ try {
21
+ state = JSON.parse(fs.readFileSync(STATE, 'utf8'));
22
+ } catch {}
23
+ if (!state.lastCheck || Date.now() - state.lastCheck > DAY) {
24
+ try {
25
+ const res = await fetch('https://registry.npmjs.org/@mumbrane/leto/latest', { signal: AbortSignal.timeout(2000) });
26
+ if (res.ok) state.latest = (await res.json()).version;
27
+ state.lastCheck = Date.now();
28
+ fs.mkdirSync(HOME_DIR, { recursive: true });
29
+ fs.writeFileSync(STATE, JSON.stringify(state));
30
+ } catch {}
31
+ }
32
+ return state.latest && newer(state.latest, VERSION) ? state.latest : null;
33
+ }
package/src/usage.js ADDED
@@ -0,0 +1,83 @@
1
+ // Usage reports: every model request is recorded in ~/.leto/usage.jsonl
2
+ // (time, user, project, session, model, tokens, estimated cost), and
3
+ // `leto usage` sums it up by day, model, project or user. When a managed
4
+ // policy sets usageEndpoint, records are also sent there in batches.
5
+ import fs from 'node:fs';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { HOME_DIR } from './config.js';
9
+ import { loadPolicy } from './policy.js';
10
+
11
+ export const USAGE_FILE = path.join(HOME_DIR, 'usage.jsonl');
12
+ const user = (() => {
13
+ try {
14
+ return os.userInfo().username;
15
+ } catch {
16
+ return 'unknown';
17
+ }
18
+ })();
19
+
20
+ let outbox = [];
21
+ let timer = null;
22
+
23
+ export function recordUsage(rec) {
24
+ const line = { t: new Date().toISOString(), user, ...rec };
25
+ try {
26
+ fs.mkdirSync(HOME_DIR, { recursive: true });
27
+ fs.appendFileSync(USAGE_FILE, JSON.stringify(line) + '\n', { mode: 0o600 });
28
+ } catch {}
29
+ const endpoint = loadPolicy()?.usageEndpoint;
30
+ if (endpoint) {
31
+ outbox.push(line);
32
+ if (!timer) timer = setTimeout(() => flushUsage(), 5000);
33
+ timer.unref?.();
34
+ }
35
+ }
36
+
37
+ export async function flushUsage() {
38
+ clearTimeout(timer);
39
+ timer = null;
40
+ const endpoint = loadPolicy()?.usageEndpoint;
41
+ if (!endpoint || !outbox.length) return;
42
+ const batch = outbox;
43
+ outbox = [];
44
+ try {
45
+ await fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ records: batch }), signal: AbortSignal.timeout(5000) });
46
+ } catch {
47
+ outbox.unshift(...batch.slice(-1000));
48
+ }
49
+ }
50
+
51
+ export function readUsage({ days = 30 } = {}) {
52
+ let raw = '';
53
+ try {
54
+ raw = fs.readFileSync(USAGE_FILE, 'utf8');
55
+ } catch {
56
+ return [];
57
+ }
58
+ const since = Date.now() - days * 86400000;
59
+ return raw.split('\n').filter(Boolean).map((l) => {
60
+ try {
61
+ return JSON.parse(l);
62
+ } catch {
63
+ return null;
64
+ }
65
+ }).filter((r) => r && Date.parse(r.t) >= since);
66
+ }
67
+
68
+ export function summarize(records, by = 'day') {
69
+ const key = (r) => (by === 'day' ? r.t.slice(0, 10) : by === 'model' ? r.model : by === 'project' ? r.project : by === 'user' ? r.user : r.session);
70
+ const groups = new Map();
71
+ for (const r of records) {
72
+ const k = key(r) ?? '(unknown)';
73
+ const g = groups.get(k) ?? { key: k, requests: 0, input: 0, output: 0, cost: 0, sessions: new Set() };
74
+ g.requests++;
75
+ g.input += (r.input ?? 0) + (r.cache_read ?? 0) + (r.cache_write ?? 0);
76
+ g.output += r.output ?? 0;
77
+ g.cost += r.cost ?? 0;
78
+ if (r.session) g.sessions.add(r.session);
79
+ groups.set(k, g);
80
+ }
81
+ const rows = [...groups.values()].map((g) => ({ ...g, sessions: g.sessions.size }));
82
+ return by === 'day' ? rows.sort((a, b) => a.key.localeCompare(b.key)) : rows.sort((a, b) => b.cost - a.cost || b.requests - a.requests);
83
+ }