@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/session.js CHANGED
@@ -6,6 +6,7 @@ import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { SESSIONS_DIR } from './config.js';
8
8
  import { VERSION } from './version.js';
9
+ import { parsePatch } from './patching.js';
9
10
 
10
11
  function newId() {
11
12
  const d = new Date();
@@ -68,6 +69,13 @@ export class Session {
68
69
  return new Session({ id: 'memory', file: null, meta: {} });
69
70
  }
70
71
 
72
+ // A new session holding the first `upto` messages of another (the original stays saved).
73
+ static fork(from, upto, { cwd, model }) {
74
+ const fresh = Session.create({ cwd, model });
75
+ for (const m of from.messages.slice(0, upto)) fresh.add(m);
76
+ return fresh;
77
+ }
78
+
71
79
  static latest(cwd) {
72
80
  const s = listSessions().find((x) => x.cwd === cwd);
73
81
  return s ? Session.load(s.id) : null;
@@ -166,3 +174,82 @@ export function listSessions() {
166
174
  }
167
175
  return out.sort((a, b) => b.updated - a.updated);
168
176
  }
177
+
178
+ const WRITE_TOOLS = new Set(['write_file', 'edit_file', 'multi_edit', 'notebook_edit']);
179
+ const hostOf = (url) => {
180
+ try {
181
+ return new URL(url).host;
182
+ } catch {
183
+ return String(url);
184
+ }
185
+ };
186
+
187
+ // What a session did, for leto audit: commands run, files written, hosts contacted and MCP calls,
188
+ // each with who allowed it. Reads the raw log, so calls from before a compaction are included.
189
+ // shortcut: sub-agents (task) keep their tool calls in memory, so only their task call is listed; log them too if audits need them.
190
+ export function auditSession(idOrPrefix) {
191
+ const file = findSessionFile(idOrPrefix);
192
+ const events = readEvents(file);
193
+ const meta = events.find((e) => e.type === 'meta') ?? { id: path.basename(file, '.jsonl') };
194
+ const approvals = new Map(events.filter((e) => e.type === 'approval').map((e) => [e.id, e]));
195
+ const results = new Map(events.filter((e) => e.type === 'message' && e.message.role === 'tool').map((e) => [e.message.tool_call_id, String(e.message.content ?? '')]));
196
+ const entries = [];
197
+ for (const e of events) {
198
+ if (e.type !== 'message' || e.message.role !== 'assistant') continue;
199
+ for (const call of e.message.tool_calls ?? []) {
200
+ const tool = call.function?.name ?? '';
201
+ let a = {};
202
+ try {
203
+ a = JSON.parse(call.function.arguments || '{}') ?? {};
204
+ } catch {}
205
+ const targets = tool === 'bash' ? [['command', a.command]]
206
+ : WRITE_TOOLS.has(tool) ? [['file', a.path]]
207
+ : tool === 'apply_patch' ? (() => {
208
+ try {
209
+ return parsePatch(a.patch).map((f) => ['file', f.to ?? f.from]);
210
+ } catch {
211
+ return [['file', '(unreadable patch)']];
212
+ }
213
+ })()
214
+ : tool === 'web_fetch' || (tool === 'browser' && a.action === 'navigate') ? [['network', hostOf(a.url)]]
215
+ : tool === 'web_search' ? [['network', `web search: ${a.query}`]]
216
+ : tool.startsWith('mcp__') ? [['mcp', tool.slice(5).replace('__', ':')]]
217
+ : [];
218
+ const result = results.get(call.id);
219
+ const text = result?.replace(/^<untrusted-data-\w+>\n/, '');
220
+ const approval = approvals.get(call.id);
221
+ const status = result === undefined ? 'no result' : approval?.by === 'denied' || text.startsWith('Permission denied') ? 'denied' : text.startsWith('Blocked') ? 'blocked' : text.startsWith('Interrupted') ? 'interrupted' : text.startsWith('Error') ? 'error' : 'done';
222
+ // by is null when no prompt was needed, or in logs written before approvals were recorded.
223
+ for (const [kind, target] of targets) entries.push({ time: new Date(approval?.t ?? e.t).toISOString(), kind, target: String(target ?? ''), tool, by: approval?.by ?? null, status });
224
+ }
225
+ }
226
+ return { id: meta.id, cwd: meta.cwd, entries };
227
+ }
228
+
229
+ const plainText = (content) => (Array.isArray(content) ? content.filter((x) => x.type === 'text').map((x) => x.text).join('\n') : String(content ?? ''));
230
+
231
+ // The user messages a conversation can be rewound or forked to: { i (message index), text }.
232
+ export function rewindPoints(messages) {
233
+ const points = [];
234
+ messages.forEach((m, i) => {
235
+ if (m.role !== 'user') return;
236
+ const text = plainText(m.content).replace(/\n\n<(file|directory) path=[\s\S]*$/, '').replace(/\n\n\[[^\]]*\]\s*$/g, '').trim();
237
+ if (!text || text.startsWith('[Summary of the earlier conversation')) return;
238
+ points.push({ i, text });
239
+ });
240
+ return points;
241
+ }
242
+
243
+ // The conversation as Markdown (/export).
244
+ export function exportMarkdown(session, { model, cwd }) {
245
+ const lines = [`# leto session ${session.id}`, '', `- model: ${model}`, `- folder: ${cwd}`, ''];
246
+ for (const m of session.messages) {
247
+ const text = plainText(m.content);
248
+ if (m.role === 'user') lines.push('## You', '', text, '');
249
+ else if (m.role === 'assistant') {
250
+ if (text) lines.push('## leto', '', text, '');
251
+ for (const t of m.tool_calls ?? []) lines.push(`> **${t.function.name}** \`${t.function.arguments.slice(0, 300)}\``, '');
252
+ } else if (m.role === 'tool') lines.push('```', text.slice(0, 2000), '```', '');
253
+ }
254
+ return lines.join('\n');
255
+ }
package/src/tools.js CHANGED
@@ -3,8 +3,11 @@ import path from 'node:path';
3
3
  import { spawn, spawnSync } from 'node:child_process';
