@mumbrane/leto 0.19.0 → 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/src/sandbox.js CHANGED
@@ -2,7 +2,8 @@
2
2
  //
3
3
  // With the sandbox on, bash commands run in an OS sandbox that can write only
4
4
  // inside the project folder and temp folders, can't read your keys and
5
- // credentials, and (by default) has no network. Because a sandboxed command
5
+ // credentials, and reaches the network only through an allowlisting proxy
6
+ // (package registries and code hosts by default). Because a sandboxed command
6
7
  // can't damage anything outside the project, it runs without asking.
7
8
  // Commands that need more (installing packages, pushing, writing elsewhere)
8
9
  // can ask to run outside the sandbox, which goes through the normal prompt.
@@ -11,8 +12,12 @@
11
12
  import fs from 'node:fs';
12
13
  import os from 'node:os';
13
14
  import path from 'node:path';
15
+ import http from 'node:http';
16
+ import net from 'node:net';
17
+ import dns from 'node:dns/promises';
14
18
  import { spawnSync } from 'node:child_process';
15
- import { HOME_DIR } from './config.js';
19
+ import { HOME_DIR, readConfigFile } from './config.js';
20
+ import { loadPolicy } from './policy.js';
16
21
 
17
22
  let cached;
18
23
  export function sandboxAvailable() {
@@ -86,5 +91,111 @@ export function sandboxCommand(command, { cwd, network = false, shell = '/bin/ba
86
91
 
87
92
  // Did the sandbox (rather than the command itself) cause the failure?
88
93
  export function looksBlocked(output) {
89
- return /Operation not permitted|Read-only file system|sandbox-exec|Could not resolve host|getaddrinfo E(NOTFOUND|AI_AGAIN)|Network is unreachable|ENETUNREACH|EAI_AGAIN|deny\(1\)/i.test(output);
94
+ return /Operation not permitted|CONNECT tunnel failed|403 Forbidden|Read-only file system|sandbox-exec|Could not resolve host|getaddrinfo E(NOTFOUND|AI_AGAIN)|Network is unreachable|ENETUNREACH|EAI_AGAIN|deny\(1\)/i.test(output);
95
+ }
96
+
97
+ // --- network allowlist -------------------------------------------------------
98
+ //
99
+ // Sandboxed commands can only reach localhost, so their HTTP(S) goes through
100
+ // this proxy, which lets through only allowlisted hosts on ports 443/80.
101
+
102
+ export const DEFAULT_ALLOW = [
103
+ 'registry.npmjs.org', 'registry.yarnpkg.com',
104
+ 'pypi.org', 'files.pythonhosted.org',
105
+ 'crates.io', 'index.crates.io', 'static.crates.io', 'static.rust-lang.org',
106
+ 'github.com', '.github.com', '.githubusercontent.com',
107
+ 'proxy.golang.org', 'sum.golang.org',
108
+ ];
109
+
110
+ // The policy's list replaces everything; otherwise config extends the defaults.
111
+ export function allowList() {
112
+ const fixed = loadPolicy()?.sandboxAllow;
113
+ const list = fixed ?? [...DEFAULT_ALLOW, readConfigFile().sandboxAllow ?? []];
114
+ return [].concat(list).join(',').toLowerCase().split(/[\s,]+/).filter(Boolean);
115
+ }
116
+
117
+ // Exact host, or ".suffix" for subdomains; "host:port" allows another port.
118
+ export function hostAllowed(host, port, list = allowList()) {
119
+ host = host.toLowerCase().replace(/\.$/, '');
120
+ if (net.isIP(host.replace(/^\[|\]$/g, ''))) return false;
121
+ return list.some((entry) => {
122
+ const [h, p] = entry.split(':');
123
+ if (p ? Number(p) !== port : port !== 443 && port !== 80) return false;
124
+ return h.startsWith('.') ? host.endsWith(h) : host === h;
125
+ });
126
+ }
127
+
128
+ // Loopback, private, link-local, CGNAT and multicast; BlockList also matches IPv4-mapped IPv6 against the IPv4 rules.
129
+ const PRIVATE = new net.BlockList();
130
+ for (const [a, n] of [['0.0.0.0', 8], ['10.0.0.0', 8], ['100.64.0.0', 10], ['127.0.0.0', 8], ['169.254.0.0', 16], ['172.16.0.0', 12], ['192.168.0.0', 16], ['224.0.0.0', 3]]) PRIVATE.addSubnet(a, n, 'ipv4');
131
+ for (const [a, n] of [['::', 127], ['fc00::', 7], ['fe80::', 10], ['ff00::', 8]]) PRIVATE.addSubnet(a, n, 'ipv6');
132
+
133
+ // The address to connect to, resolved once so DNS can't change between check and connect.
134
+ async function allowedAddress(host, port) {
135
+ if (!hostAllowed(host, port)) throw new Error(`${host}:${port} is not on the sandbox allowlist (leto config: sandboxAllow)`);
136
+ const addrs = await dns.lookup(host, { all: true });
137
+ if (!addrs.length || addrs.some((a) => PRIVATE.check(a.address, `ipv${a.family}`))) throw new Error(`${host} resolves to a private address`);
138
+ return addrs[0].address;
139
+ }
140
+
141
+ let proxy;
142
+ // The proxy's port; started on first use, it lives as long as this process.
143
+ export function sandboxProxy() {
144
+ proxy ??= new Promise((resolve, reject) => {
145
+ const server = http.createServer(async (req, res) => {
146
+ try {
147
+ const url = new URL(req.url);
148
+ if (url.protocol !== 'http:') throw new Error('only http:// URLs (use CONNECT for https)');
149
+ const port = Number(url.port) || 80;
150
+ const address = await allowedAddress(url.hostname, port);
151
+ const headers = { ...req.headers };
152
+ delete headers['proxy-connection'];
153
+ delete headers['proxy-authorization'];
154
+ const up = http.request({ host: address, port, method: req.method, path: url.pathname + url.search, headers }, (r) => {
155
+ res.writeHead(r.statusCode, r.headers);
156
+ r.pipe(res);
157
+ });
158
+ up.on('error', () => res.destroy());
159
+ req.pipe(up);
160
+ } catch (err) {
161
+ res.writeHead(403, { 'content-type': 'text/plain' }).end(`leto sandbox: ${err.message}\n`);
162
+ }
163
+ });
164
+ server.on('connect', async (req, sock, head) => {
165
+ sock.on('error', () => {});
166
+ try {
167
+ const url = new URL(`x://${req.url}`);
168
+ const port = Number(url.port) || 443;
169
+ const address = await allowedAddress(url.hostname, port);
170
+ const up = net.connect(port, address, () => {
171
+ sock.write('HTTP/1.1 200 Connection Established\r\n\r\n');
172
+ up.write(head);
173
+ up.pipe(sock).pipe(up);
174
+ });
175
+ up.on('error', () => sock.destroy());
176
+ sock.on('close', () => up.destroy());
177
+ } catch (err) {
178
+ sock.end(`HTTP/1.1 403 Forbidden\r\ncontent-type: text/plain\r\n\r\nleto sandbox: ${err.message}\n`);
179
+ }
180
+ });
181
+ server.on('error', reject);
182
+ server.listen(0, '127.0.0.1', () => {
183
+ server.unref(); // the proxy never keeps leto running
184
+ resolve(server.address().port);
185
+ });
186
+ });
187
+ return proxy;
188
+ }
189
+
190
+ // Proxy settings for the sandboxed command, in the spellings common tools read.
191
+ export function proxyEnv(port) {
192
+ const url = `http://127.0.0.1:${port}`;
193
+ const env = { NO_PROXY: 'localhost,127.0.0.1,::1', no_proxy: 'localhost,127.0.0.1,::1', NODE_USE_ENV_PROXY: '1' };
194
+ for (const k of ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy', 'npm_config_proxy', 'npm_config_https_proxy', 'YARN_HTTP_PROXY', 'YARN_HTTPS_PROXY', 'PIP_PROXY', 'CARGO_HTTP_PROXY']) env[k] = url;
195
+ return env;
196
+ }
197
+
198
+ // What the model is told when the user turns the sandbox on or off mid-session.
199
+ export function sandboxNote(p) {
200
+ return p.sandbox ? `[The shell sandbox is now ON${p.sandboxNetwork ? ' with network' : ', with only allowlisted hosts reachable'}: bash commands can write only inside the working directory and temp folders, and run without asking. If one fails because of the sandbox, retry with unsandboxed: true and the user will be asked.]` : '[The shell sandbox is now OFF: bash commands run normally and ask for permission.]';
90
201
  }
package/src/selftool.js CHANGED
@@ -22,7 +22,7 @@ import { sandboxAvailable } from './sandbox.js';
22
22
  import { detectChecks } from './verify.js';
23
23
  import { isNativeAnthropic, modelTraits } from './anthropic.js';
24
24
  import { formatCost } from './pricing.js';
25
- import { policyForcesSandbox } from './policy.js';
25
+ import { policyForcesSandbox, policyFixesSandboxNetwork } from './policy.js';
26
26
  import { projectDir } from './legacy.js';
27
27
 
28
28
  const README = new URL('../README.md', import.meta.url);
@@ -133,7 +133,7 @@ export const selfTool = {
133
133
  `context: ~${used.toLocaleString()} of ${cfg.contextWindow.toLocaleString()} tokens (${Math.round((used / cfg.contextWindow) * 100)}%); auto-compacts at 80%`,
134
134
  `cost so far: ${u.requests ? formatCost(u.cost) : '$0'}${agent.budget ? ` of a $${agent.budget.toFixed(2)} budget` : ''} over ${u.requests} requests`,
135
135
  `permissions: ${p.mode}${p.acceptEdits ? ', accepting edits' : ''}${p.planMode ? ', PLAN MODE (read-only)' : ''}`,
136
- `sandbox: ${p.sandbox ? `on${p.sandboxNetwork ? ' with network' : ', no network'}` : 'off'}${sandboxAvailable() ? '' : ' (not available on this system)'}`,
136
+ `sandbox: ${p.sandbox ? `on${p.sandboxNetwork ? ' with network' : ', allowlisted hosts only'}` : 'off'}${sandboxAvailable() ? '' : ' (not available on this system)'}`,
137
137
  `project check: ${cfg.checkCommand || 'none'}`,
138
138
  `effort: ${cfg.effort || 'default'}${isNativeAnthropic(cfg) && modelTraits(cfg.model).effort ? '' : ' (not adjustable for this model)'}`,
139
139
  `tool mode: ${cfg.toolMode || 'native'}`,
@@ -168,6 +168,7 @@ export const selfTool = {
168
168
  case 'plan_mode': {
169
169
  if (p.planMode) return 'Plan mode is already on.';
170
170
  p.planMode = true;
171
+ agent.onState?.('mode');
171
172
  return { content: 'Plan mode is ON: edits and commands are blocked. Investigate with read-only tools, then call leto exit_plan_mode with your plan for the user to approve.', display: 'plan mode on' };
172
173
  }
173
174
  case 'exit_plan_mode': {
@@ -180,6 +181,7 @@ export const selfTool = {
180
181
  return { content: 'The user did not approve the plan. Stay in plan mode; ask what to change.', display: 'plan not approved' };
181
182
  }
182
183
  p.planMode = false;
184
+ agent.onState?.('mode');
183
185
  return { content: 'The user approved the plan. Plan mode is OFF; carry it out now.', display: 'plan approved · building' };
184
186
  }
185
187
  case 'compact': {
@@ -190,14 +192,17 @@ export const selfTool = {
190
192
  if (!isNativeAnthropic(cfg) || !modelTraits(cfg.model).effort) return `Effort can't be set for ${cfg.model}.`;
191
193
  if (!a.level) throw new Error('level is required');
192
194
  cfg.effort = a.level;
195
+ agent.onState?.('effort');
193
196
  return { content: `Effort is now ${a.level} for the rest of this session.`, display: `effort ${a.level}` };
194
197
  }
195
198
  case 'sandbox': {
196
199
  if (!sandboxAvailable()) return 'No sandbox is available on this system (Linux needs bubblewrap).';
197
200
  if (a.enabled === false && policyForcesSandbox()) return "Your organization's policy keeps the sandbox on.";
201
+ if (a.network && policyFixesSandboxNetwork()) return "Your organization's policy fixes the hosts sandboxed commands may reach.";
198
202
  if (a.enabled !== undefined) p.sandbox = a.enabled;
199
203
  if (a.network !== undefined) p.sandboxNetwork = a.network;
200
- return { content: p.sandbox ? `Sandbox ON${p.sandboxNetwork ? ' with network' : ' without network'}: bash commands are confined to the working directory and temp folders and run without asking.` : 'Sandbox OFF: bash commands ask for permission again.', display: `sandbox ${p.sandbox ? 'on' : 'off'}${p.sandbox && p.sandboxNetwork ? ' · network' : ''}` };
204
+ agent.onState?.('sandbox');
205
+ return { content: p.sandbox ? `Sandbox ON${p.sandboxNetwork ? ' with network' : ' with allowlisted hosts only'}: bash commands are confined to the working directory and temp folders and run without asking.` : 'Sandbox OFF: bash commands ask for permission again.', display: `sandbox ${p.sandbox ? 'on' : 'off'}${p.sandbox && p.sandboxNetwork ? ' · network' : ''}` };
201
206
  }
202
207
  case 'set_check': {
203
208
  if (!a.command) throw new Error('command is required (or "off").');
package/src/serve.js CHANGED
@@ -1,32 +1,22 @@
1
1
  // `leto serve`: one long-lived session for another program to drive, such as the
2
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.
3
+ // object per line each way. docs/serve-protocol.md documents every command and event.
20
4
  import readline from 'node:readline';
21
5
  import fs from 'node:fs';
22
6
  import path from 'node:path';
23
- import { HOME_DIR } from './config.js';
7
+ import { HOME_DIR, loadConfig } from './config.js';
8
+ import { listModels } from './client.js';
24
9
  import { isNativeAnthropic, modelTraits } from './anthropic.js';
25
10
  import { EventUI, resultEvent } from './sdk.js';
26
11
  import { buildMessage } from './input.js';
27
- import { checkModel, policyForbidsYolo } from './policy.js';
12
+ import { checkModel, policyForbidsYolo, policyForcesSandbox } from './policy.js';
13
+ import { sandboxAvailable, sandboxNote } from './sandbox.js';
28
14
  import { closeBrowser } from './browser.js';
29
15
  import { flushUsage } from './usage.js';
16
+ import { rewindPoints, exportMarkdown, listSessions, Session } from './session.js';
17
+ import { undoNote } from './checkpoints.js';
18
+ import { listProcesses, getProcess, tailProcess, stopProcess, setExitHandler } from './processes.js';
19
+ import { readNotes, addNote, writeNotes } from './memory.js';
30
20
  import { VERSION } from './version.js';
31
21
 
32
22
  export const SERVE_MODES = ['ask', 'acceptEdits', 'plan', 'yolo'];
@@ -39,6 +29,9 @@ export class ServeUI extends EventUI {
39
29
  this.pending = new Map(); // id -> resolve
40
30
  this.seq = 0;
41
31
  this.writing = null; // the tool call being written: { name, tokens, sent }
32
+ this.nestedResults = true; // sub-agents' tool results are events too
33
+ this.outputs = new Map(); // call id -> live output not yet sent: { left, pending, timer }
34
+ this.progressSent = new Map(); // agent_id -> when its last agent_progress went out
42
35
  }
43
36
 
44
37
  toolPending(name) {
@@ -82,15 +75,43 @@ export class ServeUI extends EventUI {
82
75
  for (const id of [...this.pending.keys()]) this.resolve(id, null);
83
76
  }
84
77
 
85
- toolStart(tool, summary, { prefix = '', id = null, name = null, input = null } = {}) {
78
+ agentProgress(agentId, tokens) {
79
+ const now = Date.now();
80
+ if (now - (this.progressSent.get(agentId) ?? 0) < 250) return;
81
+ this.progressSent.set(agentId, now);
82
+ this.emit({ type: 'agent_progress', agent_id: agentId, tokens });
83
+ }
84
+
85
+ // Live output of a running bash call, at most four times a second and MAX_OUTPUT characters per call.
86
+ toolOutput(id, text) {
87
+ if (!id) return;
88
+ const o = this.outputs.get(id) ?? { left: MAX_OUTPUT, pending: '', timer: null };
89
+ this.outputs.set(id, o);
90
+ o.pending = (o.pending + text).slice(0, o.left);
91
+ o.timer ??= setTimeout(() => this.flushOutput(id), 250);
92
+ }
93
+
94
+ flushOutput(id) {
95
+ const o = this.outputs.get(id);
96
+ if (!o) return;
97
+ clearTimeout(o.timer);
98
+ o.timer = null;
99
+ o.left -= o.pending.length;
100
+ if (o.pending) this.emit({ type: 'tool_output', id, text: o.pending });
101
+ o.pending = '';
102
+ }
103
+
104
+ toolStart(tool, summary, { prefix = '', id = null, name = null, input = null, agentId = null } = {}) {
86
105
  this.writing = null;
87
- this.emit({ type: 'tool_start', tool, summary: String(summary ?? ''), agent: prefix || null, id, name, input });
106
+ this.emit({ type: 'tool_start', tool, summary: String(summary ?? ''), agent: prefix || null, agent_id: agentId, id, name, input });
88
107
  }
89
108
 
90
- toolResult(result, isError = false, { id = null, lines = null, diff = null, images = null } = {}) {
109
+ toolResult(result, isError = false, { id = null, lines = null, diff = null, images = null, agentId = null, agentUsage = null } = {}) {
110
+ this.flushOutput(id); // the last of it goes out before the result
111
+ this.outputs.delete(id);
91
112
  const shown = diff ?? lines;
92
113
  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 });
114
+ this.emit({ type: 'tool_result', result: String(result ?? ''), is_error: Boolean(isError), id, lines: shown?.length ? shown : null, images: files.length ? files : null, agent_id: agentId, ...(agentUsage && { agent_usage: agentUsage }) });
94
115
  }
95
116
 
96
117
  async confirm(preview, tool, { args, prefix } = {}) {
@@ -153,57 +174,287 @@ export function setMode(agent, mode) {
153
174
  if (Boolean(p.planMode) !== (mode === 'plan')) agent.setPlanMode(mode === 'plan');
154
175
  }
155
176
 
177
+ // The mode a client sees: plan mode wins over the permission mode underneath it.
178
+ const modeOf = (p) => (p.planMode ? 'plan' : p.mode === 'yolo' ? 'yolo' : p.acceptEdits ? 'acceptEdits' : 'ask');
179
+
180
+ const CAPABILITIES = ['req', 'state_events', 'set_sandbox', 'trust', 'attachments', 'queue', 'steer', 'compact', 'turn_usage', 'context', 'checkpoints', 'rewind', 'sessions', 'memory', 'agent_ids', 'tool_output', 'processes'];
181
+ const SESSION_COMMANDS = ['checkpoints', 'undo', 'rewind', 'sessions', 'rename', 'fork', 'export', 'clear', 'memory'];
182
+ const MAX_TEXT = 1_000_000;
183
+ const MAX_OUTPUT = 100_000; // live output sent per bash call
184
+ const MAX_TAIL = 30_000; // process_output
185
+ const MAX_ATTACHMENTS = 20;
186
+ const MAX_QUEUE = 50; // sends waiting or steering, so a stuck turn can't pile up attachments in memory
187
+ const BASH_NOTE = 'Changes made by shell commands are not checkpointed, so they are not restored.';
188
+
189
+ const processInfo = (p) => ({ id: p.id, command: p.command, running: p.code === null, code: p.code });
190
+
191
+ function needIndex(v, what) {
192
+ if (!Number.isInteger(v) || v < 0) throw new Error(`${what} must be a non-negative integer.`);
193
+ return v;
194
+ }
195
+
196
+ // Split what restoring files did into what worked and what could not be put back.
197
+ const restoreReport = (r) => ({ restored: r.filter((x) => x.action !== 'failed'), failed: r.filter((x) => x.action === 'failed').map(({ file, error }) => ({ file, error })), note: BASH_NOTE });
198
+
199
+ function needString(v, what, max = 200) {
200
+ if (typeof v !== 'string' || !v || v.length > max) throw new Error(`${what} must be a non-empty string of at most ${max} characters.`);
201
+ return v;
202
+ }
203
+
156
204
  // Runs the session until stdin closes or a shutdown arrives.
157
- export async function serve({ agent, ui, cwd, mcpServers = [], mode = 'ask' }) {
205
+ export async function serve({ agent, ui, cwd, mcpServers = [], mode = 'ask', trusted = true, trust }) {
158
206
  const emit = (ev) => ui.emit(ev);
159
207
  setMode(agent, mode);
160
208
  let turn = null;
209
+ const p = agent.permissions;
210
+ const context = () => ({ used: agent.contextTokens(), window: agent.config.contextWindow });
211
+ const state = {
212
+ mode: () => ({ type: 'mode', mode: modeOf(p) }),
213
+ effort: () => ({ type: 'effort', level: agent.config.effort }),
214
+ model: () => ({ type: 'model', model: agent.config.model, context_window: agent.config.contextWindow }),
215
+ sandbox: () => ({ type: 'sandbox', on: p.sandbox, network: p.sandboxNetwork }),
216
+ context: () => ({ type: 'context', ...context() }),
217
+ memory: () => ({ type: 'memory', notes: readNotes(cwd) }),
218
+ };
219
+ const exitReplies = new Map(); // process id -> the kill_process reply waiting for its exit
220
+ setExitHandler((p) => {
221
+ (exitReplies.get(p.id) ?? emit)({ type: 'process_exit', id: p.id, code: p.code });
222
+ exitReplies.delete(p.id);
223
+ });
224
+ let compactReply = null; // the compact command whose compaction runs next
225
+ // The model changes these itself through the leto tool; the client hears about it the same way.
226
+ agent.onState = (kind, ev, forced) => {
227
+ if (kind !== 'compact') return emit(state[kind]());
228
+ ((forced && compactReply) || emit)({ type: 'compact', ...ev });
229
+ if (forced && ev.phase !== 'start') compactReply = null;
230
+ };
161
231
 
162
- const runTurn = async (text) => {
232
+ const queue = []; // sends waiting for the running turn: { text, content, reply, req }
233
+ const runTurn = async ({ text, content, reply }) => {
163
234
  const started = Date.now();
164
- const { content, errors } = buildMessage(text, cwd);
165
- for (const e of errors) ui.error(e);
235
+ const u0 = { ...agent.usage };
236
+ reply({ type: 'turn_start', text });
166
237
  let ok = false;
167
238
  try {
168
239
  ok = await agent.send(content);
169
240
  } catch (err) {
170
- ui.error(err.message);
241
+ reply({ type: 'error', message: err.message });
242
+ }
243
+ const u = agent.usage;
244
+ reply({
245
+ ...resultEvent(agent, ok, { started }),
246
+ turn_usage: { input_tokens: u.input - u0.input, output_tokens: u.output - u0.output, cache_read_tokens: u.cacheRead - u0.cacheRead, cache_write_tokens: u.cacheWrite - u0.cacheWrite, requests: u.requests - u0.requests },
247
+ // Usage prices each request with the model that served it.
248
+ turn_cost_usd: u.unpriced > u0.unpriced ? null : Number((u.cost - u0.cost).toFixed(6)),
249
+ context: context(),
250
+ });
251
+ };
252
+ // A compact with no turn running runs like one, so sends queue behind it and interrupt stops it.
253
+ const compactNow = async (focus) => {
254
+ agent.abort = new AbortController();
255
+ try {
256
+ await agent.maybeCompact(agent.abort.signal, true, focus);
257
+ } catch {} // its compact "failed" event says why
258
+ finally {
259
+ agent.abort = null;
171
260
  }
172
- emit(resultEvent(agent, ok, { started }));
261
+ };
262
+ const start = (item) => {
263
+ turn = (item.compact !== undefined ? compactNow(item.compact) : runTurn(item)).finally(() => {
264
+ // Steered messages the turn ended before taking run next.
265
+ queue.unshift(...agent.steering.splice(0).map((s) => s.item));
266
+ turn = null;
267
+ if (queue.length) start(queue.shift());
268
+ });
269
+ };
270
+
271
+ // The live session changed: tell the client and reset its view of what depends on it.
272
+ const switched = (reply, reason) => {
273
+ reply({ type: 'session', session_id: agent.session.id, reason });
274
+ emit({ type: 'todos', todos: agent.todos });
275
+ emit(state.context());
173
276
  };
174
277
 
175
- const handle = (msg) => {
278
+ const handle = async (msg, reply) => {
279
+ if (SESSION_COMMANDS.includes(msg.type) && turn) throw new Error(`Wait for the turn to finish before ${msg.type}.`);
176
280
  switch (msg.type) {
177
281
  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));
282
+ const text = typeof msg.text === 'string' ? msg.text.trim() : '';
283
+ if (!text) throw new Error('send needs text.');
284
+ if (text.length > MAX_TEXT) throw new Error(`send text is longer than ${MAX_TEXT} characters.`);
285
+ for (const k of ['images', 'files']) if (msg[k] !== undefined && (!Array.isArray(msg[k]) || msg[k].length > MAX_ATTACHMENTS)) throw new Error(`send ${k} must be a list of at most ${MAX_ATTACHMENTS}.`);
286
+ if (msg.steer !== undefined && typeof msg.steer !== 'boolean') throw new Error('send steer must be true or false.');
287
+ const { content, attached, refused, errors } = buildMessage(text, cwd, msg.images, { files: msg.files, pdfs: isNativeAnthropic(agent.config) });
288
+ for (const e of errors) reply({ type: 'error', message: e });
289
+ if (attached.length || refused.length) reply({ type: 'attached', attached, refused });
290
+ const item = { text, content, reply, req: msg.req };
291
+ if (!turn) return start(item);
292
+ if (queue.length + agent.steering.length >= MAX_QUEUE) throw new Error(`At most ${MAX_QUEUE} messages can wait for a turn.`);
293
+ if (msg.steer) return void agent.steering.push({ content, item, taken: () => reply({ type: 'steered', text }) });
294
+ queue.push(item);
295
+ return reply({ type: 'queued', position: queue.length });
296
+ }
297
+ case 'unqueue': {
298
+ const i = queue.findIndex((q) => q.req === needString(msg.req, 'unqueue req'));
299
+ if (i < 0) throw new Error(`No queued message has req ${msg.req}.`);
300
+ queue.splice(i, 1);
301
+ return reply({ type: 'unqueued' });
302
+ }
303
+ case 'compact': {
304
+ const focus = msg.focus === undefined ? '' : needString(msg.focus, 'compact focus', 10_000);
305
+ compactReply = reply;
306
+ if (!turn) return start({ compact: focus });
307
+ agent.pendingCompact = focus; // compacted before the turn's next request
182
308
  return;
183
309
  }
184
310
  case 'interrupt':
185
311
  ui.cancelRead();
186
312
  return agent.interrupt();
187
313
  case 'permission':
188
- case 'answer':
189
- if (!ui.resolve(String(msg.id), msg.answer ?? null)) ui.error(`Nothing is waiting on ${msg.id}.`);
314
+ case 'answer': {
315
+ const answer = msg.answer ?? null;
316
+ const ok = msg.type === 'permission' ? answer === null || typeof answer === 'string' : answer === null || typeof answer === 'string' || (Array.isArray(answer) && answer.every((a) => typeof a === 'string'));
317
+ if (!ok || JSON.stringify(answer).length > MAX_TEXT) throw new Error(`${msg.type} answer must be ${msg.type === 'permission' ? 'a string' : 'a string or a list of strings'}.`);
318
+ if (!ui.resolve(needString(msg.id, `${msg.type} id`, 64), answer)) throw new Error(`Nothing is waiting on ${msg.id}.`);
190
319
  return;
320
+ }
191
321
  case 'set_mode':
192
322
  setMode(agent, msg.mode);
193
- return emit({ type: 'mode', mode: msg.mode });
323
+ return reply(state.mode());
194
324
  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 });
325
+ setEffort(agent, msg.level);
326
+ return reply(state.effort());
327
+ case 'set_model': {
328
+ const cfg = agent.config;
329
+ checkModel(needString(msg.model, 'model'));
330
+ let models = [];
331
+ try {
332
+ models = await listModels(cfg);
333
+ } catch {} // can't list: keep going, like a fresh start with -m
334
+ const listed = models.find((m) => m.id === msg.model);
335
+ // shortcut: an unlisted model counts as offered when it prefixes a listed id (aliases like claude-opus-4-5); allow all unlisted ones if a provider lists only some
336
+ if (models.length && !listed && !models.some((m) => m.id.startsWith(msg.model))) {
337
+ throw new Error(`${cfg.providerName || cfg.provider} doesn't offer "${msg.model}". A model from another provider needs a session on that provider (leto setup).`);
338
+ }
339
+ cfg.model = msg.model;
340
+ // The window a fresh start would use; the provider's own number for the model is better, unless the environment overrides it.
341
+ cfg.contextWindow = (!Number(process.env.LETO_CONTEXT_WINDOW) && listed?.contextWindow) || loadConfig({ provider: cfg.provider }).contextWindow;
342
+ agent.systemPrompt = null; // it names the model
343
+ return reply(state.model());
344
+ }
345
+ // The client is the user, so it may turn the sandbox off or let it use the network without asking.
346
+ case 'set_sandbox': {
347
+ for (const k of ['on', 'network']) if (msg[k] !== undefined && typeof msg[k] !== 'boolean') throw new Error(`set_sandbox ${k} must be true or false.`);
348
+ if (msg.on === undefined && msg.network === undefined) throw new Error('set_sandbox needs on, network or both.');
349
+ const on = msg.on ?? p.sandbox;
350
+ if (on && !sandboxAvailable()) throw new Error('No sandbox is available on this system (Linux needs bubblewrap).');
351
+ if (!on && policyForcesSandbox()) throw new Error("Your organization's policy keeps the sandbox on.");
352
+ p.sandbox = on;
353
+ p.sandboxNetwork = msg.network ?? p.sandboxNetwork;
354
+ agent.notes.push(sandboxNote(p));
355
+ return reply(state.sandbox());
356
+ }
357
+ case 'trust':
358
+ if (turn) throw new Error('Wait for the turn to finish before trusting the folder: its MCP servers restart.');
359
+ if (!trusted) {
360
+ await trust();
361
+ trusted = true;
362
+ }
363
+ return reply({ type: 'trusted', trusted });
364
+ case 'checkpoints':
365
+ return reply({ type: 'checkpoints', checkpoints: agent.checkpoints.list() });
366
+ case 'undo': {
367
+ const turns = agent.checkpoints.list();
368
+ if (!turns.length) throw new Error('Nothing to undo: leto has not changed any files in this session.');
369
+ const to = msg.to === undefined ? turns.at(-1).id : msg.to;
370
+ if (!turns.some((t) => t.id === to)) throw new Error(`No turn ${String(to).slice(0, 64)}. Turns with changes: ${turns.map((t) => t.id).join(', ')}`);
371
+ const r = agent.checkpoints.undo(to);
372
+ agent.notes.push(undoNote(r, cwd));
373
+ return reply({ type: 'undone', ...restoreReport(r) });
374
+ }
375
+ case 'rewind': {
376
+ if (typeof msg.files !== 'boolean') throw new Error('rewind files must be true or false.');
377
+ const point = rewindPoints(agent.session.messages).find((x) => x.i === needIndex(msg.index, 'rewind index'));
378
+ if (!point) throw new Error(`rewind index ${msg.index} is not one of your messages that can be rewound to.`);
379
+ const previous = agent.session.id;
380
+ const r = msg.files ? agent.checkpoints.restoreFrom(point.i) : [];
381
+ agent.useSession(Session.fork(agent.session, point.i, { cwd, model: agent.config.model }));
382
+ reply({ type: 'rewound', previous, text: point.text, ...restoreReport(r) });
383
+ return switched(reply, 'rewind');
384
+ }
385
+ case 'fork': {
386
+ const msgs = agent.session.messages;
387
+ const upto = msg.index === undefined ? msgs.length : needIndex(msg.index, 'fork index');
388
+ if (upto > msgs.length || !upto) throw new Error(msgs.length ? `fork index must be between 1 and ${msgs.length}.` : 'Nothing to fork yet.');
389
+ agent.useSession(Session.fork(agent.session, upto, { cwd, model: agent.config.model }));
390
+ return switched(reply, 'fork');
391
+ }
392
+ case 'clear':
393
+ agent.useSession(Session.create({ cwd, model: agent.config.model }));
394
+ return switched(reply, 'clear');
395
+ case 'memory': {
396
+ if (!['list', 'add', 'remove'].includes(msg.op)) throw new Error('memory op must be list, add or remove.');
397
+ if (msg.op === 'add') {
398
+ const note = needString(msg.text, 'memory text', 400);
399
+ if (addNote(cwd, note).added) agent.notes.push(`[The user added a note to your project memory: ${note}]`);
400
+ }
401
+ if (msg.op === 'remove') {
402
+ const notes = readNotes(cwd);
403
+ const i = needIndex(msg.index, 'memory index');
404
+ if (i >= notes.length) throw new Error(`memory index must be below ${notes.length}.`);
405
+ const [gone] = notes.splice(i, 1);
406
+ writeNotes(cwd, notes);
407
+ agent.notes.push(`[The user removed a note from your project memory: ${gone}]`);
408
+ }
409
+ return reply(state.memory());
410
+ }
411
+ case 'processes':
412
+ return reply({ type: 'processes', processes: listProcesses().map(processInfo) });
413
+ case 'process_output': {
414
+ const id = needString(msg.id, 'process_output id', 64);
415
+ const text = tailProcess(id, MAX_TAIL); // throws for an unknown id
416
+ const { running, code } = processInfo(getProcess(id));
417
+ return reply({ type: 'process_output', id, text, running, code });
418
+ }
419
+ case 'kill_process': {
420
+ const p = getProcess(needString(msg.id, 'kill_process id', 64));
421
+ if (!p) throw new Error(`No background process "${msg.id}".`);
422
+ if (p.code !== null) return reply({ type: 'process_exit', id: p.id, code: p.code });
423
+ exitReplies.set(p.id, reply); // its process_exit answers the command
424
+ stopProcess(p.id);
425
+ agent.notes.push(`[The user stopped background process ${p.id} (\`${p.command}\`).]`);
426
+ return;
427
+ }
428
+ case 'sessions':
429
+ return reply({ type: 'sessions', current: agent.session.id, sessions: listSessions() });
430
+ case 'rename': {
431
+ const title = needString(msg.title, 'rename title', 200).slice(0, 70);
432
+ agent.session.append({ type: 'title', title });
433
+ return reply({ type: 'renamed', title });
434
+ }
435
+ case 'export':
436
+ return reply({ type: 'exported', markdown: exportMarkdown(agent.session, { model: agent.config.model, cwd }) });
201
437
  default:
202
- return ui.error(`Unknown command type "${msg.type}".`);
438
+ throw new Error(`Unknown command type "${String(msg.type).slice(0, 64)}".`);
203
439
  }
204
440
  };
205
441
 
206
- emit({ type: 'ready', version: VERSION, session_id: agent.session.id, model: agent.config.model, cwd, mode });
442
+ const cfg = agent.config;
443
+ emit({
444
+ type: 'ready',
445
+ protocol: 2,
446
+ capabilities: CAPABILITIES,
447
+ version: VERSION,
448
+ session_id: agent.session.id,
449
+ model: cfg.model,
450
+ provider: cfg.provider,
451
+ effort: cfg.effort || null,
452
+ context_window: cfg.contextWindow,
453
+ cwd,
454
+ mode: modeOf(p),
455
+ sandbox: { on: p.sandbox, network: p.sandboxNetwork },
456
+ trusted,
457
+ });
207
458
  const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
208
459
  for await (const line of rl) {
209
460
  if (!line.trim()) continue;
@@ -214,14 +465,26 @@ export async function serve({ agent, ui, cwd, mcpServers = [], mode = 'ask' }) {
214
465
  ui.error(`Not JSON: ${line.slice(0, 200)}`);
215
466
  continue;
216
467
  }
468
+ if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {
469
+ ui.error('A command must be a JSON object.');
470
+ continue;
471
+ }
472
+ if (msg.req !== undefined && (typeof msg.req !== 'string' || msg.req.length > 200)) {
473
+ ui.error('req must be a string of at most 200 characters.');
474
+ continue;
475
+ }
217
476
  if (msg.type === 'shutdown') break;
477
+ const reply = (ev) => emit(msg.req === undefined ? ev : { ...ev, req: msg.req });
478
+ // Awaited so commands take effect in the order they were sent; a turn runs on in the background.
218
479
  try {
219
- handle(msg);
480
+ await handle(msg, reply);
220
481
  } catch (err) {
221
- ui.error(err.message);
482
+ reply({ type: 'error', message: err.message });
222
483
  }
223
484
  }
224
- // stdin closed: stop whatever is running and let it wind down.
485
+ // stdin closed: drop what waits, stop whatever is running and let it wind down.
486
+ queue.length = 0;
487
+ agent.steering.length = 0;
225
488
  if (turn) {
226
489
  ui.cancelRead();
227
490
  agent.interrupt();