@mumbrane/leto 0.0.0-stage → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +395 -2
  2. package/bin/leto.js +8 -0
  3. package/evals/core/suite.json +249 -0
  4. package/index.js +12 -0
  5. package/package.json +43 -4
  6. package/src/agent.js +572 -0
  7. package/src/agents.js +68 -0
  8. package/src/anthropic.js +204 -0
  9. package/src/browser.js +427 -0
  10. package/src/btw.js +56 -0
  11. package/src/checkpoints.js +90 -0
  12. package/src/ci.js +115 -0
  13. package/src/cli.js +1926 -0
  14. package/src/client.js +111 -0
  15. package/src/config.js +205 -0
  16. package/src/documents.js +198 -0
  17. package/src/eval.js +289 -0
  18. package/src/hooks.js +115 -0
  19. package/src/ide.js +231 -0
  20. package/src/input.js +148 -0
  21. package/src/jobs.js +97 -0
  22. package/src/legacy.js +41 -0
  23. package/src/lsp.js +401 -0
  24. package/src/markdown.js +153 -0
  25. package/src/mcp.js +346 -0
  26. package/src/memory.js +136 -0
  27. package/src/orchestrator.js +141 -0
  28. package/src/patching.js +185 -0
  29. package/src/permissions.js +75 -0
  30. package/src/plugins.js +118 -0
  31. package/src/policy.js +74 -0
  32. package/src/pricing.js +67 -0
  33. package/src/processes.js +139 -0
  34. package/src/prompt.js +134 -0
  35. package/src/prompts.js +189 -0
  36. package/src/providers.js +59 -0
  37. package/src/repomap.js +211 -0
  38. package/src/sandbox.js +90 -0
  39. package/src/sdk.js +220 -0
  40. package/src/selftool.js +238 -0
  41. package/src/serve.js +233 -0
  42. package/src/session.js +168 -0
  43. package/src/setup.js +157 -0
  44. package/src/skills.js +125 -0
  45. package/src/theme.js +185 -0
  46. package/src/toolcalls.js +257 -0
  47. package/src/tools.js +976 -0
  48. package/src/tui.js +1179 -0
  49. package/src/ui.js +454 -0
  50. package/src/update.js +33 -0
  51. package/src/usage.js +83 -0
  52. package/src/verify.js +131 -0
  53. package/src/version.js +3 -0
  54. package/src/worktree.js +87 -0
  55. package/vscode/extension.js +132 -0
  56. package/vscode/package.json +21 -0
