@mumbrane/leto 0.19.1 → 0.20.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 CHANGED
@@ -22,7 +22,7 @@ A coding agent for your terminal, built by Mumbrane. It reads your code, edits f
22
22
  npm install -g @mumbrane/leto
23
23
  ```
24
24
 
25
- Requires Node.js 18.17 or later.
25
+ Requires Node.js 22 or later.
26
26
 
27
27
  ## Set up
28
28
 
@@ -52,6 +52,7 @@ leto -p --max-cost 0.50 "…" # stop if the estimated cost passes $0.50
52
52
  leto -c # continue the last session in this directory
53
53
  leto -r <id> # resume a specific session
54
54
  leto sessions # list recent sessions
55
+ leto audit [id] [--json] # commands run, files written and hosts contacted, and who allowed each
55
56
  ```
56
57
 
57
58
  In a session:
@@ -87,7 +88,7 @@ In a session:
87
88
  | `/ide` | Editor connection: install the VS Code / Cursor extension, diffs on or off |
88
89
  | `/orchestrate` | Orchestrator mode: a brain model delegates work to a team of models |
89
90
  | `/check [cmd]` | Choose the check (typecheck, lint, tests) that runs after edits |
90
- | `/sandbox` | Toggle the shell sandbox (`/sandbox network` allows network) |
91
+ | `/sandbox` | Toggle the shell sandbox (`/sandbox network` allows the whole network, not just the allowlist) |
91
92
  | `/agents` | Browse and create custom sub-agents |
92
93
  | `/branches` | Review, merge or delete branches from worktree agents |
93
94
  | `/continue` | Pick up a turn that was interrupted or crashed |
@@ -186,6 +187,8 @@ Installed plugins live in `~/.leto/plugins/` and their skills, agents, commands
186
187
  "providers": { "custom": { "baseUrl": "https://llm.internal.example/v1" } },
187
188
  "disableYolo": true,
188
189
  "forceSandbox": true,
190
+ "sandboxAllow": ["registry.npmjs.org", ".github.com"],
191
+ "allowedMcpServers": ["github", "mcp.internal.example"],
189
192
  "disabledTools": ["browser"],
190
193
  "maxCostPerSession": 20,
191
194
  "disablePlugins": false,
@@ -193,6 +196,22 @@ Installed plugins live in `~/.leto/plugins/` and their skills, agents, commands
193
196
  }