4
4
  import { browserTool } from './browser.js';
5
5
  import { syntaxCheck } from './verify.js';
6
- import { sandboxAvailable, sandboxCommand, looksBlocked } from './sandbox.js';
6
+ import { sandboxAvailable, sandboxCommand, looksBlocked, sandboxProxy, proxyEnv } from './sandbox.js';
7
7
  import { repairJson } from './toolcalls.js';
8
+ import { UNTRUSTED_TAG } from './prompt.js';
9
+ import { readConfigFile } from './config.js';
10
+ import { policyFixesSandboxNetwork } from './policy.js';
8
11
  import { repoMapTool } from './repomap.js';
9
12
  import { readPdf, readNotebook, editNotebook } from './documents.js';
10
13
  import { selfTool } from './selftool.js';
@@ -23,6 +26,32 @@ export function truncate(text, max = MAX_OUTPUT) {
23
26
  return `${text.slice(0, half)}\n\n… [${text.length - max} characters truncated] …\n\n${text.slice(-half)}`;
24
27
  }
25
28
 
29
+ // Third-party text for the model, inside the marker; any copy of the marker's nonce in the text is removed.
30
+ const fence = (text) => `<${UNTRUSTED_TAG}>\n${text.replace(new RegExp(UNTRUSTED_TAG.split('-').pop(), 'gi'), '[marker removed]')}\n</${UNTRUSTED_TAG}>`;
31
+
32
+ export const REDACTED = '[REDACTED SECRET]';
33
+ const SECRET_FORMATS = [
34
+ /\bsk-(?=[\w-]*\d)[\w-]{20,}/g, // Anthropic (sk-ant-), OpenAI and look-alike API keys; a digit is required so kebab-case names like sk-loading-spinner-container stay readable
35
+ /\b(?:gh[oprsu]_[A-Za-z0-9]{36,}|github_pat_\w{22,})/g,
36
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
37
+ /\bxox[abp]-[\w-]{10,}/g,
38
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g, // to the end when cut short
39
+ /(authorization["']?\s*[:=]\s*["']?(?:bearer\s+)?)eyJ[\w-]*\.[\w-]*\.[\w-]*/gi,
40
+ ];
41
+
42
+ // Secret values this machine knows: provider keys and *KEY/*TOKEN/*SECRET/*PASSWORD variables.
43
+ export function knownSecrets(apiKey) {
44
+ const keys = [apiKey, ...Object.values(readConfigFile().providers).map((p) => p?.apiKey)].filter((k) => k?.length >= 8);
45
+ const env = Object.entries(process.env).filter(([k, v]) => /(KEY|TOKEN|SECRET|PASSWORD)$/i.test(k) && v?.length >= 16).map(([, v]) => v);
46
+ return [...new Set([...keys, ...env])].sort((a, b) => b.length - a.length);
47
+ }
48
+
49
+ export function redact(text, secrets) {
50
+ for (const v of secrets) text = text.replaceAll(v, REDACTED);
51
+ for (const re of SECRET_FORMATS) text = text.replace(re, (m, pre) => (typeof pre === 'string' ? pre : '') + REDACTED);
52
+ return text;
53
+ }
54
+
26
55
  function resolvePath(ctx, p) {
27
56
  if (!p || typeof p !== 'string') throw new Error('path is required');
28
57
  if (p.startsWith('~/')) p = path.join(process.env.HOME || '', p.slice(2));
@@ -97,14 +126,20 @@ function runProcess(cmd, args, { cwd, signal, timeoutMs, shell = false, onOutput
97
126
  let size = 0;
98
127
  let timedOut = false;
99
128
  let aborted = false;
100
- let tail = '';
129
+ let pending = ''; // output since the last complete line
101
130
  const add = (d) => {
102
131
  size += d.length;
103
132
  if (size < 2_000_000) out += d.toString();
104
133
  if (onOutput) {
105
- tail = (tail + d.toString()).slice(-2000);
106
- const last = tail.split('\n').map((l) => l.trim()).filter(Boolean).pop();
107
- if (last) onOutput(last);
134
+ // Complete lines only (\r ends one too): a secret split across chunks is redacted once it is whole.
135
+ // shortcut: a line longer than 64 KB goes out unfinished, so a secret across that cut is missed; the tool_result is always redacted whole.
136
+ pending += d.toString();
137
+ const cut = Math.max(pending.lastIndexOf('\n'), pending.lastIndexOf('\r'));
138
+ if (cut < 0 && pending.length < 65_536) return;
139
+ const done = cut < 0 ? pending : pending.slice(0, cut + 1);
140
+ pending = cut < 0 ? '' : pending.slice(cut + 1);
141
+ const last = done.split(/[\r\n]/).map((l) => l.trim()).filter(Boolean).pop();
142
+ if (last) onOutput(last, done);
108
143
  }
109
144
  };
110
145
  child.stdout.on('data', add);
@@ -406,26 +441,31 @@ export const TOOLS = [
406
441
  async run(a, ctx) {
407
442
  const timeoutMs = Math.min(Math.max(a.timeout_ms || 120000, 1000), 600000);
408
443
  const shellPath = fs.existsSync('/bin/bash') ? '/bin/bash' : '/bin/sh';
409
- const onOutput = (ctx.depth ?? 0) === 0 ? (line) => ctx.ui.spinnerDetail?.(line) : undefined;
444
+ const secrets = knownSecrets(ctx.agent?.config?.apiKey);
445
+ const onOutput = (ctx.depth ?? 0) === 0 ? (line, chunk) => { ctx.ui.spinnerDetail?.(redact(line, secrets)); ctx.ui.toolOutput?.(ctx.callId, redact(chunk, secrets)); } : undefined;
410
446
  // The shell's directory and variables from earlier calls (per agent).
411
447
  const state = (ctx.agent ? (ctx.agent.shell ??= { cwd: ctx.cwd, env: {}, unset: [] }) : { cwd: ctx.cwd, env: {}, unset: [] });
412
448
  if (!fs.existsSync(state.cwd)) state.cwd = ctx.cwd;
413
449
  const baseEnv = { ...process.env, LETO: '1', ...state.env };
414
450
  for (const k of state.unset) delete baseEnv[k];
415
- const wrap = (command) => (ctx.permissions?.sandbox && !a.unsandboxed ? sandboxCommand(command, { cwd: ctx.cwd, network: ctx.permissions.sandboxNetwork, shell: shellPath }) : { cmd: shellPath, args: ['-c', command] });
451
+ const boxed = ctx.permissions?.sandbox && !a.unsandboxed;
452
+ const network = ctx.permissions?.sandboxNetwork && !policyFixesSandboxNetwork();
453
+ // shortcut: bwrap's own network namespace can't reach the proxy, so Linux stays offline; bridge a socket in once it can be tested there.
454
+ const proxied = boxed && !network && sandboxAvailable() === 'sandbox-exec';
455
+ const env = proxied ? { ...baseEnv, ...proxyEnv(await sandboxProxy()) } : baseEnv;
456
+ const wrap = (command) => (boxed ? sandboxCommand(command, { cwd: ctx.cwd, network, shell: shellPath }) : { cmd: shellPath, args: ['-c', command] });
416
457
  if (a.run_in_background) {
417
458
  const { cmd, args } = wrap(String(a.command));
418
- const p = startProcess({ cmd, args, cwd: state.cwd, env: baseEnv, command: String(a.command) });
459
+ const p = startProcess({ cmd, args, cwd: state.cwd, env, command: String(a.command) });
419
460
  await new Promise((r) => setTimeout(r, 800)); // catch an immediate failure
420
461
  const { text } = readProcess(p.id);
421
462
  return { content: `Started in the background as ${p.id}.\n${text}\nRead more output with bash_output {"id":"${p.id}"}; stop it with kill_process.`, display: `background ${p.id} · ${p.code === null ? 'running' : `exited ${p.code}`}` };
422
463
  }
423
464
  const stateFile = stateFileFor();
424
- const boxed = ctx.permissions?.sandbox && !a.unsandboxed;
425
465
  const { cmd, args } = wrap(withState(String(a.command), stateFile));
426
- const { out, code, timedOut, aborted, error } = await runProcess(cmd, args, { cwd: state.cwd, signal: ctx.signal, timeoutMs, onOutput, env: baseEnv });
466
+ const { out, code, timedOut, aborted, error } = await runProcess(cmd, args, { cwd: state.cwd, signal: ctx.signal, timeoutMs, onOutput, env });
427
467
  if (error) throw error;
428
- const next = readState(stateFile, baseEnv);
468
+ const next = readState(stateFile, env);
429
469
  let moved = '';
430
470
  if (next.cwd && next.cwd !== state.cwd && fs.existsSync(next.cwd)) {
431
471
  state.cwd = next.cwd;
@@ -441,7 +481,7 @@ export const TOOLS = [
441
481
  else if (aborted) result += '\n[interrupted by user]';
442
482
  else if (code !== 0) result += `\n[exit code ${code}]`;
443
483
  if (boxed && code !== 0 && looksBlocked(out)) {
444
- result += `\n[This ran in the sandbox, which allows writes only inside the project and temp folders${ctx.permissions.sandboxNetwork ? '' : ', has no network'}, and hides credentials. If the failure is from the sandbox, call bash again with unsandboxed: true and the user will be asked.]`;
484
+ result += `\n[This ran in the sandbox, which allows writes only inside the project and temp folders${network ? '' : ', reaches only allowlisted hosts (config sandboxAllow)'}, and hides credentials. If the failure is from the sandbox, call bash again with unsandboxed: true and the user will be asked.]`;
445
485
  }
446
486
  return boxed ? { content: result, display: undefined, sandboxed: true } : result;
447
487
  },
@@ -728,12 +768,14 @@ TOOLS.push(
728
768
  summary: (a) => `${a.worker ? `${a.worker} · ` : ''}${a.agent_type || 'explore'}${a.isolation === 'worktree' ? ' · worktree' : ''}: ${a.description}`,
729
769
  async run(a, ctx) {
730
770
  if (!ctx.agent?.runSubagent) throw new Error('Sub-agents are not available here.');
731
- return ctx.agent.runSubagent(a, ctx.signal);
771
+ return ctx.agent.runSubagent(a, ctx.signal, ctx.callId);
732
772
  },
733
773
  },
734
774
  );
735
775
 
736
776
  export const READ_ONLY_TOOLS = new Set(['read_file', 'grep', 'list_files', 'repo_map', 'lsp', 'web_fetch', 'web_search', 'skill']);
777
+ // Tools whose results carry text written by third parties (MCP tools too, by their mcp flag).
778
+ export const UNTRUSTED_TOOLS = new Set(['web_fetch', 'web_search', 'browser']);
737
779
  export const PARALLEL_SAFE = new Set(['read_file', 'grep', 'list_files', 'repo_map', 'lsp', 'web_fetch', 'web_search', 'skill', 'task']);
738
780
 
739
781
  // Web search: Tavily or Brave when you have an API key for them, otherwise
@@ -879,20 +921,26 @@ export async function executeToolCall(call, ctx) {
879
921
  // Tool input may arrive malformed or cut short; check it against the schema first.
880
922
  const problem = checkArgs(tool.parameters, args);
881
923
  if (problem) return `Error: invalid input for ${tool.name}: ${problem}. Fix the arguments and call the tool again.`;
924
+ if (tool.writes && !tool.mcp && tool.name !== 'bash' && JSON.stringify(args).includes(REDACTED)) {
925
+ return `Error: the input contains ${REDACTED}, which stands for a secret hidden from you; writing it would replace the real value in the file. Change the file without touching those parts.`;
926
+ }
882
927
  const sub = (ctx.depth ?? 0) > 0;
883
- const tag = { id: call.id ?? null };
884
- ctx.ui.toolStart(tool.label ?? tool.name, safe(() => tool.summary?.(args)) ?? '', { prefix: sub ? `${ctx.label}` : '', id: call.id ?? null, name: tool.name, input: args });
928
+ const tag = { id: call.id ?? null, agentId: ctx.agentId ?? null };
929
+ const forModel = (text) => (tool.mcp || UNTRUSTED_TOOLS.has(tool.name) ? fence(text) : text);
930
+ // Only a serve client asks for the results of sub-agent tools.
931
+ const show = !sub || ctx.ui.nestedResults;
932
+ ctx.ui.toolStart(tool.label ?? tool.name, safe(() => tool.summary?.(args)) ?? '', { prefix: sub ? `${ctx.label}` : '', id: call.id ?? null, agentId: tag.agentId, name: tool.name, input: args });
885
933
  try {
886
934
  if (tool.validate) tool.validate(args, ctx);
887
935
  const writes = tool.writes || tool.writesFor?.(args);
888
936
  if (writes && ctx.permissions.planMode) {
889
- if (!sub) ctx.ui.toolResult('Blocked: plan mode is on', true, tag);
937
+ if (show) ctx.ui.toolResult('Blocked: plan mode is on', true, tag);
890
938
  return 'Blocked: plan mode is on, so files cannot be changed and commands cannot run. Finish investigating with the read-only tools, then present your plan. The user turns plan mode off with /plan when they approve.';
891
939
  }
892
940
  if (ctx.hooks) {
893
941
  const pre = await ctx.hooks.run('PreToolUse', { tool: tool.name, input: args, sessionId: ctx.sessionId });
894
942
  if (pre.blocked) {
895
- if (!sub) ctx.ui.toolResult(`Blocked by hook: ${pre.reason.split('\n')[0]}`, true, tag);
943
+ if (show) ctx.ui.toolResult(`Blocked by hook: ${pre.reason.split('\n')[0]}`, true, tag);
896
944
  return `Blocked by a PreToolUse hook: ${pre.reason}`;
897
945
  }
898
946
  }
@@ -901,18 +949,19 @@ export async function executeToolCall(call, ctx) {
901
949
  preview = safe(() => tool.preview?.(args, ctx));
902
950
  if (preview && sub) preview.title = `[${ctx.label}] ${preview.title}`;
903
951
  const allowed = await ctx.permissions.check(tool.name, preview, args);
952
+ ctx.agent?.session?.append({ type: 'approval', id: call.id ?? null, tool: tool.name, by: allowed || 'denied' });
904
953
  if (!allowed) {
905
954
  ctx.ui.toolResult('Denied', true, tag);
906
955
  return 'Permission denied: the user declined this tool call. Do not retry it; ask the user how to proceed.';
907
956
  }
908
- }
957
+ } else if (tool.name === 'bash') ctx.agent?.session?.append({ type: 'approval', id: call.id ?? null, tool: tool.name, by: 'sandbox' });
909
958
  if (!sub) ctx.ui.startSpinner(tool.name === 'task' ? 'Agents working' : 'Running');
910
959
  // With an editor connected, remember each file's content before the edit to show a diff.
911
960
  const originals = new Map();
912
- let runCtx = ctx;
961
+ let runCtx = { ...ctx, callId: call.id ?? null };
913
962
  if (ctx.ide && tool.writes && tool.name !== 'bash') {
914
963
  const cp = ctx.checkpoints;
915
- runCtx = { ...ctx, checkpoints: { record: (p) => {
964
+ runCtx = { ...runCtx, checkpoints: { record: (p) => {
916
965
  if (!originals.has(p)) originals.set(p, fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : '');
917
966
  cp?.record(p);
918
967
  } } };
@@ -937,15 +986,20 @@ export async function executeToolCall(call, ctx) {
937
986
  display = `${display ?? content.split('\n')[0]} · ⚠ ${n} error${n === 1 ? '' : 's'}`;
938
987
  }
939
988
  }
989
+ // The one place results are recorded: secrets never reach the screen, events, hooks, log or model (files on disk keep them).
990
+ const secrets = knownSecrets(ctx.agent?.config?.apiKey);
991
+ content = redact(String(content), secrets);
992
+ if (display) display = redact(display, secrets);
993
+ if (lines) lines = lines.map((l) => ({ ...l, text: redact(String(l.text), secrets) }));
940
994
  if (ctx.hooks) await ctx.hooks.run('PostToolUse', { tool: tool.name, input: args, result: truncate(String(content), 10000), sessionId: ctx.sessionId });
941
995
  // Skip the diff when the user just saw it in the approval prompt.
942
- if (!sub && display !== null) ctx.ui.toolResult(display ?? content, false, { ...tag, lines: preview?.shown ? null : lines, diff: lines, images: raw?.images });
943
- if (raw?.images?.length || raw?.documents?.length) return { text: truncate(String(content)), images: raw.images, documents: raw.documents };
944
- return truncate(String(content));
996
+ if (show && display !== null) ctx.ui.toolResult(display ?? content, false, { ...tag, lines: preview?.shown ? null : lines, diff: lines, images: raw?.images, agentUsage: raw?.agentUsage });
997
+ if (raw?.images?.length || raw?.documents?.length) return { text: forModel(truncate(String(content))), images: raw.images, documents: raw.documents };
998
+ return forModel(truncate(String(content)));
945
999
  } catch (err) {
946
- const msg = `Error: ${err.name === 'AbortError' || err.name === 'TimeoutError' ? (ctx.signal?.aborted ? 'interrupted by the user' : 'timed out') : err.message}`;
947
- if (!sub) ctx.ui.toolResult(msg, true, tag);
948
- return msg;
1000
+ const msg = redact(`Error: ${err.name === 'AbortError' || err.name === 'TimeoutError' ? (ctx.signal?.aborted ? 'interrupted by the user' : 'timed out') : err.message}`, knownSecrets(ctx.agent?.config?.apiKey));
1001
+ if (show) ctx.ui.toolResult(msg, true, tag);
1002
+ return forModel(msg);
949
1003
  }
950
1004
  }
951
1005