package/src/sandbox.js ADDED
@@ -0,0 +1,90 @@
1
+ // Sandboxed shell commands.
2
+ //
3
+ // With the sandbox on, bash commands run in an OS sandbox that can write only
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
6
+ // can't damage anything outside the project, it runs without asking.
7
+ // Commands that need more (installing packages, pushing, writing elsewhere)
8
+ // can ask to run outside the sandbox, which goes through the normal prompt.
9
+ //
10
+ // macOS: sandbox-exec (built in). Linux: bubblewrap (bwrap), if installed.
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+ import { spawnSync } from 'node:child_process';
15
+ import { HOME_DIR } from './config.js';
16
+
17
+ let cached;
18
+ export function sandboxAvailable() {
19
+ if (cached !== undefined) return cached;
20
+ if (process.platform === 'darwin' && fs.existsSync('/usr/bin/sandbox-exec')) cached = 'sandbox-exec';
21
+ else if (process.platform === 'linux' && spawnSync('bwrap', ['--version'], { stdio: 'ignore' }).status === 0) cached = 'bwrap';
22
+ else cached = null;
23
+ return cached;
24
+ }
25
+
26
+ const real = (p) => {
27
+ try {
28
+ return fs.realpathSync(p);
29
+ } catch {
30
+ return p;
31
+ }
32
+ };
33
+
34
+ // Folders a sandboxed command may write to, besides the project.
35
+ function writableDirs(cwd) {
36
+ const home = os.homedir();
37
+ const dirs = [real(cwd), real(os.tmpdir()), '/tmp', '/private/tmp', '/private/var/folders', '/dev'];
38
+ // Package-manager and build caches, so builds and tests work offline.
39
+ for (const d of ['.npm', '.cache', '.yarn', '.pnpm-store', '.bun', '.cargo/registry', '.cargo/git', 'go/pkg', '.gradle', '.m2', 'Library/Caches', '.rustup/tmp', '.local/share/pnpm']) {
40
+ dirs.push(path.join(home, d));
41
+ }
42
+ return [...new Set(dirs)];
43
+ }
44
+
45
+ // Secrets a sandboxed command may not read.
46
+ function secretPaths() {
47
+ const home = os.homedir();
48
+ return ['.ssh', '.aws', '.gnupg', '.config/gcloud', '.azure', '.kube', '.docker/config.json', '.netrc', '.npmrc', '.pypirc', '.git-credentials', '.config/gh', 'Library/Keychains', path.relative(home, HOME_DIR)].map((p) => path.join(home, p));
49
+ }
50
+
51
+ const q = (s) => `"${String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
52
+
53
+ export function macProfile(cwd, { network = false } = {}) {
54
+ const writes = writableDirs(cwd).map((d) => ` (subpath ${q(d)})`).join('\n');
55
+ const secrets = secretPaths().map((p) => ` (subpath ${q(p)})`).join('\n');
56
+ return `(version 1)
57
+ (allow default)
58
+ (deny file-write*)
59
+ (allow file-write*
60
+ ${writes}
61
+ (literal "/dev/null") (literal "/dev/stdout") (literal "/dev/stderr") (literal "/dev/tty"))
62
+ (deny file-read*
63
+ ${secrets})
64
+ ${network ? '' : `(deny network*)
65
+ (allow network* (remote unix-socket))
66
+ (allow network-bind (local ip "localhost:*"))
67
+ (allow network-inbound (local ip "localhost:*"))
68
+ (allow network-outbound (remote ip "localhost:*"))`}
69
+ `;
70
+ }
71
+
72
+ // The command line to run `command` inside the sandbox.
73
+ export function sandboxCommand(command, { cwd, network = false, shell = '/bin/bash' }) {
74
+ const kind = sandboxAvailable();
75
+ if (kind === 'sandbox-exec') return { cmd: '/usr/bin/sandbox-exec', args: ['-p', macProfile(cwd, { network }), shell, '-c', command] };
76
+ if (kind === 'bwrap') {
77
+ const args = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp', '--die-with-parent'];
78
+ for (const d of writableDirs(cwd)) if (fs.existsSync(d) && !d.startsWith('/dev') && d !== '/tmp') args.push('--bind', d, d);
79
+ for (const p of secretPaths()) if (fs.existsSync(p)) args.push(fs.statSync(p).isDirectory() ? '--tmpfs' : '--ro-bind', ...(fs.statSync(p).isDirectory() ? [p] : ['/dev/null', p]));
80
+ if (!network) args.push('--unshare-net');
81
+ args.push('--chdir', cwd, shell, '-c', command);
82
+ return { cmd: 'bwrap', args };
83
+ }
84
+ return null;
85
+ }
86
+
87
+ // Did the sandbox (rather than the command itself) cause the failure?
88
+ 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);
90
+ }
package/src/sdk.js ADDED
@@ -0,0 +1,220 @@
1
+ // Programmatic use: run leto from your own code.
2
+ //
3
+ // import { query } from '@mumbrane/leto';
4
+ // for await (const ev of query({ prompt: 'fix the failing test', permissionMode: 'acceptEdits' })) {
5
+ // if (ev.type === 'text') process.stdout.write(ev.text);
6
+ // if (ev.type === 'result') console.log('\n', ev.ok, ev.cost_usd);
7
+ // }
8
+ //
9
+ // Events: text, thinking, tool_start, tool_result, todos, info, error, and a
10
+ // final result. The same events are what `leto -p --stream-json` prints,
11
+ // one JSON object per line.
12
+ import { loadConfig } from './config.js';
13
+ import { resolveModel } from './client.js';
14
+ import { Session } from './session.js';
15
+ import { Agent } from './agent.js';
16
+ import { Permissions } from './permissions.js';
17
+ import { Checkpoints } from './checkpoints.js';
18
+ import { loadSkills } from './skills.js';
19
+ import { loadAgents } from './agents.js';
20
+ import { setPromptSkills } from './prompt.js';
21
+ import { setExtraTools, setAgentTypes } from './tools.js';
22
+ import { skillTool } from './skills.js';
23
+ import { buildMessage } from './input.js';
24
+ import { priceFor } from './pricing.js';
25
+ import { closeBrowser } from './browser.js';
26
+ import { loadOrchestrator, workerConfig } from './orchestrator.js';
27
+ import { setWorkers } from './tools.js';
28
+ import { checkModel, policyBudget, policyForcesSandbox, policyForbidsYolo } from './policy.js';
29
+
30
+ // A UI that turns everything the agent shows into events.
31
+ export class EventUI {
32
+ constructor(emit, { canUseTool, onQuestion } = {}) {
33
+ this.emit = emit;
34
+ this.canUseTool = canUseTool;
35
+ this.onQuestion = onQuestion;
36
+ this.print = !onQuestion; // no one to answer questions
37
+ this.out = process.stdout;
38
+ this.log = process.stderr;
39
+ this.c = new Proxy({}, { get: () => (s) => s });
40
+ }
41
+
42
+ text(s) {
43
+ if (s) this.emit({ type: 'text', text: s });
44
+ }
45
+
46
+ thinking(s) {
47
+ if (s) this.emit({ type: 'thinking', text: s });
48
+ }
49
+
50
+ toolStart(tool, summary, { prefix = '' } = {}) {
51
+ this.emit({ type: 'tool_start', tool, summary: String(summary ?? ''), agent: prefix || null });
52
+ }
53
+
54
+ toolResult(result, isError = false) {
55
+ this.emit({ type: 'tool_result', result: String(result ?? ''), is_error: Boolean(isError) });
56
+ }
57
+
58
+ todos(todos) {
59
+ this.emit({ type: 'todos', todos });
60
+ }
61
+
62
+ info(message) {
63
+ this.emit({ type: 'info', message: String(message).trim() });
64
+ }
65
+
66
+ success(message) {
67
+ this.info(message);
68
+ }
69
+
70
+ error(message) {
71
+ this.emit({ type: 'error', message: String(message) });
72
+ }
73
+
74
+ async confirm(preview, tool, { args } = {}) {
75
+ if (!this.canUseTool) return 'no';
76
+ const answer = await this.canUseTool({ tool, input: args ?? {}, title: preview?.title ?? tool });
77
+ return answer === true || answer === 'yes' ? 'yes' : answer === 'always' ? 'always' : 'no';
78
+ }
79
+
80
+ // Questions go to the onQuestion callback; without one, nobody can answer.
81
+ async ask(q) {
82
+ this.emit({ type: 'question', question: q.question, header: q.header ?? null, options: q.options, multi_select: Boolean(q.multiSelect) });
83
+ if (!this.onQuestion) return null;
84
+ const answer = await this.onQuestion({ question: q.question, header: q.header, options: q.options, multiSelect: Boolean(q.multiSelect) });
85
+ return answer == null || answer === '' ? null : { answer: Array.isArray(answer) ? answer.join(', ') : String(answer) };
86
+ }
87
+
88
+ write() {}
89
+ setBusy() {}
90
+ startResponse() {}
91
+ startSpinner() {}
92
+ stopSpinner() {}
93
+ spinnerDetail() {}
94
+ addTokens() {}
95
+ endText() {}
96
+ cancelRead() {}
97
+ }
98
+
99
+ export function resultEvent(agent, ok, { started } = {}) {
100
+ const last = [...agent.session.messages].reverse().find((m) => m.role === 'assistant' && m.content);
101
+ const text = last ? (Array.isArray(last.content) ? last.content.filter((p) => p.type === 'text').map((p) => p.text).join('\n') : String(last.content)) : '';
102
+ const u = agent.usage;
103
+ return {
104
+ type: 'result',
105
+ ok,
106
+ result: text,
107
+ error: ok ? null : agent.lastError,
108
+ session_id: agent.session.id,
109
+ model: agent.config.model,
110
+ tool_calls: agent.toolCount,
111
+ duration_ms: started ? Date.now() - started : undefined,
112
+ usage: { input_tokens: u.input, output_tokens: u.output, cache_read_tokens: u.cacheRead, cache_write_tokens: u.cacheWrite, requests: u.requests },
113
+ cost_usd: u.priced && priceFor(agent.config.model) ? Number(u.cost.toFixed(6)) : null,
114
+ };
115
+ }
116
+
117
+ const MODES = ['deny', 'ask', 'acceptEdits', 'plan', 'yolo'];
118
+
119
+ // Run one prompt and stream its events.
120
+ export async function* query({
121
+ prompt,
122
+ cwd = process.cwd(),
123
+ provider,
124
+ model,
125
+ apiKey,
126
+ baseUrl,
127
+ permissionMode = 'deny',
128
+ allowedTools = [],
129
+ canUseTool,
130
+ onQuestion,
131
+ sandbox = false,
132
+ checkCommand = '',
133
+ toolMode,
134
+ maxCost,
135
+ resume,
136
+ persistSession = true,
137
+ loadProjectFiles = false,
138
+ orchestrate = false,
139
+ signal,
140
+ } = {}) {
141
+ if (!prompt) throw new Error('query() needs a prompt.');
142
+ if (!MODES.includes(permissionMode)) throw new Error(`permissionMode must be one of: ${MODES.join(', ')}`);
143
+ const config = loadConfig({ provider, model, baseUrl });
144
+ if (apiKey) config.apiKey = apiKey;
145
+ if (toolMode) config.toolMode = toolMode;
146
+ if (checkCommand) config.checkCommand = checkCommand;
147
+ if (!config.provider || !config.baseUrl) throw new Error('No provider configured. Pass provider and apiKey, or run `leto` once to set one up.');
148
+ config.model = await resolveModel(config);
149
+ checkModel(config.model);
150
+ if (permissionMode === 'yolo' && policyForbidsYolo()) throw new Error("permissionMode 'yolo' is not allowed by your organization's policy.");
151
+
152
+ const queue = [];
153
+ let wake = null;
154
+ const emit = (ev) => {
155
+ queue.push(ev);
156
+ wake?.();
157
+ };
158
+ const ui = new EventUI(emit, { canUseTool, onQuestion });
159
+ const session = resume ? Session.load(resume) : persistSession ? Session.create({ cwd, model: config.model }) : Session.memory();
160
+ const permissions = new Permissions({ ui, mode: permissionMode === 'yolo' ? 'yolo' : permissionMode === 'ask' && canUseTool ? 'ask' : 'deny', allow: allowedTools });
161
+ if (permissionMode === 'acceptEdits') permissions.acceptEdits = true;
162
+ if (permissionMode === 'plan') permissions.planMode = true;
163
+ permissions.sandbox = Boolean(sandbox) || policyForcesSandbox();
164
+ permissions.sandboxNetwork = sandbox === 'network';
165
+
166
+ const skills = loadSkills(cwd, { includeProject: loadProjectFiles });
167
+ const agents = loadAgents(cwd, { includeProject: loadProjectFiles });
168
+ setPromptSkills(skills);
169
+ setAgentTypes(agents);
170
+ setExtraTools(skills.length ? [skillTool(() => skills)] : []);
171
+
172
+ const agent = new Agent({ config, session, ui, permissions, cwd, checkpoints: session.file ? new Checkpoints(session.file) : null });
173
+ agent.agentDefs = new Map(agents.map((a) => [a.name, a]));
174
+ if (maxCost) agent.budget = Number(maxCost);
175
+ if (policyBudget()) agent.budget = agent.budget ? Math.min(agent.budget, policyBudget()) : policyBudget();
176
+ // orchestrate: true uses the team saved with /orchestrate; or pass { brain, team }.
177
+ if (orchestrate) {
178
+ const o = orchestrate === true ? loadOrchestrator() : orchestrate;
179
+ if (!o.brain || !o.team?.length) throw new Error('orchestrate needs a brain and a team (set one up with /orchestrate, or pass { brain, team }).');
180
+ Object.assign(config, workerConfig({ ...o.brain, name: 'brain' }, config));
181
+ agent.orchestrator = o;
182
+ setWorkers(o.team);
183
+ } else setWorkers(null);
184
+ const onAbort = () => agent.interrupt();
185
+ signal?.addEventListener('abort', onAbort, { once: true });
186
+
187
+ const started = Date.now();
188
+ let finished = false;
189
+ let ok = false;
190
+ const { content } = buildMessage(prompt, cwd);
191
+ const run = agent.send(content).then((r) => {
192
+ ok = r;
193
+ }, (err) => emit({ type: 'error', message: err.message })).finally(() => {
194
+ finished = true;
195
+ wake?.();
196
+ });
197
+ try {
198
+ while (!finished || queue.length) {
199
+ if (!queue.length) await new Promise((r) => (wake = r));
200
+ wake = null;
201
+ while (queue.length) yield queue.shift();
202
+ }
203
+ await run;
204
+ yield resultEvent(agent, ok, { started });
205
+ } finally {
206
+ signal?.removeEventListener('abort', onAbort);
207
+ if (!finished) agent.interrupt();
208
+ closeBrowser();
209
+ }
210
+ }
211
+
212
+ // Run a prompt to completion and return the result event.
213
+ export async function run(prompt, options = {}) {
214
+ let result = null;
215
+ for await (const ev of query({ ...options, prompt })) {
216
+ if (ev.type === 'result') result = ev;
217
+ options.onEvent?.(ev);
218
+ }
219
+ return result;
220
+ }
@@ -0,0 +1,238 @@
1
+ // The `leto` tool: leto knowing about, and operating, itself.
2
+ //
3
+ // The model uses it to answer questions about leto from its own manual,
4
+ // to see its own state (model, context, cost, modes), to list what it has
5
+ // (skills, agents, commands, MCP servers, branches, jobs), and to change its
6
+ // own settings when the work calls for it: plan mode, compaction, effort,
7
+ // the sandbox, the project check, background jobs, reloading new skills and
8
+ // agents. Anything that widens what leto may do without asking (turning
9
+ // the sandbox off, setting a check command, leaving plan mode, starting a
10
+ // job) asks the user first.
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { VERSION } from './version.js';
14
+ import { loadSkills } from './skills.js';
15
+ import { loadAgents } from './agents.js';
16
+ import { loadCustomCommands } from './input.js';
17
+ import { listLetoBranches } from './worktree.js';
18
+ import { listJobs, startJob } from './jobs.js';
19
+ import { saveProjectCheck, isTrustedProject, HOME_DIR, CONFIG_PATH } from './config.js';
20
+ import { repoRoot } from './worktree.js';
21
+ import { sandboxAvailable } from './sandbox.js';
22
+ import { detectChecks } from './verify.js';
23
+ import { isNativeAnthropic, modelTraits } from './anthropic.js';
24
+ import { formatCost } from './pricing.js';
25
+ import { policyForcesSandbox } from './policy.js';
26
+ import { projectDir } from './legacy.js';
27
+
28
+ const README = new URL('../README.md', import.meta.url);
29
+
30
+ export function manualSections() {
31
+ let text = '';
32
+ try {
33
+ text = fs.readFileSync(README, 'utf8');
34
+ } catch {
35
+ return [];
36
+ }
37
+ const out = [];
38
+ let cur = { title: 'Overview', body: '' };
39
+ for (const line of text.split('\n')) {
40
+ const m = line.match(/^(#{2,3})\s+(.*)$/);
41
+ if (m) {
42
+ if (cur.body.trim()) out.push(cur);
43
+ cur = { title: m[2].trim(), body: '' };
44
+ } else cur.body += line + '\n';
45
+ }
46
+ if (cur.body.trim()) out.push(cur);
47
+ return out;
48
+ }
49
+
50
+ export function searchManual(topic) {
51
+ const sections = manualSections();
52
+ if (!sections.length) return 'The manual (README.md) is not available in this install.';
53
+ const terms = String(topic ?? '').toLowerCase().split(/[^a-z0-9/_-]+/).filter((t) => t.length > 1);
54
+ if (!terms.length) return `leto ${VERSION} manual. Sections:\n${sections.map((s) => `- ${s.title}`).join('\n')}\n\nCall again with a topic to read one.`;
55
+ const scored = sections
56
+ .map((s) => {
57
+ const t = s.title.toLowerCase();
58
+ const b = s.body.toLowerCase();
59
+ let score = 0;
60
+ for (const term of terms) {
61
+ if (t.includes(term)) score += 10;
62
+ score += Math.min(8, b.split(term).length - 1);
63
+ }
64
+ return { s, score };
65
+ })
66
+ .filter((x) => x.score > 0)
67
+ .sort((a, b) => b.score - a.score)
68
+ .slice(0, 3);
69
+ if (!scored.length) return `Nothing in the manual matches "${topic}". Sections: ${sections.map((s) => s.title).join(', ')}`;
70
+ return scored.map(({ s }) => `## ${s.title}\n${s.body.trim()}`).join('\n\n').slice(0, 12000);
71
+ }
72
+
73
+ const ACTIONS = ['docs', 'status', 'list', 'plan_mode', 'exit_plan_mode', 'compact', 'effort', 'sandbox', 'set_check', 'background', 'reload'];
74
+
75
+ export const selfTool = {
76
+ name: 'leto',
77
+ description: `Know and operate yourself (leto, the harness you run in). Actions:
78
+ - docs {topic}: read your own manual about a feature (e.g. "sandbox", "custom agents", "evals", "hooks", "mcp"). Use it to answer the user's questions about leto accurately, and to recall how a feature works before using it.
79
+ - status: your model, context use, cost, budget, permission mode, plan mode, sandbox, check command, task list.
80
+ - list {what}: skills | agents | commands | mcp | branches | jobs | checks (suggested check commands for this project) | team (orchestrator mode).
81
+ - plan_mode: switch to plan mode yourself before a large or risky change (read-only until the plan is approved).
82
+ - exit_plan_mode {plan}: present your plan; the user approves it to leave plan mode and start building.
83
+ - compact {focus}: summarize older history now to free context (say what to keep), e.g. before a long new phase.
84
+ - effort {level}: low | medium | high | xhigh | max (Claude only): think less on simple steps, more on hard ones.
85
+ - sandbox {enabled, network}: turn the shell sandbox on (no prompt) or off (asks the user).
86
+ - set_check {command}: choose the project check that runs after edits ("off" to remove; asks the user).
87
+ - background {prompt, allow_edits}: start a background job that keeps going on its own (asks the user).
88
+ - reload: pick up skills, agents and commands you just created, without restarting.`,
89
+ parameters: {
90
+ type: 'object',
91
+ properties: {
92
+ action: { type: 'string', enum: ACTIONS },
93
+ topic: { type: 'string', description: 'docs: what to look up' },
94
+ what: { type: 'string', enum: ['skills', 'agents', 'commands', 'mcp', 'branches', 'jobs', 'checks', 'team'], description: 'list: what to list' },
95
+ plan: { type: 'string', description: 'exit_plan_mode: the plan to show the user' },
96
+ focus: { type: 'string', description: 'compact: what the summary must keep' },
97
+ level: { type: 'string', enum: ['low', 'medium', 'high', 'xhigh', 'max'], description: 'effort: the level' },
98
+ enabled: { type: 'boolean', description: 'sandbox: on or off' },
99
+ network: { type: 'boolean', description: 'sandbox: allow network access' },
100
+ command: { type: 'string', description: 'set_check: the command, or "off"' },
101
+ prompt: { type: 'string', description: 'background: full instructions for the job' },
102
+ allow_edits: { type: 'boolean', description: 'background: let the job edit files (commands still need --yolo)' },
103
+ },
104
+ required: ['action'],
105
+ },
106
+ summary: (a) => [a.action, a.topic || a.what || a.level || a.command || (a.enabled === undefined ? '' : a.enabled ? 'on' : 'off')].filter(Boolean).join(' '),
107
+ // Actions that only change state the user controls go through the normal permission prompt.
108
+ needsPermissionFor: (a, ctx) =>
109
+ a.action === 'set_check' || a.action === 'background' || (a.action === 'sandbox' && a.enabled === false && ctx?.permissions?.sandbox) || (a.action === 'sandbox' && a.network === true),
110
+ writesFor: (a) => a.action === 'background' || a.action === 'set_check',
111
+ preview(a) {
112
+ if (a.action === 'set_check') return { title: a.command === 'off' ? 'Turn off the project check' : `Run \`${a.command}\` as the project check after edits`, lines: [] };
113
+ if (a.action === 'background') return { title: `Start a background job${a.allow_edits ? ' that can edit files' : ' (read-only)'}`, lines: String(a.prompt ?? '').split('\n').slice(0, 10).map((text) => ({ sign: ' ', text })) };
114
+ if (a.action === 'sandbox') return { title: a.network ? 'Allow sandboxed commands to use the network' : 'Turn the shell sandbox off (commands will ask again)', lines: [] };
115
+ return { title: `leto ${a.action}`, lines: [] };
116
+ },
117
+ async run(a, ctx) {
118
+ const agent = ctx.agent;
119
+ if (!agent) throw new Error('Not available here.');
120
+ const p = agent.permissions;
121
+ const cfg = agent.config;
122
+ switch (a.action) {
123
+ case 'docs': {
124
+ const text = searchManual(a.topic);
125
+ return { content: text, display: a.topic ? `manual: ${a.topic}` : 'manual sections' };
126
+ }
127
+ case 'status': {
128
+ const used = agent.contextTokens();
129
+ const u = agent.usage;
130
+ const lines = [
131
+ `leto ${VERSION}`,
132
+ `model: ${cfg.model} (${cfg.providerName || cfg.provider})${cfg.subagentModel ? `; sub-agents: ${cfg.subagentModel}` : ''}`,
133
+ `context: ~${used.toLocaleString()} of ${cfg.contextWindow.toLocaleString()} tokens (${Math.round((used / cfg.contextWindow) * 100)}%); auto-compacts at 80%`,
134
+ `cost so far: ${u.requests ? formatCost(u.cost) : '$0'}${agent.budget ? ` of a $${agent.budget.toFixed(2)} budget` : ''} over ${u.requests} requests`,
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)'}`,
137
+ `project check: ${cfg.checkCommand || 'none'}`,
138
+ `effort: ${cfg.effort || 'default'}${isNativeAnthropic(cfg) && modelTraits(cfg.model).effort ? '' : ' (not adjustable for this model)'}`,
139
+ `tool mode: ${cfg.toolMode || 'native'}`,
140
+ `orchestrator: ${agent.orchestrator ? `on; you lead ${agent.orchestrator.team.map((m) => `${m.name} (${m.model})`).join(', ')}` : 'off'}`,
141
+ ...(Object.keys(agent.usage.byModel ?? {}).length > 1 ? [`cost by model: ${Object.entries(agent.usage.byModel).map(([m, x]) => `${m} ${x.priced ? formatCost(x.cost) : '?'} (${x.requests} req)`).join(', ')}`] : []),
142
+ `task list: ${agent.todos.length ? agent.todos.map((t) => `[${t.status}] ${t.content}`).join('; ') : 'empty'}`,
143
+ `session: ${agent.session.id} · working directory: ${agent.cwd}`,
144
+ `config: ${CONFIG_PATH}`,
145
+ ];
146
+ return { content: lines.join('\n'), display: `${Math.round((used / cfg.contextWindow) * 100)}% context · ${p.planMode ? 'plan mode' : p.mode}` };
147
+ }
148
+ case 'list': {
149
+ const cwd = agent.cwd;
150
+ const trusted = isTrustedProject(cwd);
151
+ const what = a.what || 'skills';
152
+ let items = [];
153
+ if (what === 'skills') items = loadSkills(cwd, { includeProject: trusted }).map((s) => `${s.name}: ${s.description} (${s.file})`);
154
+ else if (what === 'agents') items = loadAgents(cwd, { includeProject: trusted }).map((d) => `${d.name}: ${d.description} · tools: ${d.tools?.join(', ') ?? 'all'}${d.model ? ` · model ${d.model}` : ''} (${d.file})`);
155
+ else if (what === 'commands') items = [...loadCustomCommands(cwd).values()].map((c) => `/${c.name}: ${c.description} (${c.file})`);
156
+ else if (what === 'mcp') items = (agent.mcpServers ?? []).map((s) => `${s.name}: ${s.error ? `error: ${s.error}` : `${s.tools?.length ?? 0} tools${s.tools?.length ? ` (${s.tools.map((t) => t.name).join(', ')})` : ''}`}`);
157
+ else if (what === 'branches') items = listLetoBranches(cwd).map((b) => `${b.branch} · ${b.when} · ${b.subject}`);
158
+ else if (what === 'jobs') items = listJobs().slice(0, 20).map((j) => `${j.id} [${j.status}] ${j.prompt.slice(0, 80)}`);
159
+ else if (what === 'checks') items = detectChecks(cwd).map((c) => `${c.command} (${c.why})`);
160
+ else if (what === 'team') items = (agent.orchestrator?.team ?? []).map((m) => `${m.name}: ${m.model} (${m.provider}) · ${m.strengths}`);
161
+ const where = {
162
+ skills: `Create one as a folder with a SKILL.md (frontmatter: name, description) in ${path.join(HOME_DIR, 'skills')} or ${path.join(projectDir(cwd), 'skills')}, then call reload.`,
163
+ agents: `Create one as a .md file (frontmatter: name, description, tools, model; body: instructions) in ${path.join(projectDir(cwd), 'agents')} or ${path.join(HOME_DIR, 'agents')}, then call reload.`,
164
+ commands: `Create one as ${path.join(projectDir(cwd), 'commands', '<name>.md')} ($ARGUMENTS is replaced with what follows the command).`,
165
+ }[what];
166
+ return { content: `${what}:\n${items.length ? items.map((x) => `- ${x}`).join('\n') : '(none)'}${where ? `\n\n${where}` : ''}`, display: `${items.length} ${what}` };
167
+ }
168
+ case 'plan_mode': {
169
+ if (p.planMode) return 'Plan mode is already on.';
170
+ p.planMode = true;
171
+ 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
+ case 'exit_plan_mode': {
174
+ if (!p.planMode) return 'Plan mode is not on; go ahead.';
175
+ if (!a.plan) throw new Error('plan is required: write out the plan for the user to approve.');
176
+ const preview = { title: 'Approve this plan and start building?', lines: String(a.plan).split('\n').slice(0, 40).map((text) => ({ sign: ' ', text })) };
177
+ const answer = p.mode === 'yolo' ? 'yes' : p.mode === 'deny' ? 'no' : await ctx.ui.confirm(preview, 'exit_plan_mode', { args: a });
178
+ if (answer === 'no') {
179
+ ctx.agent.permissions.onDeny?.();
180
+ return { content: 'The user did not approve the plan. Stay in plan mode; ask what to change.', display: 'plan not approved' };
181
+ }
182
+ p.planMode = false;
183
+ return { content: 'The user approved the plan. Plan mode is OFF; carry it out now.', display: 'plan approved · building' };
184
+ }
185
+ case 'compact': {
186
+ agent.pendingCompact = a.focus ?? '';
187
+ return { content: 'Older history will be summarized before your next step. Keep going.', display: 'compacting next step' };
188
+ }
189
+ case 'effort': {
190
+ if (!isNativeAnthropic(cfg) || !modelTraits(cfg.model).effort) return `Effort can't be set for ${cfg.model}.`;
191
+ if (!a.level) throw new Error('level is required');
192
+ cfg.effort = a.level;
193
+ return { content: `Effort is now ${a.level} for the rest of this session.`, display: `effort ${a.level}` };
194
+ }
195
+ case 'sandbox': {
196
+ if (!sandboxAvailable()) return 'No sandbox is available on this system (Linux needs bubblewrap).';
197
+ if (a.enabled === false && policyForcesSandbox()) return "Your organization's policy keeps the sandbox on.";
198
+ if (a.enabled !== undefined) p.sandbox = a.enabled;
199
+ 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' : ''}` };
201
+ }
202
+ case 'set_check': {
203
+ if (!a.command) throw new Error('command is required (or "off").');
204
+ const key = repoRoot(agent.cwd) ?? agent.cwd;
205
+ if (a.command === 'off') {
206
+ cfg.checkCommand = '';
207
+ saveProjectCheck(key, null);
208
+ return 'The project check is off.';
209
+ }
210
+ cfg.checkCommand = a.command;
211
+ saveProjectCheck(key, a.command);
212
+ return { content: `Project check set to \`${a.command}\`; it runs before a turn that changed files ends.`, display: `check: ${a.command}` };
213
+ }
214
+ case 'background': {
215
+ if (!a.prompt) throw new Error('prompt is required');
216
+ const flags = a.allow_edits ? ['--allow', 'edit_file,write_file,multi_edit,notebook_edit'] : [];
217
+ if (p.sandbox) flags.push('--sandbox');
218
+ const job = startJob({ prompt: a.prompt, cwd: agent.cwd, flags });
219
+ return { content: `Started background job ${job.id}. Check it with leto list jobs; its log: leto jobs log ${job.id}.`, display: `job ${job.id} started` };
220
+ }
221
+ case 'reload': {
222
+ const cwd = agent.cwd;
223
+ const trusted = isTrustedProject(cwd);
224
+ const skills = loadSkills(cwd, { includeProject: trusted });
225
+ const agents = loadAgents(cwd, { includeProject: trusted });
226
+ agent.reloadExtras?.({ skills, agents });
227
+ agent.agentDefs = new Map(agents.map((d) => [d.name, d]));
228
+ const cmds = [...loadCustomCommands(cwd).keys()];
229
+ return {
230
+ content: `Reloaded. Skills: ${skills.map((s) => s.name).join(', ') || 'none'} (load with the skill tool). Agents: ${agents.map((d) => d.name).join(', ') || 'none'} (use as task agent_type). Commands: ${cmds.map((c) => `/${c}`).join(', ') || 'none'}.`,
231
+ display: `${skills.length} skills · ${agents.length} agents · ${cmds.length} commands`,
232
+ };
233
+ }
234
+ default:
235
+ throw new Error(`Unknown action "${a.action}". Actions: ${ACTIONS.join(', ')}`);
236
+ }
237
+ },
238
+ };