194
197
  ```
195
198
 
199
+ Every key is optional:
200
+
201
+ | Key | Effect |
202
+ | --- | --- |
203
+ | `allowedProviders` | Only these providers can be used |
204
+ | `allowedModels` | Only models matching one of these regular expressions can be used |
205
+ | `providers` | Fixes a provider's settings, such as `baseUrl`, over the user's config |
206
+ | `disableYolo` | No `--yolo` or `/yolo` |
207
+ | `forceSandbox` | Shell commands are always sandboxed |
208
+ | `sandboxAllow` | The only hosts sandboxed commands may reach; the user cannot add hosts or turn on `/sandbox network` |
209
+ | `allowedMcpServers` | MCP servers that may load, by name (local) or URL host (remote); others never start and the user is told at startup |
210
+ | `disabledTools` | Tools that are removed |
211
+ | `maxCostPerSession` | Dollar cap per session |
212
+ | `disablePlugins` | Plugins, and the MCP servers and skills they bring, are not loaded |
213
+ | `usageEndpoint` | Usage records are also sent here |
214
+
196
215
  **Usage reports.** Every request is recorded in `~/.leto/usage.jsonl`: time, user, project, session, model, tokens and estimated cost. `leto usage` sums it up (`--by day|model|project|user|session`, `--days 30`, `--json`). With `usageEndpoint` in the policy, records are also sent there in batches, for company-wide reporting.
197
216
 
198
217
  ## Self-checking
@@ -204,7 +223,15 @@ leto checks its own work while it can still fix it:
204
223
 
205
224
  ## Sandbox
206
225
 
207
- `leto --sandbox` (or `/sandbox`, or `leto config set sandbox on`) runs shell commands in an OS sandbox: they can write only inside the project and temp folders, can't read credentials (`~/.ssh`, `~/.aws`, `~/.leto`, keychains…), and have no network except localhost. Because a sandboxed command can't harm anything outside the project, it runs without asking. When a command really needs more (installing packages, pushing), leto asks to run that one outside the sandbox. `/sandbox network` allows network access. macOS uses the built-in `sandbox-exec`; Linux needs bubblewrap (`apt install bubblewrap`).
226
+ Shell commands run in an OS sandbox by default on macOS (on Linux, turn it on with `leto config set sandbox on`): they can write only inside the project and temp folders, can't read credentials (`~/.ssh`, `~/.aws`, `~/.leto`, keychains…), and reach the network only through an allowlist. Because a sandboxed command can't harm anything outside the project, it runs without asking. When a command really needs more (pushing over SSH, writing elsewhere), leto asks to run that one outside the sandbox. macOS uses the built-in `sandbox-exec`; Linux needs bubblewrap (`apt install bubblewrap`). Without either, leto says so once and commands ask as usual.
227
+
228
+ Turn it off with `leto config set sandbox off` (or `LETO_SANDBOX=0`, or `/sandbox` for this session); `--yolo` runs commands unsandboxed unless you also pass `--sandbox`. A policy with `forceSandbox` keeps it on.
229
+
230
+ **Network allowlist.** Sandboxed commands can connect only to localhost. leto runs a small HTTP/HTTPS proxy for them and sets `HTTP_PROXY`/`HTTPS_PROXY` (and the lowercase, npm, yarn, pip and cargo spellings, which git and Go also read). The proxy lets through only allowlisted hosts on ports 443 and 80; by default npm, Yarn, PyPI, crates.io, GitHub (with `githubusercontent.com`) and the Go module proxy. Add hosts with `leto config set sandboxAllow "example.com,.internal.dev,my.host:8443"`: a name matches exactly, a leading dot matches its subdomains, and `host:port` allows another port. IP addresses, and names that resolve to loopback, link-local or private addresses, are always refused, so nothing in the sandbox reaches your machine or network through the proxy. A policy's `sandboxAllow` replaces the list. `/sandbox network` (or `leto config set sandboxNetwork on`) allows the whole network instead. On Linux the allowlist isn't available yet: sandboxed commands have no network beyond their own localhost.
231
+
232
+ **Untrusted content.** Results of `web_fetch`, `web_search`, the browser and MCP tools reach the model between `<untrusted-data-…>` tags whose suffix is random for each run and named in the system prompt, which tells the model that everything inside is data written by others, never instructions. Any copy of the marker inside the content is removed, so a page can't close the block early. You see the results without the tags.
233
+
234
+ **Secret redaction.** Before a tool result is shown, logged in the session, passed to hooks or sent to the model, leto replaces secrets with `[REDACTED SECRET]`: your provider API keys, values of environment variables whose names end in `KEY`, `TOKEN`, `SECRET` or `PASSWORD` (16 characters or longer), and well-known formats (`sk-…` keys, GitHub tokens, AWS access key IDs, Slack tokens, PEM private keys, JWTs in `Authorization` headers). Files on disk are never changed: a file the model writes keeps the real value, and the edit tools refuse input that contains the placeholder, so it can't overwrite a secret.
208
235
 
209
236
  ## Parallel work in worktrees
210
237
 
@@ -309,6 +336,12 @@ leto eval compare before.json after.json
309
336
 
310
337
  A suite is a JSON file of tasks. Each task gives the starting code (inline `files`, a local folder, or a git `repo` + `commit`), an optional `setup` command, the `prompt`, and a `check` command (exit code 0 = pass). Every run gets a fresh copy, leto works on it with `--yolo`, then the check decides. You get the pass rate, cost, tokens, tool calls and time per task, saved as JSON; `compare` shows which tasks got better or worse between two runs (say, two checkpoints of your model). `--tool-mode text` evaluates text tool calling.
311
338
 
339
+ ## CI
340
+
341
+ `.github/workflows/ci.yml` runs `node test/run.js` on every pull request and push to main, on Node 22 and 24, on Linux and macOS.
342
+
343
+ `.github/workflows/evals.yml` runs `leto eval` (the `core` suite by default) when you start it from the Actions tab (pick a model, a suite and a max cost per task, above 0 and at most $2) and when a release is published. It uploads the result JSON as an artifact, writes the pass rate to the job summary, and fails if it dropped more than 5 points below the last successful run (compared only when that run used the same suite and model) or if no agent run succeeded at all (a wrong key or provider). It needs a repository secret `LETO_API_KEY` (and optionally `LETO_PROVIDER`, default `anthropic`); without the key it skips with a notice. It never runs on pull requests. To run the same thing yourself: `leto eval core -m <model> --max-cost 0.5 -o result.json`, then `leto eval compare old.json result.json`.
344
+
312
345
  ## SDK and scripting
313
346
 
314
347
  Use leto from your own code:
package/bin/leto.js CHANGED
@@ -1,6 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import '../src/legacy.js';
3
- import { main } from '../src/cli.js';
2
+ // Checked before anything loads: older Node fails later, in ways that don't say why.
3
+ if (Number(process.versions.node.split('.')[0]) < 22) {
4
+ console.error(`leto needs Node.js 22 or later; this is ${process.versions.node}. Install it from https://nodejs.org.`);
5
+ process.exit(1);
6
+ }
7
+ await import('../src/legacy.js');
8
+ const { main } = await import('../src/cli.js');
4
9
 
5
10
  main(process.argv.slice(2)).catch((err) => {
6
11
  console.error(`leto: ${err?.message ?? err}`);
@@ -0,0 +1,243 @@
1
+ # The `leto serve` protocol
2
+
3
+ `leto serve [--mode ask|acceptEdits|plan|yolo] [-m model] [--sandbox] [--yolo]` runs one long-lived
4
+ session for another program to drive, such as the Leto desktop app. It reads commands from stdin and
5
+ writes events to stdout, one JSON object per line each way. Closing stdin ends the session like a
6
+ `shutdown` command. Diagnostics that are not events go to stderr.
7
+
8
+ The session is set up like an interactive `leto` run in the current directory (config, provider,
9
+ model, `~/.leto`, MCP servers, hooks, skills and agents), except that an untrusted project's own MCP
10
+ servers, hooks, skills and agents are skipped instead of asking (an `info` event says so).
11
+
12
+ This is protocol 2. Everything protocol 1 had still works the same way: new fields are added to
13
+ existing events, never renamed or removed, and a client that ignores what it doesn't know keeps
14
+ working. `ready.protocol` and `ready.capabilities` say what this leto speaks; a leto without
15
+ `protocol` speaks protocol 1.
16
+
17
+ ## Requests and errors
18
+
19
+ Any command may carry `req`, a string of at most 200 characters. Every event that answers that
20
+ command echoes it, including its `error`: `mode` for `set_mode`, and for `send` its `attached`,
21
+ `queued`, `steered`, `turn_start` and `result`, and for `compact` its `compact` events. Events
22
+ a turn streams along the way (`text`, `tool_start`, ...) carry no `req`.
23
+
24
+ Every field is checked. A line that is not a JSON object, an unknown `type`, a field of the wrong type
25
+ or size, a value outside its list, or an `id` nothing waits on answers with an `error` event (with the
26
+ command's `req` when it had a valid one); the loop keeps running. `send` text is limited to 1,000,000
27
+ characters, ids to 64, `images` and `files` to 20 each.
28
+
29
+ ## Attachments
30
+
31
+ `send` can carry bytes inline, so a client works the same when leto runs on another machine (over SSH):
32
+
33
+ - `images`: `[{path} | {data, media_type}]`. `data` is base64, `media_type` one of `image/png`,
34
+ `image/jpeg`, `image/gif`, `image/webp` (a path's type comes from its extension). At most 5 MB each.
35
+ - `files`: `[{path} | {name, data}]`. A text file is put into the message like an `@path` mention
36
+ (cut at 100,000 characters). A PDF (a name ending in `.pdf`) is attached as a document, up to 30 MB,
37
+ for Claude on the Anthropic provider; other providers can't take one, so it is refused.
38
+
39
+ Paths are read on the machine leto runs on, relative to its `cwd`. Anything that can't be attached is
40
+ listed in the `attached` event with the reason (and also sent as an `error`, as protocol 1 did for
41
+ `@image` mentions that could not be read); the message is sent without it.
42
+
43
+ ## Queue and steering
44
+
45
+ A `send` while a turn runs waits for it: the answer is `queued` `{position}` (1 is next), and when
46
+ its turn starts, `turn_start`. Queued sends run one after another, each with its own `result`.
47
+ `unqueue` with a queued send's `req` removes it, so give sends a `req` to be able to take them back. At most 50 sends can wait (queued or steering); one more gets an `error`.
48
+ `interrupt` stops only the running turn: the queue stays and its next send starts right after the
49
+ interrupted turn's `result`. To drop everything, `unqueue` each send first, then `interrupt`.
50
+
51
+ `send` with `steer: true` puts the message into the running turn instead, at the next point where
52
+ the model is about to be asked again (after the tool calls it made have their results). `steered`
53
+ says it went in; the running turn's `result` then covers it. If the turn ends before that point (it
54
+ finished, was interrupted or failed), the message runs as the next turn, ahead of the queue (a
55
+ `turn_start` with its `req`). A steered message can't be taken back. With no turn running, a steered
56
+ send starts a turn like any other.
57
+
58
+ ## Compaction
59
+
60
+ When the conversation gets close to the context window, older turns are summarized so the work can
61
+ go on. leto does this itself at 80% of the window before a model request; on Claude models with
62
+ server-side compaction, Claude does it inside a request. The model can also ask for it (its `leto`
63
+ tool), and the client with `compact`. Every compaction is reported the same way, with `compact`
64
+ events (`before` and `after` are context tokens, estimated where no API response says):
65
+
66
+ - `start` `{before}` (`after` is `null`), then `done` `{before, after}`, or `failed` `{before, after, error}`
67
+ (the summary request failed or was interrupted; the history is unchanged, so `after` equals `before`).
68
+ - Server-side compaction is only known once Claude's answer arrives, so it sends `done` alone.
69
+ - `compact` with no turn running runs right away, like a turn: sends queue behind it and `interrupt`
70
+ stops it. With nothing to summarize yet it answers `failed` with `error` "Nothing to compact yet.".
71
+ During a turn it runs before the turn's next model request (or, if the turn has none left, before
72
+ the first one of the next turn). Its `compact` events carry the command's `req`.
73
+
74
+ ## Checkpoints, rewind and sessions
75
+
76
+ Before leto writes or edits a file in a turn, it saves the original (a checkpoint). `checkpoints`
77
+ lists the turns that changed files; `undo` puts files back; `rewind` goes back to before one of your
78
+ messages. Changes made by shell commands (`bash`) are not checkpointed, so they are never restored;
79
+ `undone` and `rewound` say so in `note`. A file that can't be written back is listed in `failed`
80
+ with the reason and the others are still restored.
81
+
82
+ A rewind point is the `index` of one of your messages in the conversation (the `index` of a
83
+ checkpoint is the message its turn started at). Compaction rewrites the conversation, so it also
84
+ moves every checkpoint's `index`; a turn that started inside the summarized part has `index: null`
85
+ and can't be rewound to (a rewind to an `index` that is not one of your messages is refused, never
86
+ guessed). Sessions compacted by a leto before protocol 2 may still carry old indexes.
87
+
88
+ `rewind`, `fork` and `clear` change the live session: each answers with `session`
89
+ `{session_id, reason}` (`rewind`, `fork` or `clear`), then `todos` (the task list, reset) and `context`
90
+ (the meter, reset). The model's notes, system prompt and checkpoints are those of the new session. The
91
+ old session stays saved (see `sessions`). All these commands work only while no turn runs; during one
92
+ they answer with an `error`.
93
+
94
+ ## Memory
95
+
96
+ `memory` with `op: "list"`, `"add"` (with `text`, at most 400 characters) or `"remove"` (with `index`, the
97
+ position in the list) works on the project's learned notes (`src/memory.js`). The answer is `memory`
98
+ `{notes}`, the whole list. A change also tells the running model in a note on its next message, because the
99
+ system prompt is frozen after the first turn. `memory` is also sent when the model's own `memory` tool
100
+ adds or removes a note, so a client can keep the list in sync from these events alone. It is refused
101
+ during a turn, like the other commands that change the session.
102
+
103
+ ## Sub-agents
104
+
105
+ Every event from a sub-agent's run (`tool_start`, `tool_result`, `agent_progress`) carries `agent_id`,
106
+ the `id` of the `task` call that started it, so parallel tasks can be told apart; `agent` keeps the
107
+ label. A sub-agent nested inside another keeps the top-level task's `agent_id`. The main agent's events
108
+ have `agent_id: null`. Sub-agent tools now send `tool_result` too (protocol 1 sent only their `tool_start`).
109
+
110
+ The `task` call's own `tool_result` has `agent_usage` `{tokens, cost_usd, tool_calls}`: input plus output
111
+ tokens the sub-agent used, its estimated cost (`null` when the model has no known price) and how many
112
+ tools it called. While it runs, `agent_progress` `{agent_id, tokens}` is sent after each of its model
113
+ responses, at most four times a second per task. These tokens are also in the session's `usage`.
114
+
115
+ ## Live output and background processes
116
+
117
+ While a `bash` call runs, `tool_output` `{id, text}` sends what it prints, with the call's `id`: at
118
+ most four events a second, and at most 100,000 characters per call (the rest is not streamed). It is
119
+ only a preview: the `tool_result` still has the complete output. Only the main agent's calls stream.
120
+
121
+ `processes` lists the background processes (`bash` with `run_in_background`) of this session,
122
+ `process_output` returns the last 30,000 characters of one's output, and `kill_process` stops one.
123
+ Looking at the output does not mark it as read for the model. `process_exit` `{id, code}` is sent when
124
+ a process ends, by itself, by the model or by `kill_process` (`code` is 128 when a signal stopped it, -1
125
+ when it never started); the answer to `kill_process` is that event, with its `req`.
126
+
127
+ ## State events
128
+
129
+ `mode`, `effort`, `model` and `sandbox` are sent whenever that state changes, whoever changed it: a
130
+ command from the client, or the model through its `leto` tool (entering plan mode, a plan being
131
+ approved, changing its effort, turning the sandbox on). A client can keep its view of the session in
132
+ sync from these events alone.
133
+
134
+ ## Commands (stdin)
135
+
136
+ | Command | Fields | What it does |
137
+ |---|---|---|
138
+ | `send` | `text`, `images`, `files`, `steer` | Start a turn. `@path` mentions attach files and images as in the terminal; `images` and `files` attach more (see Attachments). While a turn runs, the send is queued, or with `steer: true` joins the running turn (see Queue and steering). An `error` if `text` is empty. |
139
+ | `unqueue` | `req` | Remove the queued send with this `req`. Answers with `unqueued`. |
140
+ | `compact` | `focus` (optional string, at most 10,000 characters) | Summarize the older conversation now, keeping what `focus` names. Answers with `compact` events (see Compaction). |
141
+ | `interrupt` | | Stop the running turn. Every open `permission_request` and `question` is answered "no". Queued sends stay queued and the next one starts. |
142
+ | `permission` | `id`, `answer` | Answer a `permission_request`: `yes`, `always`, `prefix` (always allow commands that start with the request's `prefix`) or `no`; any other string counts as `no`. |
143
+ | `answer` | `id`, `answer` | Answer a `question`: a string, a list of strings (joined with ", "), or `null`/`""` to skip it. |
144
+ | `set_mode` | `mode` | `ask`, `acceptEdits`, `plan` or `yolo` (yolo can be forbidden by policy). Answers with `mode`. |
145
+ | `set_model` | `model` | Use another model of the same provider from the next request on. The context window becomes the one the provider lists for that model, else the one a fresh start would use (`LETO_CONTEXT_WINDOW` still wins). A model the provider doesn't list answers with an `error`: switching providers needs a new session (`leto setup`). Answers with `model`. |
146
+ | `set_effort` | `level` | `low`, `medium`, `high`, `xhigh` or `max`, for Claude models that support it. Answers with `effort`. |
147
+ | `set_sandbox` | `on`, `network` (booleans, either or both) | Turn the shell sandbox on or off and allow it the network or not. The client is the user, so turning the sandbox off or the network on needs no further approval (the model has to ask for those). An `error` if no sandbox is available or policy keeps it on. Answers with `sandbox`. |
148
+ | `trust` | | Trust the project folder (saved in `~/.leto/config.json`, like answering yes in the terminal), then load its MCP servers, hooks, skills and agents that were skipped at start. MCP servers restart, so an `error` while a turn is running. Answers with `trusted`. |
149
+ | `checkpoints` | | List the turns that changed files. Answers with `checkpoints`. |
150
+ | `undo` | `to` (optional turn id) | Put files back as they were before turn `to` (default: the latest turn), and every turn after it. The conversation is untouched. Answers with `undone`. |
151
+ | `rewind` | `index`, `files` (boolean) | Continue from before the message at `index`: a new session holds the messages before it, and with `files: true` the files leto changed since are restored. Answers with `rewound`, then `session`. |
152
+ | `fork` | `index` (optional) | A new session from the first `index` messages (default: all of them); files untouched. Answers with `session`. |
153
+ | `clear` | | A new empty session. Answers with `session`. |
154
+ | `sessions` | | List saved sessions. Answers with `sessions`. |
155
+ | `rename` | `title` (at most 200 characters, kept to 70) | Name the current session. Answers with `renamed`. |
156
+ | `export` | | The conversation as Markdown. Answers with `exported`. |
157
+ | `memory` | `op` (`list`, `add`, `remove`), `text` (add), `index` (remove) | List, add or remove the project's notes (see Memory). Answers with `memory`. |
158
+ | `processes` | | List the background processes. Answers with `processes`. |
159
+ | `process_output` | `id` | The end of a background process's output. Answers with `process_output`. |
160
+ | `kill_process` | `id` | Stop a background process. Answers with `process_exit`. |
161
+ | `shutdown` | | End the session: queued and steered sends are dropped, a running turn is interrupted and allowed to wind down, MCP servers and the browser are closed. |
162
+
163
+ ## Events (stdout)
164
+
165
+ `req` is also on every event that answers a command (see Requests and errors); it is left out below.
166
+
167
+ | Event | Fields | When |
168
+ |---|---|---|
169
+ | `ready` | `protocol` (`2`), `capabilities`, `version`, `session_id`, `model`, `provider` (id, for example `anthropic`), `effort` (level or `null` for the model's default), `context_window`, `cwd`, `mode`, `sandbox` `{on, network}`, `trusted` | Once, after setup and before any command is read. `trusted` is `false` when the project's own MCP servers, hooks, skills or agents were skipped because the folder is not trusted. |
170
+ | `mode` | `mode` | The mode changed (see State events). |
171
+ | `effort` | `level` | The effort changed. |
172
+ | `model` | `model`, `context_window` | The model changed. |
173
+ | `sandbox` | `on`, `network` | The sandbox changed. |
174
+ | `trusted` | `trusted: true` | The answer to `trust`. |
175
+ | `context` | `used`, `window` | After each model response: the tokens the conversation takes (exact from the API's usage plus an estimate for what was added since). |
176
+ | `compact` | `phase` (`start`, `done`, `failed`), `before`, `after`, `error?` | A compaction, whoever caused it (see Compaction). |
177
+ | `session` | `session_id`, `reason` (`rewind`, `fork`, `clear`) | The live session changed. |
178
+ | `checkpoints` | `checkpoints`: `[{id, label, time, files, index}]`, oldest first | The answer to `checkpoints`; `files` are absolute paths. |
179
+ | `undone` | `restored`: `[{file, action: "restored"\|"removed"}]`, `failed`: `[{file, error}]`, `note` | The answer to `undo`. |
180
+ | `rewound` | `previous`, `text`, `restored`, `failed`, `note` | The answer to `rewind`; `previous` is the old session's id, `text` the message rewound to, for the client's input. |
181
+ | `sessions` | `current`, `sessions`: `[{id, cwd, model, updated, messages, title}]` | The answer to `sessions`, most recently updated first. |
182
+ | `renamed` | `title` | The answer to `rename`. |
183
+ | `exported` | `markdown` | The answer to `export`. |
184
+ | `memory` | `notes`: `[string]` | The answer to `memory`, and whenever the model's `memory` tool changes the notes. |
185
+ | `processes` | `processes`: `[{id, command, running, code}]` | The answer to `processes`; `code` is `null` while running. |
186
+ | `process_output` | `id`, `text`, `running`, `code` | The answer to `process_output`. |
187
+ | `process_exit` | `id`, `code` | A background process ended, or the answer to `kill_process`. |
188
+ | `info` | `message` | A notice (for example that project MCP servers were skipped). |
189
+ | `error` | `message` | A failed command, or an error during a turn (the API rejected a request, a tool crashed). |
190
+ | `attached` | `attached`, `refused`: `[{name, reason}]` | What a `send` attached, as the terminal labels it (`src/app.js`, `🖼 shot.png`, `📄 spec.pdf`). Only sent when either list has something. |
191
+ | `queued` | `position` | The send waits behind the running turn (1 is next). |
192
+ | `unqueued` | | The answer to `unqueue`. |
193
+ | `steered` | `text` | A steered send went into the running turn. |
194
+ | `turn_start` | `text` | A send's turn starts, right away or when its place in the queue comes. |
195
+ | `text` | `text` | A chunk of the answer. |
196
+ | `thinking` | `text` | A chunk of visible reasoning. |
197
+ | `tool_pending` | `name` | The model has started writing a call to this tool (a whole file can take a minute). |
198
+ | `progress` | `name`, `tokens` | Tokens of that call written so far, at most four times a second. |
199
+ | `tool_start` | `tool` (what to show, for example `Bash`), `summary`, `agent` (the sub-agent's label, `null` for the main agent), `agent_id` (see Sub-agents), `id`, `name` (`bash`), `input` | A tool call starts; `id` pairs it with its result. |
200
+ | `tool_output` | `id`, `text` | Live output of a running `bash` call (see Live output and background processes). |
201
+ | `tool_result` | `result`, `is_error`, `id`, `agent_id`, `lines` (the diff or lines to show, `[{sign: "+"\|"-"\|" ", text, n?}]`, or `null`), `images` (paths of images the tool returned, saved under `~/.leto/images`, or `null`), `agent_usage` (only on a `task` call) | A call finished. |
202
+ | `agent_progress` | `agent_id`, `tokens` | A sub-agent is working (see Sub-agents). |
203
+ | `todos` | `todos`: `[{content, status, ...}]` | The task list changed. |
204
+ | `permission_request` | `id` (`p1`, ...), `tool`, `title`, `input`, `lines`, `prefix` (the command prefix a `bash` request can always be allowed by, or `null`), `once` (true when "always" makes no sense: approving a plan, a `leto` self-change) | The tool waits for a `permission` command with this `id`. |
205
+ | `question` | `id` (`q1`, ...), `question`, `header`, `options`: `[{label, description?}]`, `multi_select` | The model asks the user; answer with `answer`. |
206
+ | `result` | `ok`, `result` (the last answer's text), `error` (why it failed, or `null`), `session_id`, `model`, `tool_calls`, `duration_ms`, `usage` (the session's cumulative `{input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, requests}`), `cost_usd` (cumulative, `null` when the model has no known price), `turn_usage` (the same fields for this turn alone), `turn_cost_usd` (each request priced with the model that served it, which can differ from `model` after a fallback or `set_model`; `null` when one had no known price), `context` `{used, window}` | The end of every turn, also after an interrupt or an error. |
207
+
208
+ ## Capabilities
209
+
210
+ `ready.capabilities` lists the protocol 2 features this leto has:
211
+
212
+ | Capability | What it adds |
213
+ |---|---|
214
+ | `req` | `req` on commands, echoed on the events that answer them |
215
+ | `state_events` | `mode`, `effort`, `model` and `sandbox` events whoever changes the state |
216
+ | `set_sandbox` | the `set_sandbox` command |
217
+ | `trust` | the `trust` command |
218
+ | `attachments` | inline `images` and `files` on `send`, and `attached` |
219
+ | `queue` | sends during a turn are queued; `queued`, `unqueue`, `unqueued` |
220
+ | `steer` | `send` with `steer: true`, and `steered` |
221
+ | `compact` | the `compact` command and `compact` events |
222
+ | `turn_usage` | `turn_usage` and `turn_cost_usd` on `result` |
223
+ | `context` | `context` events and `context` on `result` |
224
+ | `checkpoints` | `checkpoints`, `undo`, and their events |
225
+ | `rewind` | `rewind`, `fork`, `clear`, and `session` |
226
+ | `sessions` | `sessions`, `rename`, `export`, and their events |
227
+ | `memory` | the `memory` command and event |
228
+ | `agent_ids` | `agent_id` on sub-agent events, their `tool_result`, `agent_usage`, `agent_progress` |
229
+ | `tool_output` | `tool_output` events |
230
+ | `processes` | `processes`, `process_output`, `kill_process`, `process_exit` |
231
+
232
+ ## Compatibility
233
+
234
+ - Fields and events are only ever added. A client ignores what it doesn't know: that is how an older app
235
+ works with a newer leto, and an app written for protocol 1 sees the events it always did (plus the new
236
+ fields on them). It does see tool results from sub-agents now, and `agent_id` (null for the main agent)
237
+ on `tool_start` and `tool_result`.
238
+ - A client uses a feature only if its name is in `ready.capabilities`; a missing capability means an
239
+ older leto, and a command for it would answer with an `error` ("Unknown command type"). A leto without
240
+ `ready.protocol` speaks protocol 1: a client treats it as having no capabilities at all.
241
+ - `permission_request` and `question` keep their protocol 1 shape, so an app that only answers those
242
+ still works.
243
+ - `capabilities` only grows; a capability is not removed or changed in meaning within protocol 2.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mumbrane/leto",
3
- "version": "0.19.1",
3
+ "version": "0.20.0",
4
4
  "description": "Leto: a coding agent for your terminal, built by Mumbrane",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -16,10 +16,11 @@
16
16
  "bin",
17
17
  "src",
18
18
  "vscode",
19
+ "docs",
19
20
  "evals/core"
20
21
  ],
21
22
  "engines": {
22
- "node": ">=18.17"
23
+ "node": ">=22"
23
24
  },
24
25
  "repository": {
25
26
  "type": "git",
package/src/agent.js CHANGED
@@ -2,6 +2,7 @@ import { streamChat, completeText } from './client.js';
2
2
  import { toolSchemas, executeToolCall, truncate, READ_ONLY_TOOLS, PARALLEL_SAFE } from './tools.js';
3
3
  import { buildSystemPrompt } from './prompt.js';
4
4
  import { Session } from './session.js';
5
+ import { Checkpoints } from './checkpoints.js';
5
6
  import { isNativeAnthropic, streamAnthropic, completeAnthropic, serverCompaction } from './anthropic.js';
6
7
  import { Usage } from './pricing.js';
7
8
  import { runCheck, condense } from './verify.js';
@@ -45,7 +46,7 @@ function wait(ms, signal) {
45
46
  export function estimateTokens(messages) {
46
47
  let chars = 0;
47
48
  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
+ if (Array.isArray(m.content)) for (const p of m.content) chars += p.type === 'image_url' ? 6400 : p.type === 'document' ? p.document.url.length / 2 : String(p.text ?? '').length;
49
50
  else chars += String(m.content ?? '').length;
50
51
  if (m.tool_calls) chars += JSON.stringify(m.tool_calls).length;
51
52
  if (m.images) chars += m.images.length * 6400;
@@ -59,7 +60,7 @@ const textOf = (content) => (Array.isArray(content) ? content.map((p) => (p.type
59
60
 
60
61
  export class Agent {
61
62
  // 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
+ constructor({ config, session, ui, permissions, cwd, depth = 0, label = '', toolFilter = null, checkpoints = null, hooks = null, usage = null, agentId = null, spent = null }) {
63
64
  this.config = config;
64
65
  this.session = session;
65
66
  this.ui = ui;
@@ -71,7 +72,10 @@ export class Agent {
71
72
  this.checkpoints = checkpoints;
72
73
  this.hooks = hooks;
73
74
  this.notes = []; // things to tell the model with the next message (e.g. an undo)
75
+ this.steering = []; // user messages for the running turn (serve's steer): { content, taken? }
74
76
  this.usage = usage ?? new Usage();
77
+ this.agentId = agentId; // the top-level task call this sub-agent runs for (nested ones keep it)
78
+ this.spent = spent ?? { tokens: 0, cost: 0, unpriced: false }; // this task's share of the shared usage
75
79
  // The system prompt is built once and then frozen: changing it mid-session
76
80
  // invalidates the prompt cache (and, on Claude, earlier thinking blocks).
77
81
  this.systemPrompt = null;
@@ -109,21 +113,8 @@ export class Agent {
109
113
 
110
114
  // Run one user turn to completion. Returns true on success.
111
115
  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 });
116
+ if (!(await this.promptHook(input))) return false;
117
+ this.session.add({ role: 'user', content: this.withNotes(input) });
127
118
  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
119
  this.checkRounds = 0;
129
120
  this.abort = new AbortController();
@@ -140,13 +131,21 @@ export class Agent {
140
131
  this.pendingCompact = null;
141
132
  await this.maybeCompact(signal, true, focus);
142
133
  } else await this.maybeCompact(signal);
134
+ // Messages steered into this turn join here, where every tool call has its result.
135
+ for (const s of this.steering.splice(0)) {
136
+ if (!(await this.promptHook(s.content))) continue;
137
+ this.session.add({ role: 'user', content: this.withNotes(s.content) });
138
+ s.taken?.();
139
+ }
143
140
  const msg = await this.callModelWithRetry(signal);
141
+ this.onState?.('context');
144
142
  if (this.depth === 0 && this.budget && this.usage.cost >= this.budget) {
145
143
  this.lastError = 'Budget reached.';
146
144
  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
145
  return false;
148
146
  }
149
147
  if (!msg.tool_calls?.length) {
148
+ if (this.steering.length) continue;
150
149
  if (await this.runProjectCheck(signal)) continue;
151
150
  if (this.depth === 0 && this.hooks) await this.hooks.run('Stop', { sessionId: this.session.id });
152
151
  if (this.depth === 0) this.warnContext();
@@ -179,6 +178,26 @@ export class Agent {
179
178
  }
180
179
  }
181
180
 
181
+ // UserPromptSubmit hooks; false when one blocks the message.
182
+ async promptHook(input) {
183
+ if (this.depth > 0 || !this.hooks) return true;
184
+ const text = typeof input === 'string' ? input : input.find((p) => p.type === 'text')?.text ?? '';
185
+ const hook = await this.hooks.run('UserPromptSubmit', { prompt: text, sessionId: this.session.id });
186
+ if (hook.blocked) {
187
+ this.ui.error(`Message blocked by a hook: ${hook.reason}`);
188
+ return false;
189
+ }
190
+ if (hook.output) this.notes.push(`<hook-context>\n${hook.output}\n</hook-context>`);
191
+ return true;
192
+ }
193
+
194
+ // Pending notes ride along with the next user message.
195
+ withNotes(content) {
196
+ if (!this.notes.length) return content;
197
+ const note = this.notes.splice(0).join('\n');
198
+ return typeof content === 'string' ? `${content}\n\n${note}` : [...content, { type: 'text', text: note }];
199
+ }
200
+
182
201
  async runTools(calls, signal) {
183
202
  const ctx = {
184
203
  cwd: this.cwd,
@@ -188,6 +207,7 @@ export class Agent {
188
207
  agent: this,
189
208
  depth: this.depth,
190
209
  label: this.label,
210
+ agentId: this.agentId,
191
211
  allowed: (name) => this.allowsTool(name),
192
212
  checkpoints: this.checkpoints,
193
213
  hooks: this.hooks,
@@ -220,7 +240,7 @@ export class Agent {
220
240
  });
221
241
  }
222
242
 
223
- async runSubagent({ description = 'sub-task', prompt, agent_type = 'explore', isolation = 'none', worker }, signal) {
243
+ async runSubagent({ description = 'sub-task', prompt, agent_type = 'explore', isolation = 'none', worker }, signal, callId = null) {
224
244
  if (!prompt) throw new Error('prompt is required');
225
245
  let member = null;
226
246
  if (worker) {
@@ -254,6 +274,8 @@ export class Agent {
254
274
  checkpoints: wt ? null : this.checkpoints,
255
275
  hooks: this.hooks,
256
276
  usage: this.usage,
277
+ agentId: this.agentId ?? callId,
278
+ spent: this.depth ? this.spent : null,
257
279
  });
258
280
  sub.subagentType = def ? 'custom' : readOnly ? 'explore' : 'general';
259
281
  sub.agentDef = def ?? null;
@@ -276,8 +298,22 @@ export class Agent {
276
298
  report += `\n\n[Worktree] ${wt.result.summary}${wt.result.stat ? `\n${wt.result.stat}` : ''}`;
277
299
  if (wt.result.branch) display += ` → ${wt.result.branch}`;
278
300
  }
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 };
301
+ const s = sub.spent;
302
+ const agentUsage = { tokens: s.tokens, cost_usd: s.unpriced ? null : Number(s.cost.toFixed(6)), tool_calls: sub.toolCount };
303
+ if (!ok) return { content: `Sub-agent "${description}" did not finish: ${sub.lastError}\n\nPartial report:\n${report || '(none)'}`, display, agentUsage };
304
+ return { content: report || '(The sub-agent returned no report.)', display, agentUsage };
305
+ }
306
+
307
+ // Adds a response's usage to the session's and to this task's share of it (exact even with parallel tasks: add is synchronous).
308
+ record(model, u) {
309
+ const t = this.usage;
310
+ const [input, output, cost, unpriced] = [t.input, t.output, t.cost, t.unpriced];
311
+ t.add(model, u);
312
+ const s = this.spent;
313
+ s.tokens += t.input - input + t.output - output;
314
+ s.cost += t.cost - cost;
315
+ s.unpriced ||= t.unpriced > unpriced;
316
+ if (this.agentId) this.ui.agentProgress?.(this.agentId, s.tokens);
281
317
  }
282
318
 
283
319
  // Turn plan mode on or off. Told to the model as a note on the next message,
@@ -354,6 +390,16 @@ export class Agent {
354
390
  return true;
355
391
  }
356
392
 
393
+ // Switch the live conversation, resetting everything that belongs to the old one.
394
+ useSession(session) {
395
+ this.session = session;
396
+ this.checkpoints = new Checkpoints(session.file);
397
+ this.systemPrompt = null;
398
+ this.todos = session.todos ?? [];
399
+ this.notes = [];
400
+ this.contextMark = null;
401
+ }
402
+
357
403
  // Context used, in tokens: exact from the last response, plus an estimate
358
404
  // for messages added since.
359
405
  contextTokens() {
@@ -386,6 +432,7 @@ export class Agent {
386
432
  }
387
433
 
388
434
  async callAnthropic(history, tools, signal) {
435
+ const before = this.contextTokens();
389
436
  let final = null;
390
437
  for await (const ev of streamAnthropic({ config: this.config, history, tools, signal })) {
391
438
  if (ev.type === 'done') final = ev.message;
@@ -396,7 +443,7 @@ export class Agent {
396
443
  else if (ev.type === 'tool_input') this.ui.addTokens?.(ev.text.length / 4);
397
444
  else if (ev.type === 'retry') this.ui.info(' (Claude sent a malformed tool call; retrying)');
398
445
  }
399
- this.usage.add(final.model ?? this.config.model, final.usage);
446
+ this.record(final.model ?? this.config.model, final.usage);
400
447
  let blocks = final.content ?? [];
401
448
  if (blocks.some((b) => b.type === 'compaction') && !this.silent) this.ui.info(' Claude summarized the earlier conversation to free up context.');
402
449
  const text = blocks.filter((b) => b.type === 'text').map((b) => b.text).join('');
@@ -417,6 +464,7 @@ export class Agent {
417
464
  }
418
465
  this.session.add(msg);
419
466
  this.markContext(final.usage);
467
+ if (blocks.some((b) => b.type === 'compaction')) this.onState?.('compact', { phase: 'done', before, after: this.contextTokens() });
420
468
  return msg;
421
469
  }
422
470
 
@@ -453,7 +501,7 @@ export class Agent {
453
501
  });
454
502
  for await (const event of streamChat({ config: this.config, messages, tools: textMode ? [] : tools, signal })) {
455
503
  if (event.usage) {
456
- this.usage.add(this.config.model, event.usage);
504
+ this.record(this.config.model, event.usage);
457
505
  lastUsage = event.usage;
458
506
  }
459
507
  const delta = event.choices?.[0]?.delta;
@@ -525,8 +573,13 @@ export class Agent {
525
573
  if (cut <= 0) {
526
574
  for (let i = messages.length - 1; i > 0; i--) if (messages[i].role === 'user') { cut = i; break; }
527
575
  }
528
- if (cut <= 0) return this.trimToolResults();
576
+ const before = this.contextTokens();
577
+ if (cut <= 0) {
578
+ if (force) this.onState?.('compact', { phase: 'failed', before, after: before, error: 'Nothing to compact yet.' }, true);
579
+ return this.trimToolResults();
580
+ }
529
581
  if (!this.silent) this.ui.info('Compacting conversation history to free up context…');
582
+ this.onState?.('compact', { phase: 'start', before, after: null }, force);
530
583
  const transcript = messages.slice(0, cut).map(renderForSummary).join('\n\n');
531
584
  const summary = await this.complete(
532
585
  [
@@ -537,10 +590,15 @@ export class Agent {
537
590
  },
538
591
  ],
539
592
  signal,
540
- );
593
+ ).catch((err) => {
594
+ this.onState?.('compact', { phase: 'failed', before, after: before, error: err.name === 'AbortError' ? 'Interrupted.' : err.message }, force);
595
+ throw err;
596
+ });
541
597
  this.session.compact(summary.trim() || '(no summary produced)', cut);
598
+ if (this.depth === 0) this.checkpoints?.compacted(cut);
542
599
  this.warnedContext = false;
543
600
  if (estimateTokens(this.session.messages) >= this.config.contextWindow * COMPACT_AT) this.trimToolResults();
601
+ this.onState?.('compact', { phase: 'done', before, after: this.contextTokens() }, force);
544
602
  return true;
545
603
  }
546
604
 
package/src/anthropic.js CHANGED
@@ -54,6 +54,9 @@ function userBlocks(content) {
54
54
  const m = p.image_url?.url?.match(dataUrl);
55
55
  if (m) blocks.push({ type: 'image', source: { type: 'base64', media_type: m[1], data: m[2] } });
56
56
  else if (p.image_url?.url) blocks.push({ type: 'image', source: { type: 'url', url: p.image_url.url } });
57
+ } else if (p.type === 'document') {
58
+ const m = p.document?.url?.match(dataUrl);
59
+ if (m) blocks.push({ type: 'document', source: { type: 'base64', media_type: m[1], data: m[2] } });
57
60
  }
58
61
  }
59
62
  return blocks;