Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(agent): sixteen typed tools fold into shell_execute, old names redirect

Davide64654cfcae3
diff --git a/src-tauri/src/commands/bg_tasks.rs b/src-tauri/src/commands/bg_tasks.rs
index 000b281c..a41e3803 100644
--- a/src-tauri/src/commands/bg_tasks.rs
+++ b/src-tauri/src/commands/bg_tasks.rs
@@ -141,7 +141,7 @@ struct StartArgs {
// State-wrapping layer and call these directly — same as uselu's tests
// did against the originally `pub` fns with a hand-built `AppState`.
-async fn shell_task_start_impl(args: &Value) -> CmdResult {
+pub(crate) async fn shell_task_start_impl(args: &Value) -> CmdResult {
let a: StartArgs =
serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;
if a.command.trim().is_empty() {
@@ -315,7 +315,7 @@ struct IdArgs {
id: String,
}
-async fn shell_task_status_impl(args: &Value) -> CmdResult {
+pub(crate) async fn shell_task_status_impl(args: &Value) -> CmdResult {
let a: IdArgs = serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;
let task = REGISTRY
.get(&a.id)
@@ -326,7 +326,7 @@ async fn shell_task_status_impl(args: &Value) -> CmdResult {
Ok(json!(g.status))
}
-async fn shell_task_kill_impl(args: &Value) -> CmdResult {
+pub(crate) async fn shell_task_kill_impl(args: &Value) -> CmdResult {
let a: IdArgs = serde_json::from_value(args.clone()).map_err(|e| bad_request(e.to_string()))?;
let task = REGISTRY
.get(&a.id)
@@ -343,7 +343,7 @@ async fn shell_task_kill_impl(args: &Value) -> CmdResult {
}
}
-async fn shell_task_list_impl(_args: &Value) -> CmdResult {
+pub(crate) async fn shell_task_list_impl(_args: &Value) -> CmdResult {
let mut tasks = REGISTRY.list();
// Reverse-chronological — newest first reads better in the UI.
tasks.sort_by(|a, b| b.started_at.cmp(&a.started_at));
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 7ffe02d2..23587c8a 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -750,7 +750,32 @@ async fn handle_agent_tool(
}
"shell_execute" => {
let command = body.args.get("command").and_then(|v| v.as_str()).unwrap_or("").to_string();
- if command.is_empty() { Err("shell_execute needs a non-empty `command` argument.".into()) }
+ // Background-task actions folded into shell_execute (2.6.6 merge):
+ // task: "status" | "list" | "kill" plus task_id, and background:
+ // true for a detached start. Same registry as the desktop side.
+ let task = body.args.get("task").and_then(|v| v.as_str()).unwrap_or("");
+ if !task.is_empty() {
+ let id = body.args.get("task_id").or_else(|| body.args.get("id")).and_then(|v| v.as_str()).unwrap_or("");
+ let id_args = serde_json::json!({ "id": id });
+ match task {
+ "status" => crate::commands::bg_tasks::shell_task_status_impl(&id_args).await,
+ "kill" => crate::commands::bg_tasks::shell_task_kill_impl(&id_args).await,
+ "list" => crate::commands::bg_tasks::shell_task_list_impl(&id_args).await,
+ other => Err(format!("shell_execute: unknown task action \"{}\" (use status | list | kill).", other)),
+ }
+ }
+ else if command.is_empty() { Err("shell_execute needs a non-empty `command` argument (or a task action).".into()) }
+ else if body.args.get("background").and_then(|v| v.as_bool()).unwrap_or(false) {
+ let cwd_raw = body.args.get("cwd").and_then(|v| v.as_str()).map(String::from);
+ let cwd = cwd_raw
+ .filter(|c| !c.trim().is_empty())
+ .and_then(|c| resolve_remote_path(&c, chat_id.as_deref(), &app_state).ok())
+ .or_else(|| Some(crate::commands::agent::agent_workspace_for(chat_id.as_deref(), &app_state)
+ .to_string_lossy()
+ .to_string()));
+ let start_args = serde_json::json!({ "command": command, "cwd": cwd, "chat_id": chat_id });
+ crate::commands::bg_tasks::shell_task_start_impl(&start_args).await
+ }
else {
// Default cwd → the per-chat workspace folder so `npm install`
// / `git status` / etc. land in the same directory the agent
@@ -774,7 +799,8 @@ async fn handle_agent_tool(
}
let timeout = body.args.get("timeout").and_then(|v| v.as_u64());
let shell = body.args.get("shell").and_then(|v| v.as_str()).map(String::from);
- crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, chat_id.clone(), None).await
+ let stdin = body.args.get("stdin").and_then(|v| v.as_str()).map(String::from);
+ crate::commands::shell::shell_execute(command, None, cwd, timeout, shell, stdin, chat_id.clone(), None).await
}
}
"system_info" => crate::commands::system::system_info(),
@@ -2078,7 +2104,7 @@ button{-webkit-appearance:none;appearance:none}
// with live Thought/Action/Observation cards streamed into the chat.
// The old "you can't run tools" text was from v2.3.3 before the mobile
// bridge could actually execute them.
- var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / code_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';
+ var CODEX_PROMPT = 'You are the Coding Agent, an autonomous coding agent inside LU. You execute coding tasks end-to-end by reading files, writing code, and running shell commands. You MUST use tools — never guess file contents.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. Empty assistant messages are a FAILURE.\n\n2. DO NOT stop after the first tool. Real coding tasks take 3-15 tool calls. Stopping after one file_read or one shell_execute without producing the requested artefact = FAILURE. "I have called one tool, that is enough" is NOT a valid stop reason.\n\n3. NEVER say "Now I will create X" / "Next I\'ll write Y" as plain prose and then stop. Do the next step RIGHT NOW as a concrete tool call.\n\n4. When your plan has N steps, execute ALL N steps in one session — each step as a concrete tool call. Plan in tool-call form, not prose-then-stop.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk, OR (b) you are stuck and genuinely need user input.\n\n=== WORKFLOW ===\n\n1. Understand the task.\n2. If the task needs more than about three tool calls, call todo_write with the WHOLE plan before you start. The user sees that list live on their phone. It is how they follow a long run on a small screen. Call it again after each step with the complete list, the finished item completed and the next one in_progress. Never mark an item completed before it actually succeeded.\n3. Explore (file_list, file_read, file_search) when you need to know existing layout.\n4. Implement (file_write) — chain ALL writes without stopping.\n5. Verify (shell_execute / file_read).\n6. Only THEN write a short summary of what you did.\n\n=== FILE & DIRECTORY RULES ===\n\n- file_write AUTOMATICALLY creates any missing parent directories. Never call shell_execute with `mkdir`, `New-Item -ItemType Directory`, `md`, or `os.makedirs` to set up a folder before writing — just file_write the target path directly.\n- All relative paths resolve to the current chat workspace folder. Always pass relative paths (e.g. `client/public/index.html`) — do not hard-code absolute drive paths.\n- shell_execute runs inside the workspace folder by default. Do not `cd` into a parent or sibling folder; prefer relative commands.\n- On Windows, the shell is PowerShell. Quote arguments with spaces. Use forward slashes in paths inside commands. Avoid `mkdir -p` (PowerShell mkdir does not accept -p) — again, just use file_write.\n\n=== GENERAL ===\n\n- Always read a file before modifying it.\n- Chain tool calls: after each tool result, if there is another step left, IMMEDIATELY call the next tool.\n- If a command fails, diagnose and retry with corrected arguments — do not introduce yourself again.\n- After 2-3 failures of the same approach, switch strategy (e.g. file_write instead of shell mkdir) instead of repeating.\n- Be concise in text. All real work happens in tool calls.\n- Respond in the same language the user used in their message.';
// ── Thinking-compatible prefixes (parity with desktop) ──
// Keep in sync with THINKING_COMPATIBLE in src/lib/model-compatibility.ts.
@@ -2187,7 +2213,7 @@ button{-webkit-appearance:none;appearance:none}
var AGENT_TOOLS = [
{name:'todo_write', description:'Write the plan for a multi-step task and keep it up to date. The list is shown to the user live, so it is how they see what you are doing and how far along you are. USE FIRST on any task that needs more than about three tool calls: write the whole plan before the first step. Then call it again after each step to flip that item to completed and the next one to in_progress. Send the COMPLETE list every time. It replaces the previous one, it does not merge. Exactly one item should be in_progress at a time. DO NOT use it for a single-step request, and NEVER mark an item completed before the work actually succeeded.',
parameters:[{name:'todos',type:'array',description:'The complete plan, in order. Replaces the previous list.',required:true}]},
- {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. For current date/time, use get_current_time — do NOT web_search for it.',
+ {name:'web_search', description:'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. For the current date/time, trust the date line in the system prompt; do NOT web_search for it.',
parameters:[{name:'query',type:'string',description:'The search query string',required:true},
{name:'maxResults',type:'number',description:'Maximum results to return (default: 5, max: 20)',required:false}]},
{name:'web_fetch', description:'Fetch a single URL and return its readable text (up to ~24 000 chars). Strips <script>, <style>, <nav>, <header>, <footer>, <aside>, <form> — returns main content only. PREFER this over web_search when you already know the target URL. NEVER call with localhost, private IPs (10.*, 192.168.*, 172.16-31.*), or file:// — they are refused. If response is empty or 4xx, try a different URL rather than retrying the same one.',
@@ -2208,18 +2234,15 @@ button{-webkit-appearance:none;appearance:none}
parameters:[{name:'path',type:'string',description:'Directory to search in (recursive by default)',required:true},
{name:'pattern',type:'string',description:'Regex pattern to search for',required:true},
{name:'maxResults',type:'number',description:'Maximum matching files (default: 50)',required:false}]},
- {name:'shell_execute', description:'Run a shell command. PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`, get_current_time over `date`. Use shell_execute for git, npm, cargo, docker, package managers, or platform utilities without a dedicated tool. This is also how you open things on the desktop: a folder, a file, or an application. The system prompt states which OS this is and gives the exact command. NEVER use to permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). Default timeout 120 s; set higher only for known long-running builds.',
- parameters:[{name:'command',type:'string',description:'The full command to execute',required:true},
+ {name:'shell_execute', description:'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. Everything runs here: git, tests, package managers, gh, python, platform utilities. This is also how you open things on the desktop: files, folders, apps (the system prompt states the OS and the exact open command). Useful forms: `git status --porcelain=2 --branch` and a recognised test run (`npm test`, `npx vitest run`, `cargo test`, `pytest`) return a parsed summary; `git log --oneline -n 20`; `git diff`; `git add -A && git commit -m "msg"`; `git push`; `gh pr create --title "t" --body "b"`. Feed a script via `stdin` instead of quoting it: set command to `python3 -` or `bash -s` and put the source in `stdin` (fresh process each call, no REPL state). Long-running work: set `background: true` to get a task id back immediately; follow it by calling again with `task: "status"` and `task_id` (or `task: "list"` / `task: "kill"`). PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`. `git commit --no-verify` is refused. NEVER permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). Default timeout 120 s (recognised test runs get 300 s); set higher only for known long builds.',
+ parameters:[{name:'command',type:'string',description:'The full command to execute. Omit only for task actions.',required:false},
{name:'cwd',type:'string',description:'Working directory (optional, absolute preferred)',required:false},
{name:'timeout',type:'number',description:'Timeout in milliseconds (default: 120000)',required:false},
- {name:'shell',type:'string',description:'Override shell: "powershell" | "cmd" | "bash" (default: auto)',required:false}]},
- {name:'code_execute', description:'Execute Python code in a fresh subprocess. Returns stdout, stderr, exit code. Use for math, data transforms, JSON/CSV parsing, one-off scripts. NOT a REPL — state does not persist between calls; import everything you need each time. For system commands and shell utilities, PREFER shell_execute. Default timeout 30 s.',
- parameters:[{name:'code',type:'string',description:'The Python source to execute (UTF-8)',required:true},
- {name:'language',type:'string',description:'Programming language: "python" or "shell"',required:false}]},
- {name:'system_info', description:'Return desktop system info: OS, architecture, hostname, username, total RAM, CPU count. Zero arguments. Call once when output needs to be tailored to the user\'s platform; do not call repeatedly in a loop.',
- parameters:[]},
- {name:'process_list', description:'List the top 30 running processes sorted by memory: {name, pid, memory, cpu%}. Zero arguments. Use for task-manager-style queries ("is Chrome running?", "which process is eating RAM?"). There is NO process_kill tool — to kill a process use shell_execute with taskkill (Windows) or kill (Unix).',
- parameters:[]},
+ {name:'shell',type:'string',description:'Override shell: "powershell" | "cmd" | "bash" (default: auto)',required:false},
+ {name:'stdin',type:'string',description:'Text piped to the command\x27s stdin, e.g. a Python script for `python3 -`.',required:false},
+ {name:'background',type:'boolean',description:'Run detached; returns a task id immediately instead of waiting.',required:false},
+ {name:'task',type:'string',description:'Background-task action instead of running a command.',required:false},
+ {name:'task_id',type:'string',description:'Task id for task "status" or "kill".',required:false}]},
{name:'screenshot', description:'Capture the primary display as a base64 PNG. Zero arguments. USE for visual verification when the user asks "what\'s on my screen" or "look at X". Returns a short summary string (size + filename); the actual image is forwarded to the model via message content. NEVER call in a tight loop — screenshots are expensive and privacy-sensitive.',
parameters:[]},
{name:'image_generate', description:'Generate an image from a text prompt via the local image pipeline (Apple MLX on macOS; ComfyUI elsewhere, auto-detected). Blocks up to 5 minutes. USE for "draw me", "make an image of", "generate a picture". Pass `inputImage` (a filename from an earlier image_generate result) for image-to-image — restyle / edit an existing image at the given `denoise` strength; omit it for text-to-image. First installed image model is auto-selected (or pass `model`). EXPECT A PAUSE on non-Mac (ComfyUI) single-GPU machines: LU may briefly unload the chat model from VRAM to fit the image model, then reload it after — typically a 30-90s swap. This avoids out-of-memory errors; your conversation is fully preserved across the swap. Rate-limit yourself to 1 call per turn — generations serialize internally so parallel calls will queue, not speed up. Fine-tune with the optional `settings` object (steps, cfg, sampler, scheduler, width/height, seed, lora, vae); set ONLY what the user asked for. A value beyond the installed model\'s real limit is REJECTED with the actual limit so you can retry lower — values are never silently changed.',
@@ -2228,12 +2251,10 @@ button{-webkit-appearance:none;appearance:none}
{name:'model',type:'string',description:'Optional image model filename to use. Omit to auto-select the first installed image model.',required:false},
{name:'inputImage',type:'string',description:'Optional. Filename of a previously generated image (from an earlier image_generate result) to use as the base for image-to-image. Omit for text-to-image.',required:false},
{name:'denoise',type:'number',description:'Image-to-image strength 0.05–1.0 (default 0.6). Lower keeps more of the input image, higher follows the prompt more. Only used together with inputImage.',required:false}]},
- {name:'get_current_time', description:'Return the user\'s current local date, time, and timezone. Zero arguments. USE FIRST for any \'what day / time / date is it\' question — do NOT web_search or shell_execute `date`. The Rust backend probes the OS timezone on every call, so this is always authoritative.',
- parameters:[]}
];
// ── Tool-set constants ──
- var CODEX_TOOLS = ['file_read','file_write','file_list','file_search','shell_execute','code_execute','system_info','get_current_time','web_search','web_fetch'];
+ var CODEX_TOOLS = ['file_read','file_write','file_list','file_search','shell_execute','web_search','web_fetch'];
var AGENT_ALL_TOOLS = AGENT_TOOLS.map(function(t){return t.name;});
// ── Mobile parity helpers (Codex audit fixes) ──────────────────────
@@ -2657,7 +2678,7 @@ button{-webkit-appearance:none;appearance:none}
// blocks in chat with "save this as index.html" instead of calling
// file_write. Codex already had its own prompt; this matches the
// strictness for the LU-mode + Agent-on path.
- var AGENT_PROMPT = 'You are an autonomous AI agent inside LU. You execute tasks end-to-end via tools — you do NOT just describe what to do.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. There is no middle ground. Empty messages are a FAILURE.\n\n2. DO NOT stop after the FIRST tool. Real tasks take 3-10 tool calls. If the user said "build X" you write the files. If the user said "use every tool" you keep going through every tool. Stopping after one shell_execute or one get_current_time without producing a useful artefact = FAILURE.\n\n3. NEVER produce a code block followed by "save this as X". That is FAILURE — call file_write yourself.\n\n4. NEVER say "Now I will create X" / "Next I will write Y" as plain prose and stop. Do the next step right now as a concrete tool call.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk / web results returned / etc., OR (b) you are stuck in a way that genuinely needs user input. "I have called one tool, that should be enough" is NOT a valid stop reason.\n\n=== WORKFLOW ===\n\n- Build / create tasks: file_write each artefact directly, chain ALL writes, then write a 1-3 sentence final answer.\n- Read / explore tasks: file_list / file_read first, then proceed.\n- Web tasks: web_search → web_fetch on the best URL → summarize.\n- Multi-tool / "use every tool" tasks: plan the order, then call each tool one at a time, recording the partial result in a final summary file before the visible reply.\n\n=== FILE RULES ===\n\n- file_write AUTOMATICALLY creates missing parent directories — do NOT shell out to mkdir / New-Item / md / os.makedirs first. Just file_write the target path.\n- Relative paths resolve to the current chat workspace folder. Use relative paths (e.g. `index.html`, `src/app.py`); do not hard-code absolute drive letters.\n- After 2-3 failures of the same approach, switch strategy — do not repeat the same broken command. Do not introduce yourself again.\n\nBe concise in prose. All real work happens in tool calls. Respond in the same language the user used in their message.';
+ var AGENT_PROMPT = 'You are an autonomous AI agent inside LU. You execute tasks end-to-end via tools — you do NOT just describe what to do.\n\n=== HARD RULES ===\n\n1. AFTER EVERY TOOL RESULT, your very next message MUST be EITHER (a) another tool call to continue the work, OR (b) the final user-facing summary. There is no middle ground. Empty messages are a FAILURE.\n\n2. DO NOT stop after the FIRST tool. Real tasks take 3-10 tool calls. If the user said "build X" you write the files. If the user said "use every tool" you keep going through every tool. Stopping after one shell_execute or one web_search without producing a useful artefact = FAILURE.\n\n3. NEVER produce a code block followed by "save this as X". That is FAILURE — call file_write yourself.\n\n4. NEVER say "Now I will create X" / "Next I will write Y" as plain prose and stop. Do the next step right now as a concrete tool call.\n\n5. The ONLY reasons to stop calling tools: (a) the user task is FULLY done with concrete artefacts on disk / web results returned / etc., OR (b) you are stuck in a way that genuinely needs user input. "I have called one tool, that should be enough" is NOT a valid stop reason.\n\n=== WORKFLOW ===\n\n- Build / create tasks: file_write each artefact directly, chain ALL writes, then write a 1-3 sentence final answer.\n- Read / explore tasks: file_list / file_read first, then proceed.\n- Web tasks: web_search → web_fetch on the best URL → summarize.\n- Multi-tool / "use every tool" tasks: plan the order, then call each tool one at a time, recording the partial result in a final summary file before the visible reply.\n\n=== FILE RULES ===\n\n- file_write AUTOMATICALLY creates missing parent directories — do NOT shell out to mkdir / New-Item / md / os.makedirs first. Just file_write the target path.\n- Relative paths resolve to the current chat workspace folder. Use relative paths (e.g. `index.html`, `src/app.py`); do not hard-code absolute drive letters.\n- After 2-3 failures of the same approach, switch strategy — do not repeat the same broken command. Do not introduce yourself again.\n\nBe concise in prose. All real work happens in tool calls. Respond in the same language the user used in their message.';
// ── System prompt builder ──
function buildSystemPrompt(){
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index c20ed6b7..37781e25 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -189,11 +189,12 @@ pub async fn shell_execute(
cwd: Option<String>,
timeout: Option<u64>,
shell: Option<String>,
+ stdin: Option<String>,
chatId: Option<String>,
workingDirectory: Option<String>,
) -> Result<serde_json::Value, String> {
tokio::task::spawn_blocking(move || {
- shell_execute_sync(command, args, cwd, timeout, shell, chatId, workingDirectory)
+ shell_execute_sync(command, args, cwd, timeout, shell, stdin, chatId, workingDirectory)
})
.await
.map_err(|e| format!("Task join error: {}", e))?
@@ -205,6 +206,7 @@ fn shell_execute_sync(
cwd: Option<String>,
timeout: Option<u64>,
shell: Option<String>,
+ stdin: Option<String>,
chat_id: Option<String>,
working_directory: Option<String>,
) -> Result<serde_json::Value, String> {
@@ -256,15 +258,36 @@ fn shell_execute_sync(
cmd.current_dir(&workdir);
}
- cmd.stdin(Stdio::null())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped());
+ // stdin feeds a script instead of quoting it (`python -`, `bash -s`),
+ // replacing the code_execute tool (2.6.6 merge) and its PowerShell
+ // quoting trap along the way. No stdin stays Stdio::null so interactive
+ // commands still fail fast instead of hanging on a silent read.
+ if stdin.is_some() {
+ cmd.stdin(Stdio::piped());
+ } else {
+ cmd.stdin(Stdio::null());
+ }
+ cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
#[cfg(target_os = "windows")]
cmd.creation_flags(CREATE_NO_WINDOW);
let mut child = cmd.spawn().map_err(|e| format!("Spawn shell: {}", e))?;
+ // Write on a thread: the child may fill its output pipes before it has
+ // consumed stdin, and a blocking write here would deadlock against the
+ // drain below.
+ if let Some(input) = stdin {
+ if let Some(mut pipe) = child.stdin.take() {
+ std::thread::spawn(move || {
+ use std::io::Write;
+ let _ = pipe.write_all(input.as_bytes());
+ // Dropping the pipe closes it, which is the EOF `bash -s`
+ // and `python -` wait for.
+ });
+ }
+ }
+
// Start draining both pipes immediately — see `drain`.
let (out_buf, out_done) = match child.stdout.take() {
Some(p) => drain(p),
diff --git a/src/api/__tests__/mobile-codex-parity.test.ts b/src/api/__tests__/mobile-codex-parity.test.ts
index a3031d18..5517b5c5 100644
--- a/src/api/__tests__/mobile-codex-parity.test.ts
+++ b/src/api/__tests__/mobile-codex-parity.test.ts
@@ -41,12 +41,12 @@ describe('Mobile CODEX_TOOLS parity', () => {
expect(REMOTE_RS).toContain("'shell_execute'")
})
- it('includes code_execute', () => {
- expect(REMOTE_RS).toContain("'code_execute'")
- })
-
- it('includes system_info', () => {
- expect(REMOTE_RS).toContain("'system_info'")
+ it('does NOT include the tools retired by the 2.6.6 merge', () => {
+ // code_execute / system_info / get_current_time left CODEX_TOOLS when the
+ // typed wrappers folded into shell_execute plus the environment block.
+ expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*code_execute/)
+ expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*system_info/)
+ expect(REMOTE_RS).not.toMatch(/CODEX_TOOLS = \[[^\]]*get_current_time/)
})
it('includes web_search', () => {
diff --git a/src/api/__tests__/tool-description-parity.test.ts b/src/api/__tests__/tool-description-parity.test.ts
index b4ec1759..92741907 100644
--- a/src/api/__tests__/tool-description-parity.test.ts
+++ b/src/api/__tests__/tool-description-parity.test.ts
@@ -181,7 +181,7 @@ describe('tool-description-parity — extraction sanity', () => {
expect(builtinTools.length).toBeGreaterThanOrEqual(13)
})
it('parses the mobile AGENT_TOOLS list', () => {
- expect(mobileTools.length).toBeGreaterThanOrEqual(13)
+ expect(mobileTools.length).toBeGreaterThanOrEqual(9)
})
})
diff --git a/src/api/__tests__/tool-registry.test.ts b/src/api/__tests__/tool-registry.test.ts
index 7b6d1a8f..ced186be 100644
--- a/src/api/__tests__/tool-registry.test.ts
+++ b/src/api/__tests__/tool-registry.test.ts
@@ -25,23 +25,13 @@ const offeredDefNames = AGENT_TOOL_DEFS
// ── AGENT_TOOL_DEFS ─────────────────────────────────────────────
describe('AGENT_TOOL_DEFS', () => {
- it('contains exactly 33 tool definitions', () => {
- // Phase 13 v2.4.0: delegate_task added as a builtin (→ 15 tools).
- // v2.5.0 sprint A/B/C from uselu: +13 codex tools — shell_task_*,
- // shell_execute_background, git_*, gh_pr_create, pr_resume,
- // project_init, run_tests (→ 28 tools).
- // v2.5.0 Feature EE: video_generate (text-to-video via the VRAM hand-off
- // orchestrator) added alongside image_generate (→ 29 tools).
- // v2.5.9 M1: file_edit (surgical SEARCH/REPLACE edit) (→ 30 tools).
- // 2026-08-05 audit C4: todo_write — the plan the model keeps and the user
- // sees above the composer (→ 31 tools).
- // 2.6.3 B1 (Morgan): opening a folder or starting a program is NOT a tool.
- // desktop_open and app_launch existed here briefly and were removed on
- // 2026-08-06: they only wrapped `open` / `explorer` / `xdg-open`, cost ~478
- // tokens of every system prompt, and inherited the same confirm gate
- // shell_execute already had, so they bought nothing. The capability lives
- // in shell_execute plus the platform line from lib/host-platform.ts.
- expect(AGENT_TOOL_DEFS).toHaveLength(31)
+ it('contains exactly 15 tool definitions', () => {
+ // 2.6.6 tool merge (plan section E): the twelve typed shell wrappers,
+ // system_info, process_list and get_current_time folded into
+ // shell_execute plus the environment block in the system prompt, so the
+ // catalog went from 31 definitions to 15. The old names still execute
+ // via the retired-name redirect in mcp/builtin-tools.ts.
+ expect(AGENT_TOOL_DEFS).toHaveLength(15)
})
const expectedTools = [
@@ -53,28 +43,13 @@ describe('AGENT_TOOL_DEFS', () => {
'file_edit',
'file_list',
'file_search',
- 'code_execute',
'shell_execute',
- 'shell_execute_background',
- 'shell_task_status',
- 'shell_task_kill',
- 'shell_task_list',
- 'git_status',
- 'git_commit',
- 'git_push',
- 'git_log',
- 'git_diff',
- 'gh_pr_create',
'pr_resume',
- 'project_init',
- 'run_tests',
'image_generate',
'video_generate',
'run_workflow',
'screenshot',
- 'process_list',
- 'system_info',
- 'get_current_time',
+ 'delegate_task',
]
it.each(expectedTools)('includes the "%s" tool', (name) => {
@@ -100,7 +75,7 @@ describe('AGENT_TOOL_DEFS', () => {
// todo_write is category 'system' (auto) because it only writes the plan
// shown in the UI. Prompting for approval to write a to-do list would make
// the feature useless on a long unattended run.
- expect(autoNames).toEqual(['get_current_time', 'process_list', 'system_info', 'todo_write', 'web_fetch', 'web_search'])
+ expect(autoNames).toEqual(['todo_write', 'web_fetch', 'web_search'])
})
it('confirm-permission tools include file ops, code, shell, image, workflow, screenshot, delegate_task, sprint A/B/C tools', () => {
@@ -111,13 +86,11 @@ describe('AGENT_TOOL_DEFS', () => {
// shell, git, gh, project_init, run_tests — all touch the user's machine).
// v2.5.0 Feature EE: video_generate (image category → confirm default).
expect(confirmNames).toEqual([
- 'code_execute', 'delegate_task',
+ 'delegate_task',
'file_edit', 'file_list', 'file_read', 'file_search',
- 'file_write', 'gh_pr_create', 'git_commit', 'git_diff', 'git_log',
- 'git_push', 'git_status', 'image_generate', 'pr_resume', 'project_init',
- 'run_tests', 'run_workflow', 'screenshot', 'shell_execute',
- 'shell_execute_background', 'shell_task_kill', 'shell_task_list',
- 'shell_task_status', 'video_generate',
+ 'file_write', 'image_generate', 'pr_resume',
+ 'run_workflow', 'screenshot', 'shell_execute',
+ 'video_generate',
])
})
})
@@ -202,8 +175,7 @@ describe('getToolPermission', () => {
it('returns "auto" for auto-permission tools', () => {
expect(getToolPermission('web_search')).toBe('auto')
expect(getToolPermission('web_fetch')).toBe('auto')
- expect(getToolPermission('process_list')).toBe('auto')
- expect(getToolPermission('system_info')).toBe('auto')
+ expect(getToolPermission('todo_write')).toBe('auto')
})
it('returns "confirm" for confirm-permission tools', () => {
diff --git a/src/api/__tests__/tool-schema-shape.test.ts b/src/api/__tests__/tool-schema-shape.test.ts
index 1fe9c940..4ef84fdf 100644
--- a/src/api/__tests__/tool-schema-shape.test.ts
+++ b/src/api/__tests__/tool-schema-shape.test.ts
@@ -58,7 +58,8 @@ const typesOf = (p: JSONSchemaProp): string[] => (Array.isArray(p.type) ? p.type
describe('the registry parsed, so the rest of this file means something', () => {
it('has the tools we expect to audit', () => {
- expect(TOOLS.length).toBeGreaterThan(25)
+ // 15 since the 2.6.6 merge folded the typed shell wrappers away.
+ expect(TOOLS.length).toBeGreaterThan(12)
expect(TOOLS.map((t) => t.name)).toContain('todo_write')
})
})
diff --git a/src/api/agent-context.ts b/src/api/agent-context.ts
index 96ff91ad..9fb61363 100644
--- a/src/api/agent-context.ts
+++ b/src/api/agent-context.ts
@@ -56,10 +56,11 @@ interface AgentCtxState {
/** Chat-tools artifact mode: when true, file_write captures instead of
* writing to disk, so plain chat shows files inline (ChatGPT-style). */
artifactMode: boolean
+ readOnlyShellTurn: boolean
artifacts: CapturedArtifact[]
}
const _g = globalThis as typeof globalThis & { __LU_AGENT_CTX?: AgentCtxState }
-const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, conversationId: null, workspace: null, model: null, artifactMode: false, artifacts: [] })
+const ctx: AgentCtxState = _g.__LU_AGENT_CTX ?? (_g.__LU_AGENT_CTX = { chatId: null, conversationId: null, workspace: null, model: null, artifactMode: false, readOnlyShellTurn: false, artifacts: [] })
/**
* The text model driving the current agent loop. Pinned by useAgentChat right
@@ -111,9 +112,26 @@ export function clearActiveChatId(): void {
ctx.workspace = null
ctx.model = null
ctx.artifactMode = false
+ ctx.readOnlyShellTurn = false
ctx.artifacts = []
}
+// ── Read-only turn (2.6.6 tool merge, plan E4 point 1) ─────────
+//
+// /review and Code-Review Mode used to strip the mutating tools BY NAME and
+// keep the typed inspectors (git_status, git_diff, …). Those names are gone;
+// the one terminal stays in the catalog and this flag makes its EXECUTOR the
+// gate: only commands the conservative read-only classifier accepts run while
+// it is set. Set at run start by useCodex, cleared in its finally.
+
+export function setReadOnlyShellTurn(on: boolean): void {
+ ctx.readOnlyShellTurn = !!on
+}
+
+export function isReadOnlyShellTurn(): boolean {
+ return ctx.readOnlyShellTurn
+}
+
// ── Chat-tools artifact mode (David 2026-06-12) ────────────────
//
// In PLAIN chat, "file writes" must behave like ChatGPT: the content is shown
diff --git a/src/api/agents/__tests__/error-hints.test.ts b/src/api/agents/__tests__/error-hints.test.ts
index f95c08cb..cd118743 100644
--- a/src/api/agents/__tests__/error-hints.test.ts
+++ b/src/api/agents/__tests__/error-hints.test.ts
@@ -21,9 +21,6 @@ describe('error-hints — explainError', () => {
['file_search', 'invalid regex: unmatched parenthesis', /regex|escape/i],
['shell_execute', "'foo' is not recognized as an internal or external command", /installed|PATH/i],
['shell_execute', 'Command timed out after 120s', /break|timeout/i],
- ['code_execute', 'SyntaxError: invalid syntax', /syntax|indent/i],
- ['code_execute', 'ModuleNotFoundError: No module named numpy', /stdlib|pip install/i],
- ['code_execute', "NameError: name 'x' is not defined", /persist|redefine/i],
['web_fetch', 'refused: private IP 192.168.1.1', /public|https/i],
['web_fetch', 'Error 404: page not found', /web_search/i],
['web_fetch', 'Error 403: forbidden', /different source/i],
@@ -55,10 +52,10 @@ describe('error-hints — explainError', () => {
it('every built-in tool has at least one hint OR an explicit empty list (Phase 3 coverage)', () => {
const expected = [
'file_read', 'file_write', 'file_list', 'file_search',
- 'shell_execute', 'code_execute',
+ 'shell_execute',
'web_search', 'web_fetch',
- 'system_info', 'process_list', 'screenshot',
- 'image_generate', 'run_workflow', 'get_current_time',
+ 'screenshot',
+ 'image_generate', 'run_workflow',
]
for (const name of expected) {
expect(Object.hasOwn(__internal.TOOL_HINTS, name), `missing entry for ${name}`).toBe(true)
diff --git a/src/api/agents/error-hints.ts b/src/api/agents/error-hints.ts
index df9ba582..1eaee355 100644
--- a/src/api/agents/error-hints.ts
+++ b/src/api/agents/error-hints.ts
@@ -56,12 +56,6 @@ const TOOL_HINTS: Record<string, HintRule[]> = {
{ pattern: /exit code ([1-9]|1\d|2\d)/i, hint: 'Command exited non-zero. Read stderr for the root cause before retrying.' },
{ pattern: /permission denied|EACCES/i, hint: 'Permission denied. The command or its target requires elevated privileges.' },
],
- code_execute: [
- { pattern: /SyntaxError/, hint: 'Python syntax error. Re-check indentation and parentheses before retrying.' },
- { pattern: /ModuleNotFoundError|No module named/i, hint: 'Module not in the sandbox Python. Use only stdlib, or shell_execute `pip install <name>` first.' },
- { pattern: /NameError/i, hint: 'NameError, variable or function not defined. State does not persist between code_execute calls; redefine everything.' },
- { pattern: /timed out/i, hint: 'Execution timed out. Shorten the code or break into chunks.' },
- ],
web_fetch: [
{ pattern: /refused|private IP|localhost|loopback/i, hint: 'Target URL was refused for safety. Use a public https:// URL only.' },
{ pattern: /404|not found/i, hint: 'Page 404. Search for the canonical URL via web_search first.' },
@@ -88,12 +82,9 @@ const TOOL_HINTS: Record<string, HintRule[]> = {
{ pattern: /not found/i, hint: 'Workflow name unknown. The error already lists available names, pick one.' },
{ pattern: /depth|nesting/i, hint: 'Workflow nesting limit reached. Do not call run_workflow from inside another workflow.' },
],
- system_info: [],
- process_list: [],
screenshot: [
{ pattern: /permission|denied/i, hint: 'Screen capture denied. Tell the user to grant screen permission.' },
],
- get_current_time: [],
}
/**
diff --git a/src/api/agents/in-turn-cache.ts b/src/api/agents/in-turn-cache.ts
index 1c9967aa..11c9f6b0 100644
--- a/src/api/agents/in-turn-cache.ts
+++ b/src/api/agents/in-turn-cache.ts
@@ -6,8 +6,7 @@
* Scope is deliberately narrow: one agent TURN (from sendAgentMessage or
* sendInstruction start until the ReAct loop exits). We do NOT cache across
* turns because many tools return time-sensitive data (web_search results,
- * process_list, get_current_time, file_read on a file that may have just
- * been overwritten). Scoping to a single turn keeps the semantics trivial:
+ * file_read on a file that may have just been overwritten). Scoping to a single turn keeps the semantics trivial:
* everything inside one user prompt sees a consistent view of each tool's
* output; the next user prompt starts fresh.
*
@@ -45,6 +44,8 @@ const NON_CACHEABLE_TOOLS = new Set<string>([
'file_write',
'file_edit',
'shell_execute',
+ // Retired names (2.6.6 merge) still execute via the registry redirect and
+ // must keep exactly these semantics under their old names.
'shell_execute_background',
'code_execute',
'run_tests',
@@ -68,6 +69,7 @@ const WORKSPACE_MUTATING_TOOLS = new Set<string>([
'file_write',
'file_edit',
'shell_execute',
+ // Redirect-era names, same reasoning as above.
'shell_execute_background',
'code_execute',
'run_tests',
@@ -77,10 +79,11 @@ const WORKSPACE_MUTATING_TOOLS = new Set<string>([
const READ_TOOLS = new Set<string>(['file_read', 'file_list'])
function isNonCacheableTool(name: string): boolean {
+ // git_* covers the redirected typed git tools, reads and writes alike.
return NON_CACHEABLE_TOOLS.has(name) || name.startsWith('git_')
}
-/** A workspace-mutating call — the disk-touching subset, plus git_*. */
+/** A workspace-mutating call, the disk-touching subset plus redirected git_*. */
function isMutatingTool(name: string): boolean {
return WORKSPACE_MUTATING_TOOLS.has(name) || name.startsWith('git_')
}
diff --git a/src/api/agents/side-effect-key.ts b/src/api/agents/side-effect-key.ts
index ab4b2377..b82f1440 100644
--- a/src/api/agents/side-effect-key.ts
+++ b/src/api/agents/side-effect-key.ts
@@ -7,18 +7,16 @@
* sideEffectKey and runs one group in parallel but within-group in
* sequence.
*
- * - Pure reads (file_read, web_fetch, web_search, system_info,
- * process_list, file_list, file_search, get_current_time,
- * screenshot) → no key (fully parallel-safe).
+ * - Pure reads (file_read, web_fetch, web_search, file_list,
+ * file_search, screenshot) → no key (fully parallel-safe).
*
* - file_write → key is `file_write:<normalized-path>`. Two writes to
* the SAME path serialize; writes to DIFFERENT paths remain parallel.
*
- * - shell_execute, code_execute, shell_execute_background, run_tests,
- * git_commit, git_push → key 'exec'. We do not know what a shell command
- * touches, and concurrent repo writes race on `.git/index.lock`, so batch
- * all exec-class + repo-mutating calls onto a single queue. Read-only git_*
- * (git_status/git_log/git_diff) stay parallel.
+ * - shell_execute → key 'exec'. We do not know what a shell command
+ * touches, and concurrent repo writes race on `.git/index.lock`, so all
+ * shell calls share a single queue. (Since the 2.6.6 merge the shell IS
+ * git, tests and background starts, so this one case covers them all.)
*
* - image_generate, video_generate, run_workflow → key 'comfyui'. ComfyUI
* serializes internally and workflows do heavy I/O; running in parallel
@@ -35,17 +33,17 @@ export function deriveSideEffectKey(
return path ? `file_write:${path}` : 'file_write:unknown'
}
case 'shell_execute':
+ // Retired names (2.6.6 merge) still execute via the registry redirect,
+ // so a model batching git_commit + git_push under the old names must
+ // still land on the same queue.
case 'code_execute':
case 'shell_execute_background':
case 'run_tests':
case 'git_commit':
case 'git_push':
- // Everything that shells out or mutates the repo shares ONE serial queue.
- // We can't know what a command touches, and two concurrent git writes
- // (e.g. git_commit + a `git push`, or two git_commits) race on
- // `.git/index.lock` and one fails. run_tests and shell_execute_background
- // also shell out, so they must not run against a repo mid-commit. Only the
- // read-only git_* tools (git_status/git_log/git_diff) stay parallel.
+ // Everything that shells out shares ONE serial queue. We can't know
+ // what a command touches, and two concurrent git writes race on
+ // `.git/index.lock` and one fails.
return 'exec'
case 'image_generate':
case 'video_generate':
@@ -55,8 +53,7 @@ export function deriveSideEffectKey(
// both queued on the hand-off and a back-to-back gen could survive Stop.
return 'comfyui'
default:
- // file_read, file_list, file_search, web_search, web_fetch,
- // system_info, process_list, get_current_time, screenshot.
+ // file_read, file_list, file_search, web_search, web_fetch, screenshot.
return undefined
}
}
diff --git a/src/api/hermes-tool-calling.ts b/src/api/hermes-tool-calling.ts
index 3edee8c3..13edf300 100644
--- a/src/api/hermes-tool-calling.ts
+++ b/src/api/hermes-tool-calling.ts
@@ -60,10 +60,9 @@ export function buildHermesToolPrompt(tools: (AgentToolDef | ToolLike)[]): strin
// Everything below the <tools> block is about HOW to use what is in it, so
// each note only appears when the tool it talks about is actually offered.
- // The old prompt closed with a fixed "Other tools: file_read, file_write,
- // code_execute, image_generate" line that had not been updated in five
- // releases: it named four of thirty tools and contradicted the block right
- // above it.
+ // The old prompt closed with a fixed "Other tools: ..." line naming four
+ // hardcoded tools, and it had not been updated in five releases: it
+ // contradicted the block right above it.
const has = (name: string) => tools.some((t) => t.name === name)
const notes: string[] = []
if (has('todo_write')) {
diff --git a/src/api/mcp/__tests__/tool-merge-redirect.test.ts b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
new file mode 100644
index 00000000..06f9b917
--- /dev/null
+++ b/src/api/mcp/__tests__/tool-merge-redirect.test.ts
@@ -0,0 +1,130 @@
+/**
+ * 2.6.6 tool merge (plan E4/E5): the sixteen typed wrappers are gone from the
+ * catalog, but their NAMES must keep working. A restored session, or a model
+ * that knows git_status from its own training, calls the old name; burning
+ * that step on "Unknown tool" would be a regression users feel immediately.
+ *
+ * And the read-only gate moved with them: it used to strip tools by NAME,
+ * now shell_execute stays offered on /review turns and the executor refuses
+ * by COMMAND. These tests pin both halves at the executor, where they run.
+ *
+ * Run: npx vitest run src/api/mcp/__tests__/tool-merge-redirect.test.ts
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const backendCalls: { cmd: string; body: any }[] = []
+
+vi.mock('../../backend', () => ({
+ backendCall: vi.fn(async (cmd: string, body: any) => {
+ backendCalls.push({ cmd, body })
+ if (cmd === 'shell_execute') {
+ return { stdout: '# branch.head master\n', stderr: '', exitCode: 0 }
+ }
+ return { ok: true }
+ }),
+ fetchExternal: vi.fn(async () => ({ ok: true, status: 200, text: async () => '' })),
+}))
+// The delegate/workflow imports drag in the provider stack, which the
+// redirect under test never touches. Stub them to keep the module loadable.
+vi.mock('../../agents/sub-agent', () => ({
+ DELEGATE_TASK_TOOL_DEF: { name: 'delegate_task', description: '', category: 'system', inputSchema: {} },
+ buildDelegateExecutor: () => async () => 'stub',
+}))
+vi.mock('../../../lib/workflow-engine', () => ({ WorkflowEngine: class {} }))
+
+import { runRetiredTool, RETIRED_TOOL_NAMES, registerBuiltinTools } from '../builtin-tools'
+import { ToolRegistry } from '../tool-registry'
+import { setReadOnlyShellTurn } from '../../agent-context'
+
+beforeEach(() => {
+ backendCalls.length = 0
+ setReadOnlyShellTurn(false)
+})
+afterEach(() => setReadOnlyShellTurn(false))
+
+describe('retired names still execute through the redirect', () => {
+ it('git_status runs the real shell command and carries the retirement note', async () => {
+ const result = await runRetiredTool('git_status', {})
+ expect(result).not.toBeNull()
+ expect(backendCalls.some((c) => c.cmd === 'shell_execute' && String(c.body.command).startsWith('git status'))).toBe(true)
+ expect(result).toContain('git_status is retired')
+ expect(result).toContain('shell_execute')
+ })
+
+ it('a name that was never ours returns null, so the registry can say Unknown tool', async () => {
+ expect(await runRetiredTool('made_up_tool', {})).toBeNull()
+ })
+
+ it('all sixteen retired names resolve', () => {
+ expect(RETIRED_TOOL_NAMES.size).toBe(16)
+ for (const name of ['git_status', 'git_log', 'git_diff', 'git_commit', 'git_push', 'run_tests',
+ 'gh_pr_create', 'project_init', 'code_execute', 'system_info', 'process_list',
+ 'get_current_time', 'shell_execute_background', 'shell_task_status', 'shell_task_kill', 'shell_task_list']) {
+ expect(RETIRED_TOOL_NAMES.has(name), name).toBe(true)
+ }
+ })
+})
+
+describe('the read-only gate lives at the executor now', () => {
+ it('a mutating retired name is refused on a read-only turn', async () => {
+ setReadOnlyShellTurn(true)
+ const result = await runRetiredTool('git_commit', { message: 'x' })
+ expect(result).toContain('Refused')
+ expect(result).toContain('read-only')
+ expect(backendCalls).toHaveLength(0)
+ })
+
+ it('a read-only retired name still runs on a read-only turn', async () => {
+ setReadOnlyShellTurn(true)
+ const result = await runRetiredTool('git_status', {})
+ expect(result).not.toContain('Refused')
+ expect(backendCalls.some((c) => c.cmd === 'shell_execute')).toBe(true)
+ })
+
+ it('negative control: the same commit runs when the turn is not read-only', async () => {
+ const result = await runRetiredTool('git_commit', { message: 'x' })
+ expect(result).not.toContain('Refused: this turn is read-only')
+ })
+})
+
+describe('shell_execute refuses by COMMAND on a read-only turn (E7 priority)', () => {
+ const registry = new ToolRegistry()
+ registerBuiltinTools(registry)
+ const shell = (args: Record<string, any>) => registry.execute('shell_execute', args)
+
+ it('the reviewer can still look at the diff', async () => {
+ setReadOnlyShellTurn(true)
+ const result = await shell({ command: 'git diff --stat' })
+ expect(result).not.toContain('Refused')
+ expect(backendCalls.some((c) => c.cmd === 'shell_execute' && c.body.command === 'git diff --stat')).toBe(true)
+ })
+
+ it('git commit is refused', async () => {
+ setReadOnlyShellTurn(true)
+ const result = await shell({ command: 'git commit -m x' })
+ expect(result).toContain('Refused')
+ expect(backendCalls).toHaveLength(0)
+ })
+
+ it('chaining a read prefix onto a write does not slip through', async () => {
+ setReadOnlyShellTurn(true)
+ const result = await shell({ command: 'git log; rm -rf x' })
+ expect(result).toContain('Refused')
+ expect(backendCalls).toHaveLength(0)
+ })
+
+ it('background starts and task kills are refused too, status stays allowed', async () => {
+ setReadOnlyShellTurn(true)
+ expect(await shell({ command: 'git log', background: true })).toContain('Refused')
+ expect(await shell({ task: 'kill', task_id: 't1' })).toContain('Refused')
+ const status = await shell({ task: 'status', task_id: 't1' })
+ expect(status).not.toContain('Refused')
+ })
+
+ it('negative control: the same commit runs on a normal turn', async () => {
+ setReadOnlyShellTurn(false)
+ const result = await shell({ command: 'git commit -m x' })
+ expect(result).not.toContain('Refused')
+ expect(backendCalls.some((c) => c.body?.command === 'git commit -m x')).toBe(true)
+ })
+})
diff --git a/src/api/mcp/__tests__/tool-registry-retry.test.ts b/src/api/mcp/__tests__/tool-registry-retry.test.ts
index 13b5b0cc..94a53937 100644
--- a/src/api/mcp/__tests__/tool-registry-retry.test.ts
+++ b/src/api/mcp/__tests__/tool-registry-retry.test.ts
@@ -41,8 +41,8 @@ describe('ToolRegistry.execute — retry discipline (audit B2)', () => {
it('never retries a mutating tool, even on a transient throw', async () => {
const registry = new ToolRegistry()
const runs = { count: 0 }
- registry.registerBuiltin(mkTool('git_commit'), throwingExecutor('fetch failed', runs))
- const result = await registry.execute('git_commit', {})
+ registry.registerBuiltin(mkTool('shell_execute'), throwingExecutor('fetch failed', runs))
+ const result = await registry.execute('shell_execute', {})
expect(runs.count).toBe(1)
expect(result).toMatch(/^Error:/)
})
diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.ts
index 95386ca1..aeee03f6 100644
--- a/src/api/mcp/builtin-tools.ts
+++ b/src/api/mcp/builtin-tools.ts
@@ -3,7 +3,7 @@
import type { MCPToolDefinition } from './types'
import type { ToolRegistry } from './tool-registry'
import { backendCall, fetchExternal } from '../backend'
-import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact } from '../agent-context'
+import { getActiveChatId, getActiveConversationId, getActiveWorkspace, isChatArtifactMode, captureChatArtifact, isReadOnlyShellTurn } from '../agent-context'
import { useAgentWorkflowStore } from '../../stores/agentWorkflowStore'
import { WorkflowEngine } from '../../lib/workflow-engine'
import type { StepResult } from '../../types/agent-workflows'
@@ -85,7 +85,7 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
'Search the web via the configured provider (Brave, Tavily, or auto). Returns a ranked list of {title, url, snippet}. '
+ 'PREFER web_fetch on promising URLs for full content — snippets are teasers, not answers. '
+ 'DO NOT call more than 3x per turn with similar queries; refine the query instead of re-searching. '
- + 'For current date/time, use get_current_time — do NOT web_search for it.',
+ + 'For the current date/time, trust the date line in the system prompt; do NOT web_search for it.',
inputSchema: {
type: 'object',
properties: {
@@ -222,209 +222,25 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
{
name: 'shell_execute',
description:
- 'Run a shell command. PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. '
- + 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`, get_current_time over `date`. '
- + 'Use shell_execute for git, npm, cargo, docker, package managers, or platform utilities without a dedicated tool. '
- + 'This is also how you open things on the desktop: a folder, a file, or an application. The system prompt states which OS this is and gives the exact command. '
- + 'NEVER use to permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). '
- + 'Default timeout 120 s; set higher only for known long-running builds.',
+ 'THE terminal. Run a shell command: PowerShell on Windows, bash on Unix. Returns stdout, stderr, exit code. '
+ + 'Everything runs here: git, tests, package managers, gh, python, platform utilities. This is also how you open things on the desktop: files, folders, apps (the system prompt states the OS and the exact open command). '
+ + 'Useful forms: `git status --porcelain=2 --branch` and a recognised test run (`npm test`, `npx vitest run`, `cargo test`, `pytest`) return a parsed summary; `git log --oneline -n 20`; `git diff`; `git add -A && git commit -m "msg"`; `git push`; `gh pr create --title "t" --body "b"`. '
+ + 'Feed a script via `stdin` instead of quoting it: set command to `python3 -` or `bash -s` and put the source in `stdin` (fresh process each call, no REPL state). '
+ + 'Long-running work: set `background: true` to get a task id back immediately; follow it by calling again with `task: "status"` and `task_id` (or `task: "list"` / `task: "kill"`). '
+ + 'PREFER dedicated tools where available: file_read over `cat`, file_list over `ls`/`dir`, file_search over `grep`. '
+ + '`git commit --no-verify` is refused. NEVER permanently delete without confirmation (rm -rf, Remove-Item -Recurse, git reset --hard). '
+ + 'Default timeout 120 s (recognised test runs get 300 s); set higher only for known long builds.',
inputSchema: {
type: 'object',
properties: {
- command: { type: 'string', description: 'The full command to execute' },
+ command: { type: 'string', description: 'The full command to execute. Omit only for task actions.' },
cwd: { type: 'string', description: 'Working directory (optional, absolute preferred)' },
timeout: { type: 'number', description: 'Timeout in milliseconds (default: 120000)' },
shell: { type: 'string', description: 'Override shell: "powershell" | "cmd" | "bash" (default: auto)' },
- },
- required: ['command'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'code_execute',
- description:
- 'Execute Python code in a fresh subprocess. Returns stdout, stderr, exit code. '
- + 'Use for math, data transforms, JSON/CSV parsing, one-off scripts. '
- + 'NOT a REPL — state does not persist between calls; import everything you need each time. '
- + 'For system commands and shell utilities, PREFER shell_execute. '
- + 'Default timeout 30 s.',
- inputSchema: {
- type: 'object',
- properties: {
- code: { type: 'string', description: 'The Python source to execute (UTF-8)' },
- language: { type: 'string', description: 'Programming language: "python" or "shell"', enum: ['python', 'shell'] },
- },
- required: ['code'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'shell_execute_background',
- description:
- 'Spawn a shell command on the bridge as a LONG-RUNNING BACKGROUND task. '
- + 'Returns an opaque task `id` immediately — the user can close the browser, '
- + 'come back later, and use `shell_task_status` to read the tail of stdout/stderr. '
- + 'USE for batch refactors, large `pnpm install`, `cargo build`, dataset transforms — '
- + 'anything that would time out a normal `shell_execute` call.',
- inputSchema: {
- type: 'object',
- properties: {
- command: { type: 'string', description: 'Shell command to run.' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: ['command'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'shell_task_status',
- description:
- 'Read the status of a background task started via `shell_execute_background`. '
- + 'Returns running/finished, exit code, cancelled flag, and the last ~64 KiB of '
- + 'output. Poll periodically while a task is running.',
- inputSchema: {
- type: 'object',
- properties: {
- id: { type: 'string', description: 'Task id returned by shell_execute_background.' },
- },
- required: ['id'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'shell_task_kill',
- description:
- 'Cancel a running background task. No-op if the task already finished.',
- inputSchema: {
- type: 'object',
- properties: {
- id: { type: 'string', description: 'Task id to cancel.' },
- },
- required: ['id'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'shell_task_list',
- description:
- 'List all background tasks the bridge knows about (newest first). Use for '
- + '"what is still running?" queries.',
- inputSchema: { type: 'object', properties: {}, required: [] },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'git_status',
- description:
- 'Run `git status --porcelain=2 --branch` and return a STRUCTURED summary: '
- + 'branch, ahead/behind counts, per-file status codes, clean-tree flag. '
- + 'PREFER over shell_execute for "what changed" queries — output is greppable.',
- inputSchema: {
- type: 'object',
- properties: {
- cwd: { type: 'string', description: 'Working directory (defaults to chat workspace).' },
- },
- required: [],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'git_commit',
- description:
- 'Stage files (or all tracked changes) and create a commit with `message`. '
- + 'When `allTracked` is true → `git add -A` then `git commit`; '
- + 'when `files` is given → only those paths are staged; '
- + 'otherwise commits whatever is already staged. '
- + 'NEVER passes `--no-verify` — fix hook failures, don\'t skip them. '
- + 'Output includes the new commit SHA on success.',
- inputSchema: {
- type: 'object',
- properties: {
- message: { type: 'string', description: 'Commit message (multi-line OK).' },
- allTracked: { type: 'boolean', description: 'Stage every tracked change first.' },
- files: { type: 'array', items: { type: 'string' }, description: 'Specific files to stage.' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: ['message'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'git_push',
- description:
- 'Run `git push`. With no args pushes the current branch to its tracked upstream. '
- + 'WARN: not for `main`/`master` without explicit user instruction — '
- + 'check git_status first.',
- inputSchema: {
- type: 'object',
- properties: {
- remote: { type: 'string', description: 'Remote name (default: origin).' },
- branch: { type: 'string', description: 'Branch to push (default: current).' },
- setUpstream: { type: 'boolean', description: 'Pass `-u` for first-time push.' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: [],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'git_log',
- description:
- 'Recent commits in one-line format. Returns parsed [{sha, subject}]. '
- + 'PREFER over shell_execute when answering "what changed recently" — output is greppable.',
- inputSchema: {
- type: 'object',
- properties: {
- limit: { type: 'number', description: 'Max commits to return (default 20).' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: [],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'git_diff',
- description:
- 'Run `git diff` between HEAD (or a ref) and the working tree. '
- + 'Returns the raw unified diff — pair with file_search if you only need a path. '
- + 'For staged changes pass `staged: true`.',
- inputSchema: {
- type: 'object',
- properties: {
- ref: { type: 'string', description: 'Base ref (e.g. main, HEAD~3). Defaults to HEAD.' },
- path: { type: 'string', description: 'Limit to a path.' },
- staged: { type: 'boolean', description: 'Diff the index instead of the working tree.' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: [],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'project_init',
- description:
- 'Scaffold a new project from a known stack recipe. With no `recipe` arg, lists '
- + 'available stacks (next-postgres, next-supabase, next-stripe, rust-axum, vite-react). '
- + 'With a `recipe` arg, returns a markdown plan of ordered shell commands the model '
- + 'can then execute via shell_execute. Workspace-sandboxed IDEs can\'t do this — LU '
- + 'can because the bridge has real shell + filesystem access.',
- inputSchema: {
- type: 'object',
- properties: {
- recipe: {
- type: 'string',
- description: 'Stack id (e.g. "next-postgres"). Omit to list available recipes.',
- },
+ stdin: { type: 'string', description: 'Text piped to the command\'s stdin, e.g. a Python script for `python3 -`.' },
+ background: { type: 'boolean', description: 'Run detached; returns a task id immediately instead of waiting.' },
+ task: { type: 'string', enum: ['status', 'list', 'kill'], description: 'Background-task action instead of running a command.' },
+ task_id: { type: 'string', description: 'Task id for task "status" or "kill".' },
},
required: [],
},
@@ -449,80 +265,8 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
category: 'terminal',
source: 'builtin',
},
- {
- name: 'gh_pr_create',
- description:
- 'Open a new GitHub pull request via the `gh` CLI. Requires the user to be authed against GitHub locally. '
- + 'Pushes the current branch first if it has no upstream. Returns the PR URL on success.',
- inputSchema: {
- type: 'object',
- properties: {
- title: { type: 'string', description: 'PR title (under 70 chars).' },
- body: { type: 'string', description: 'PR description in markdown.' },
- base: { type: 'string', description: 'Base branch (default: repo default).' },
- cwd: { type: 'string', description: 'Working directory.' },
- },
- required: ['title'],
- },
- category: 'terminal',
- source: 'builtin',
- },
- {
- name: 'run_tests',
- description:
- 'Run the project test suite and return a STRUCTURED summary: passed/failed counts, '
- + 'failing test names, last 40 output lines. AUTO-DETECTS the runner '
- + '(vitest, jest, cargo, pytest) from files in the working directory unless `runner` is given. '
- + 'PREFER this over shell_execute when the user says "run the tests", "make this green", '
- + 'or you are iterating on a failing assertion — the output is greppable instead of an opaque dump. '
- + 'Default timeout 300 s. Pass `command` to override the auto-detected command (e.g. a single-file scope).',
- inputSchema: {
- type: 'object',
- properties: {
- runner: {
- type: 'string',
- description: 'Force a runner: "vitest" | "jest" | "cargo" | "pytest". Auto if omitted.',
- enum: ['vitest', 'jest', 'cargo', 'pytest'],
- },
- command: {
- type: 'string',
- description: 'Override the test command entirely. Use for single-file runs (`pnpm exec vitest run path/to/x.test.ts`).',
- },
- cwd: {
- type: 'string',
- description: 'Override working directory. Defaults to the chat workspace.',
- },
- timeout: {
- type: 'number',
- description: 'Timeout in ms (default 300_000 — tests can take a while).',
- },
- },
- required: [],
- },
- category: 'terminal',
- source: 'builtin',
- },
// System
- {
- name: 'system_info',
- description:
- 'Return desktop system info: OS, architecture, hostname, username, total RAM, CPU count. Zero arguments. '
- + 'Call once when output needs to be tailored to the user\'s platform; do not call repeatedly in a loop.',
- inputSchema: { type: 'object', properties: {}, required: [] },
- category: 'system',
- source: 'builtin',
- },
- {
- name: 'process_list',
- description:
- 'List the top 30 running processes sorted by memory: {name, pid, memory, cpu%}. Zero arguments. '
- + 'Use for task-manager-style queries ("is Chrome running?", "which process is eating RAM?"). '
- + 'There is NO process_kill tool — to kill a process use shell_execute with taskkill (Windows) or kill (Unix).',
- inputSchema: { type: 'object', properties: {}, required: [] },
- category: 'system',
- source: 'builtin',
- },
// Desktop
{
@@ -662,20 +406,6 @@ const BUILTIN_TOOLS: MCPToolDefinition[] = [
DELEGATE_TASK_TOOL_DEF,
// Local clock — so the agent never googles "what day is it".
- {
- name: 'get_current_time',
- description:
- "Return the user's current local date, time, and timezone. Zero arguments. "
- + "USE FIRST for any 'what day / time / date is it' question — do NOT web_search or shell_execute `date`. "
- + "The Rust backend probes the OS timezone on every call, so this is always authoritative.",
- inputSchema: {
- type: 'object',
- properties: {},
- required: [],
- },
- category: 'system',
- source: 'builtin',
- },
]
// ── Executors ────────────────────────────────────────────────────
@@ -891,18 +621,81 @@ async function executeFileSearch(args: Record<string, any>): Promise<string> {
}
async function executeShellExecute(args: Record<string, any>): Promise<string> {
+ // Background-task actions: the three shell_task_* tools folded in (2.6.6).
+ const task = typeof args.task === 'string' ? args.task : ''
+ if (task === 'list') return executeShellTaskList()
+ if (task === 'status' || task === 'kill') {
+ if (task === 'kill' && isReadOnlyShellTurn()) {
+ return 'Refused: this turn is read-only (/review or Code-Review Mode); killing a task changes state.'
+ }
+ const id = args.task_id ?? args.id
+ if (!id) return `shell_execute: task "${task}" needs a task_id.`
+ return task === 'status' ? executeShellTaskStatus({ id }) : executeShellTaskKill({ id })
+ }
+
+ const command = typeof args.command === 'string' ? args.command.trim() : ''
+ if (!command) return 'shell_execute: `command` is required (or pass task: "status" | "list" | "kill").'
+
+ const { rejectShellCommand, commandTimeoutMs, commandKind, isReadOnlyCommand } = await import(
+ '../../lib/shell-command-classify'
+ )
+ // Read-only turn (/review …): the classifier is the gate now that the typed
+ // read-only inspectors are gone. Conservative on purpose: chained commands
+ // are refused outright, a read-only mode that can be talked around is none.
+ if (isReadOnlyShellTurn() && (args.background || !isReadOnlyCommand(command))) {
+ return 'Refused: this turn is read-only (/review or Code-Review Mode). Only inspection commands run here: git status/log/diff/show/blame, ls, cat, pwd. One command, no chaining.'
+ }
+
+ if (args.background) return executeShellExecuteBg({ command, cwd: args.cwd })
+
+ // The one refusal that stays hard after the merge: --no-verify on a commit.
+ const refusal = rejectShellCommand(command)
+ if (refusal) return refusal
+
+ // An explicit timeout wins; otherwise a recognised test run keeps the old
+ // run_tests budget (300 s) instead of the shell default.
+ const timeout = args.timeout || commandTimeoutMs(command, 120000)
const data = await backendCall('shell_execute', {
- command: args.command,
+ command,
args: args.args || null,
cwd: args.cwd || null,
- timeout: args.timeout || 120000,
+ timeout,
shell: args.shell || null,
+ stdin: typeof args.stdin === 'string' && args.stdin ? args.stdin : null,
...chatCtx(),
})
const output = data.stdout || ''
const err = data.stderr || ''
if (data.timedOut) return `Timed out.\n${err}`
+
+ const kind = commandKind(command)
+ // Parsed summaries (plan E4 point 4): they used to hang on the typed tool
+ // names, small models rely on them, so they hang on the command now.
+ if (kind === 'test-run') {
+ const { parseForRunner, renderResult } = await import('../agents/test-runner')
+ const runner = /vitest/.test(command)
+ ? 'vitest'
+ : /jest/.test(command)
+ ? 'jest'
+ : /cargo/.test(command)
+ ? 'cargo'
+ : /pytest/.test(command)
+ ? 'pytest'
+ : 'unknown'
+ const combined = `${output}\n${err}`.trim()
+ const tail = combined.length > 4000 ? `…${combined.slice(-4000)}` : combined
+ return `${renderResult(parseForRunner(runner, combined))}\n---\n${tail}`
+ }
if (data.exitCode && data.exitCode !== 0) return `Error (${data.exitCode}):\n${err || output}`
+ if (kind === 'git-status' && /--porcelain=2/.test(command)) {
+ const { parseGitStatus, renderGitStatus } = await import('../agents/git-tools')
+ return renderGitStatus(parseGitStatus(output))
+ }
+ if (kind === 'git-commit') {
+ const combined = `${output}\n${err}`.trim()
+ const m = combined.match(/\[(\S+)\s+([0-9a-f]{7,40})\]/)
+ return m ? `Committed on ${m[1]} as ${m[2]}.\n${combined}` : combined || 'Done.'
+ }
return output || (err ? `stderr: ${err}` : 'Done.')
}
@@ -1543,27 +1336,11 @@ const EXECUTOR_MAP: Record<string, (args: Record<string, any>) => Promise<string
file_list: executeFileList,
file_search: executeFileSearch,
shell_execute: executeShellExecute,
- code_execute: executeCodeExecute,
- run_tests: executeRunTests,
- shell_execute_background: executeShellExecuteBg,
- shell_task_status: executeShellTaskStatus,
- shell_task_kill: executeShellTaskKill,
- shell_task_list: executeShellTaskList,
- git_status: executeGitStatus,
- git_commit: executeGitCommit,
- git_push: executeGitPush,
- git_log: executeGitLog,
- git_diff: executeGitDiff,
- gh_pr_create: executeGhPrCreate,
pr_resume: executePrResume,
- project_init: executeProjectInit,
- system_info: executeSystemInfo,
- process_list: executeProcessList,
screenshot: executeScreenshot,
image_generate: executeImageGenerate,
video_generate: executeVideoGenerate,
run_workflow: executeRunWorkflow,
- get_current_time: executeGetCurrentTime,
delegate_task: buildDelegateExecutor(),
}
@@ -1575,3 +1352,79 @@ export function registerBuiltinTools(registry: ToolRegistry) {
}
}
}
+
+// ── Retired tools (2.6.6 merge, plan E5) ────────────────────────
+//
+// Sixteen typed wrappers left the catalog: their schemas cost ~109 tokens
+// each per step while every executor ended in runShell anyway. But a running
+// chat, a restored session and every model that saw the old names in its
+// context still CALLS them, and "Error: Unknown tool" burns that step. Same
+// cure as uselu's RETIRED_MODELS: the old call still runs (through the kept
+// executors), and the reply names the new way once.
+
+const RETIRED_HINT: Record<string, string> = {
+ git_status: 'shell_execute with command "git status --porcelain=2 --branch"',
+ git_log: 'shell_execute with command "git log --oneline -n 20"',
+ git_diff: 'shell_execute with command "git diff"',
+ git_commit: 'shell_execute with command "git add -A && git commit -m \\"msg\\""',
+ git_push: 'shell_execute with command "git push"',
+ run_tests: 'shell_execute with the project test command (npm test, npx vitest run, cargo test, pytest)',
+ gh_pr_create: 'shell_execute with command "gh pr create --title \\"t\\" --body \\"b\\""',
+ project_init: 'shell_execute with the scaffold commands directly',
+ code_execute: 'shell_execute with command "python3 -" and the source in stdin',
+ system_info: 'the system prompt (OS, shell, time are stated there); for hardware, shell_execute "uname -a" (Windows: Get-ComputerInfo)',
+ process_list: 'shell_execute with command "ps aux" (Windows: Get-Process)',
+ get_current_time: 'the system prompt, which states date and time at run start',
+ shell_execute_background: 'shell_execute with background: true',
+ shell_task_status: 'shell_execute with task: "status" and task_id',
+ shell_task_kill: 'shell_execute with task: "kill" and task_id',
+ shell_task_list: 'shell_execute with task: "list"',
+}
+
+const RETIRED_EXECUTORS: Record<string, (args: Record<string, any>) => Promise<string>> = {
+ git_status: executeGitStatus,
+ git_log: executeGitLog,
+ git_diff: executeGitDiff,
+ git_commit: executeGitCommit,
+ git_push: executeGitPush,
+ run_tests: executeRunTests,
+ gh_pr_create: executeGhPrCreate,
+ project_init: executeProjectInit,
+ code_execute: executeCodeExecute,
+ system_info: executeSystemInfo,
+ process_list: executeProcessList,
+ get_current_time: executeGetCurrentTime,
+ shell_execute_background: executeShellExecuteBg,
+ shell_task_status: executeShellTaskStatus,
+ shell_task_kill: executeShellTaskKill,
+ shell_task_list: executeShellTaskList,
+}
+
+const RETIRED_MUTATING = new Set([
+ 'git_commit', 'git_push', 'gh_pr_create', 'project_init', 'run_tests',
+ 'code_execute', 'shell_execute_background', 'shell_task_kill',
+])
+
+/** Names that still resolve through the redirect, for override migration. */
+export const RETIRED_TOOL_NAMES: ReadonlySet<string> = new Set(Object.keys(RETIRED_EXECUTORS))
+
+/**
+ * Run a retired tool under its old name, or return null when the name was
+ * never ours. The appended note is one line so the model learns the new way
+ * without the step being wasted.
+ */
+export async function runRetiredTool(
+ name: string,
+ args: Record<string, any>,
+): Promise<string | null> {
+ const run = RETIRED_EXECUTORS[name]
+ if (!run) return null
+ // The read-only gate lives on shell_execute's command classifier; a retired
+ // mutating name would walk straight past it via this redirect.
+ if (isReadOnlyShellTurn() && RETIRED_MUTATING.has(name)) {
+ return `Refused: this turn is read-only (/review or Code-Review Mode); ${name} changes state.`
+ }
+ const result = await run(args)
+ const hint = RETIRED_HINT[name]
+ return hint ? `${result}\n\n(Note: ${name} is retired, next time use ${hint}.)` : result
+}
diff --git a/src/api/mcp/tool-registry.ts b/src/api/mcp/tool-registry.ts
index ce05637b..392b0a6f 100644
--- a/src/api/mcp/tool-registry.ts
+++ b/src/api/mcp/tool-registry.ts
@@ -105,7 +105,15 @@ export class ToolRegistry {
async execute(name: string, args: Record<string, any>, maxRetries = 1): Promise<string> {
const entry = this.tools.get(name)
- if (!entry) return `Error: Unknown tool "${name}"`
+ if (!entry) {
+ // Retired names (2.6.6 tool merge) still run: a restored session or a
+ // model that knows git_status from its context must not burn the step
+ // on "Unknown tool". Dynamic import keeps the module graph acyclic.
+ const { runRetiredTool } = await import('./builtin-tools')
+ const redirected = await runRetiredTool(name, args)
+ if (redirected !== null) return redirected
+ return `Error: Unknown tool "${name}"`
+ }
// Audit B2: a retry re-RUNS the tool. For a side-effecting tool that is a
// second commit, a second push, a second shell command — never acceptable
diff --git a/src/components/chat/ToolCallBlock.tsx b/src/components/chat/ToolCallBlock.tsx
index 76240e92..66dcd5b3 100644
--- a/src/components/chat/ToolCallBlock.tsx
+++ b/src/components/chat/ToolCallBlock.tsx
@@ -1,12 +1,13 @@
import { useState, useEffect, memo } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
-import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Cpu, Monitor, GitBranch, GitCompare, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download } from 'lucide-react'
+import { Search, Globe, FileText, FileEdit, Terminal, Image, Film, Loader2, Check, X, Clock, AlertCircle, FolderOpen, Monitor, GitBranch, GitCommitHorizontal, GitPullRequest, FlaskConical, History, Users, Database, Download } from 'lucide-react'
import type { AgentToolCall } from '../../types/agent-mode'
import { getComfyHost, getComfyPort, downloadComfyFile } from '../../api/backend'
import { useModelPickStore } from '../../stores/modelPickStore'
import { useGenerationStore } from '../../stores/generationStore'
import { ModelPickerCard, ChangeModelInline, pickKindForToolCall } from './ModelPickerCard'
import { DiffView } from './DiffView'
+import { commandIcon } from '../../lib/shell-command-classify'
import { requestGenerationCancel } from '../../api/vram-handoff'
import { fileUrlToPath, readLocalFileAsBlobUrl } from '../../lib/local-media-url'
import { hiddenFromTranscript } from '../../lib/transcript-visibility'
@@ -151,6 +152,8 @@ interface Props {
// Complete over the registry (audit D4): 16 of 29 tools had no entry and fell
// back to the Terminal icon, so a git_commit looked like a shell command and
// a surgical file_edit like a plain write. Every builtin has a face now.
+// Since the 2.6.6 merge, shell_execute derives its face from the COMMAND
+// (commandIcon), so a commit still looks like a commit.
const TOOL_ICONS: Record<string, typeof Search> = {
web_search: Search,
web_fetch: Globe,
@@ -159,29 +162,30 @@ const TOOL_ICONS: Record<string, typeof Search> = {
file_edit: FileEdit,
file_list: FolderOpen,
file_search: Search,
- code_execute: Terminal,
shell_execute: Terminal,
- shell_execute_background: History,
- shell_task_status: History,
- shell_task_list: History,
- shell_task_kill: X,
- git_status: GitBranch,
- git_diff: GitCompare,
- git_log: GitBranch,
- git_commit: GitCommitHorizontal,
- git_push: GitBranch,
- gh_pr_create: GitPullRequest,
pr_resume: GitPullRequest,
- project_init: FolderOpen,
- run_tests: FlaskConical,
- system_info: Cpu,
- process_list: Cpu,
screenshot: Monitor,
image_generate: Image,
video_generate: Film,
run_workflow: GitBranch,
delegate_task: Users,
- get_current_time: Clock,
+}
+
+// The per-command faces of the merged shell tool (plan E4 point 6).
+const SHELL_COMMAND_ICONS: Record<string, typeof Search> = {
+ 'git-read': GitBranch,
+ 'git-commit': GitCommitHorizontal,
+ 'git-push': GitBranch,
+ test: FlaskConical,
+ read: FileText,
+ terminal: Terminal,
+}
+
+function shellIconFor(toolCall: AgentToolCall): typeof Search {
+ const command = toolCall.args?.command
+ if (toolCall.args?.background || typeof toolCall.args?.task === 'string') return History
+ if (typeof command !== 'string') return Terminal
+ return SHELL_COMMAND_ICONS[commandIcon(command)] ?? Terminal
}
const STATUS_ICONS = {
@@ -211,7 +215,7 @@ function ToolCallBlockImpl({ toolCall, onApprove, onReject }: Props) {
// Default: collapsed (closed)
const [open, setOpen] = useState(toolCall.status === 'pending_approval')
- const ToolIcon = TOOL_ICONS[toolCall.toolName] || Terminal
+ const ToolIcon = toolCall.toolName === 'shell_execute' ? shellIconFor(toolCall) : (TOOL_ICONS[toolCall.toolName] || Terminal)
const StatusIcon = STATUS_ICONS[toolCall.status]
const isRunning = toolCall.status === 'running'
const isPending = toolCall.status === 'pending_approval'
diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.ts
index cb4538fd..1ae15977 100644
--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts
+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts
@@ -58,7 +58,6 @@ describe('a plain coding turn does not carry the generators', () => {
const out = names(gateCreateTools(codingCatalog(), 'refactor the auth guard and run the tests'))
expect(out).toContain('file_read')
expect(out).toContain('shell_execute')
- expect(out).toContain('git_status')
expect(out).toContain('todo_write')
})
diff --git a/src/hooks/__tests__/useCodex-tool-permissions.test.ts b/src/hooks/__tests__/useCodex-tool-permissions.test.ts
index e72884cb..29db25fb 100644
--- a/src/hooks/__tests__/useCodex-tool-permissions.test.ts
+++ b/src/hooks/__tests__/useCodex-tool-permissions.test.ts
@@ -132,7 +132,7 @@ describe('the name repair runs before both gates', () => {
// turn passed it, and canonicalToolName then turned it into `file_write`
// on the way to the executor.
const repairAt = src.indexOf('const knownToolNames = toolRegistry.getAll()')
- const readOnlyGateAt = src.indexOf('const blocked = toolCalls.filter((tc) => MUTATING_TOOLS.has')
+ const readOnlyGateAt = src.indexOf('const blocked = toolCalls.filter((tc) => !allowedInReadOnlyTurn')
const permissionGateAt = src.indexOf('const refused = toolCalls.filter(isBlocked)')
it('all three landmarks are present', () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index ae9ca0c1..a1cee7cd 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -11,7 +11,7 @@ import {
import { v4 as uuid } from 'uuid'
import { streamProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter, createThinkStreamSplitter } from '../lib/hermes-stream'
-import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts } from '../api/agent-context'
+import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, renderWorkspaceSection, setChatArtifactMode, takeChatArtifacts, setReadOnlyShellTurn } from '../api/agent-context'
import { isOllamaLocal } from '../api/backend'
import { requestGenerationCancel } from '../api/vram-handoff'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
@@ -49,13 +49,13 @@ import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'
import { selectRelevantToolsAsync, ALWAYS_INCLUDE, SMALL_MODEL_MAX_TOOLS } from '../lib/tool-selection'
import { renderToolRoster, renderToolNames } from '../lib/tool-roster'
-import { MUTATING_TOOLS } from '../lib/mutating-tools'
+import { MUTATING_TOOLS, allowedInReadOnlyTurn } from '../lib/mutating-tools'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
import { buildLoopRecheck, loopPassSaysDone } from '../lib/agent-commands'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
-import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
+import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
import { budgetFromSettings } from '../api/agents/budget'
import type { ChatMessage, ToolCall, ToolDefinition } from '../api/providers/types'
@@ -69,7 +69,7 @@ import { openPlanGap, planReconcileSteer, PLAN_RECONCILE_BUDGET } from '../lib/p
import { PlanStaleness, planStalenessSteer } from '../lib/plan-staleness'
import { reasoningOnlyRound, REASONING_CONTINUE_BUDGET, REASONING_CONTINUE_STEER } from '../lib/reasoning-round'
import { useTodoStore } from '../stores/todoStore'
-import { platformPromptLine } from '../lib/host-platform'
+import { hostEnvironmentBlock } from '../lib/host-platform'
import { httpStatusOf, isTerminalModelError, retryDelayMs } from '../lib/http-status'
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
@@ -345,6 +345,10 @@ export function useAgentChat() {
const slug = chatWorkspaceSlug(convId, convForSlug?.title)
setActiveChatId(slug)
setActiveConversationId(convId)
+ // Read-only turn: shell_execute stays offered (it carries the git
+ // inspectors since the 2.6.6 merge), the executor refuses everything
+ // that is not an inspection command. clearActiveChatId() resets it.
+ setReadOnlyShellTurn(opts?.readOnly === true)
// Multi-Repo Agent (B15) + workspace unification (B17): pin the
// resolved workspace so chatCtx() in builtin-tools.ts threads it
@@ -460,7 +464,7 @@ export function useAgentChat() {
// aren't drowned in the full ~24-tool set).
const curated = opts?.curatedTools
const toolMatchesCurated = (name: string) =>
- (!curated || curated.includes(name)) && !(opts?.readOnly && MUTATING_TOOLS.has(name))
+ (!curated || curated.includes(name)) && !(opts?.readOnly && !allowedInReadOnlyTurn(name))
// Build agent system prompt FIRST, then append caveman style as a modifier
const hermesToolDefs = toolRegistry.toHermesToolDefs(permissions)
@@ -1347,9 +1351,9 @@ export function useAgentChat() {
// 2026-07-25, where a read-only /plan created a file while every request
// carried a read-only catalog.
if (opts?.readOnly) {
- const blocked = toolCalls.filter((tc) => MUTATING_TOOLS.has(tc.function?.name ?? ''))
+ const blocked = toolCalls.filter((tc) => !allowedInReadOnlyTurn(tc.function?.name ?? ''))
if (blocked.length) {
- toolCalls = toolCalls.filter((tc) => !MUTATING_TOOLS.has(tc.function?.name ?? ''))
+ toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? ''))
const names = [...new Set(blocked.map((tc) => tc.function.name))].join(', ')
// `agentMessages`, not `messages` (audit follow-up): this guard was
// copied from useCodex, whose history array IS called messages. In
@@ -1416,9 +1420,6 @@ export function useAgentChat() {
if (tc.function.name === 'shell_execute' && !toolArgs.timeout) {
toolArgs.timeout = SHELL_EXECUTE_DEFAULT_TIMEOUT_MS
}
- if (tc.function.name === 'code_execute' && !toolArgs.timeout) {
- toolArgs.timeout = CODE_EXECUTE_DEFAULT_TIMEOUT_MS
- }
const ac: AgentToolCall = {
id: toolCallId,
toolName: tc.function.name,
@@ -2016,7 +2017,7 @@ export function extractMediaPrompt(text: string): string {
function buildAgentSystemPrompt(basePrompt: string, roster: string): string {
const agentInstructions = `You are an autonomous AI agent inside LU with full access to this computer. You execute tasks end-to-end by using tools, you do NOT just describe what to do.
-${platformPromptLine()}
+${hostEnvironmentBlock()}
Available tools:
${roster}
@@ -2052,7 +2053,7 @@ Other rules:
- PATHS: use paths relative to your working directory (e.g. \`package.json\`, \`src/app.ts\`, \`.\` for the current folder). Never start a path with \`/\` or a drive letter (\`C:\\\`), that escapes your workspace and fails. To list the current folder, use file_list with path \`.\`.
- For filesystem READ tasks: file_list first if needed, then file_read.
- For web tasks: web_search → web_fetch on the best URL → answer based on real data. web_search returns ONLY short snippets, ALWAYS call web_fetch to read the page.
-- The OS is stated above, so do not spend a call finding it out. For hardware or exact system paths: call system_info once at the start.
+- OS, clock and timezone are stated above, so do not spend a call finding them out. For hardware details or running processes, use shell_execute (macOS/Linux: \`uname -a\`, \`ps aux\`; Windows: \`Get-ComputerInfo\`, \`Get-Process\`).
- Chain multiple tools as needed. If a tool fails, try a different approach.
- Be concise in text. All the work happens in tool calls.
- Respond in the same language the user uses.`
@@ -2071,7 +2072,7 @@ Other rules:
function buildAgentSystemPromptLean(basePrompt: string, alwaysThere: string): string {
const lean = `You are an autonomous agent in LU with tools on this computer. Do tasks by CALLING tools, do not just describe them.
-${platformPromptLine()}
+${hostEnvironmentBlock()}
You always have: ${alwaysThere}. Your request carries the other tools that fit the task. Read their names there, do not guess.
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index b36cc2dd..b857f986 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -9,7 +9,7 @@ import { markToolsUnsupported } from '../api/tool-capability'
import { toolRegistry } from '../api/mcp'
import { usePermissionStore } from '../stores/permissionStore'
import { toolStrategyFor } from '../lib/tool-support'
-import { MUTATING_TOOLS } from '../lib/mutating-tools'
+import { allowedInReadOnlyTurn } from '../lib/mutating-tools'
import { applyGoalCommand } from '../lib/goal-command'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
@@ -17,7 +17,7 @@ import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'
import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'
import { streamProviderTurn, type StreamedProviderTurn } from '../lib/provider-stream'
import { createHermesDisplayFilter } from '../lib/hermes-stream'
-import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel } from '../api/agent-context'
+import { setActiveChatId, setActiveConversationId, clearActiveChatId, chatWorkspaceSlug, setActiveWorkspace, setActiveAgentModel, setReadOnlyShellTurn } from '../api/agent-context'
import { resolveWorkspace } from '../api/agents/workspace-resolve'
import { useAgentModeStore } from '../stores/agentModeStore'
import { loadLurules, renderRulesSection, type RulesReader } from '../lib/lurules'
@@ -55,9 +55,10 @@ import { canonicalToolName } from '../lib/loose-tool-parse'
import { selectRelevantTools, selectRelevantToolsAsync, SMALL_MODEL_MAX_TOOLS, gateCreateTools, wantsMediaTools, CREATE_TOOLS } from '../lib/tool-selection'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
-import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS, CODE_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
+import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
import { compactMessages, getModelMaxTokens, estimateTokens } from '../lib/context-compaction'
import { resolveAgentNumCtx } from '../lib/agent-num-ctx'
+import { hostEnvironmentBlock } from '../lib/host-platform'
import { AgentLoopGuard } from '../lib/agent-loop-guard'
import { findStagedForPath, stagedReadResult, stagedListingNote } from '../lib/staged-overlay'
import { applyAllStagedChanges } from '../lib/staged-apply'
@@ -79,11 +80,11 @@ function diagLog(_tag: string, _data: unknown): void {
// framing for a read-only reviewer and would fight the executor gate. The
// list-stripping below (MUTATING_TOOLS) still enforces
// read-only programmatically even if the model tries a write tool anyway.
-const CODEX_REVIEW_SYSTEM_PROMPT = `You are the Coding Agent in REVIEW MODE, a read-only code reviewer inside LU. You DO NOT modify any files, run any commands, or change any state. Your job is to read code with file_read / file_list / file_search / git_diff / git_log and return INLINE COMMENTS only.
+const CODEX_REVIEW_SYSTEM_PROMPT = `You are the Coding Agent in REVIEW MODE, a read-only code reviewer inside LU. You DO NOT modify any files or change any state. Your job is to read code with file_read / file_list / file_search plus inspection commands over shell_execute (git status, git log, git diff, git show, git blame, ls, cat, pwd) and return INLINE COMMENTS only.
REVIEW MODE CONTRACT (binding):
-- You MAY call: file_read, file_list, file_search, git_status, git_log, git_diff, system_info, process_list, get_current_time, web_fetch, web_search.
-- You MUST NOT call: file_write, file_edit, shell_execute, code_execute, run_tests, git_commit, git_push, gh_pr_create, image_generate, video_generate, run_workflow, screenshot, delegate_task. They are stripped from your tool list; attempting one fails as an unknown tool and wastes the step.
+- You MAY call: file_read, file_list, file_search, web_fetch, web_search, and shell_execute for INSPECTION ONLY (git status/log/diff/show/blame, ls, cat, pwd; one command, no chaining).
+- You MUST NOT call: file_write, file_edit, image_generate, video_generate, run_workflow, screenshot, delegate_task, or any shell command that changes state (commit, push, install, tests, deletes). Mutating tools are stripped from your list and mutating shell commands are refused; attempting one wastes the step.
- Output format: a markdown report with sections "## Summary", "## Findings (priority order)", "## Suggested follow-ups". For each finding cite the file + line range (path:line or path:start-end).
- Be direct. No flattery, no boilerplate. If the code is fine, say so in one sentence and stop.`
@@ -466,6 +467,10 @@ export function useCodex() {
// list-stripping below (MUTATING_TOOLS) still enforces it
// programmatically even if the model tries to call a write tool anyway.
const reviewMode = settings.codexReviewMode === true
+ // The merged shell_execute stays offered on read-only turns (it carries
+ // git status/log/diff now); the executor refuses everything else while
+ // this flag is up. Cleared in the finally below.
+ setReadOnlyShellTurn(reviewMode || readOnlyTurn)
// Review mode always wins; otherwise Small-Model Mode swaps in the lean
// prompt (Knob 2) for small local models.
const baseCodexPrompt = reviewMode
@@ -496,7 +501,10 @@ export function useCodex() {
workDir && workDir !== '.'
? `Working directory: ${workDir}\nUse paths relative to it (e.g. \`package.json\`); do not prefix with \`/\` or a drive letter.`
: 'Working directory: your private sandbox folder. Use relative paths only (e.g. `package.json`, `.`); never a leading `/` or a drive letter like `C:\\`.'
- let systemPrompt = `${baseCodexPrompt}${assetLine}\n\n${workDirLine}`
+ // Environment block (2.6.6, plan E3): OS, shell, clock, timezone. Codex
+ // never had the platform sentence; it paid for it with system_info and
+ // get_current_time round trips instead, and those tools are gone now.
+ let systemPrompt = `${baseCodexPrompt}${assetLine}\n\n${hostEnvironmentBlock()}\n${workDirLine}`
// Standing goal (/goal) — ahead of the rules and the repo map so it frames
// everything that follows instead of reading as an afterthought.
systemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))
@@ -905,7 +913,7 @@ export function useCodex() {
// with the system prompt — covers the model ignoring the instruction
// and trying anyway.
const codexTools = (settings.codexReviewMode || readOnlyTurn)
- ? codexToolsAll.filter((t) => !MUTATING_TOOLS.has(t.name))
+ ? codexToolsAll.filter((t) => allowedInReadOnlyTurn(t.name))
: codexToolsAll
// Tool-list sizing is a MODEL-STRENGTH decision (audit B3):
// - Small-Model Mode: embedding router + hard cap, ≤6 tools. A
@@ -1146,7 +1154,7 @@ export function useCodex() {
const def = toolRegistry.getToolByName(t.name)
if (!def) return true
if (!(CODEX_CATEGORIES as readonly string[]).includes(def.category)) return false
- if ((settings.codexReviewMode || readOnlyTurn) && MUTATING_TOOLS.has(t.name)) return false
+ if ((settings.codexReviewMode || readOnlyTurn) && !allowedInReadOnlyTurn(t.name)) return false
return true
},
)
@@ -1327,9 +1335,9 @@ export function useCodex() {
// every one of its six requests, and still created a file on disk.
// Review Mode carried the identical hole since 2.5.6.
if (settings.codexReviewMode || readOnlyTurn) {
- const blocked = toolCalls.filter((tc) => MUTATING_TOOLS.has(tc.function?.name ?? ''))
+ const blocked = toolCalls.filter((tc) => !allowedInReadOnlyTurn(tc.function?.name ?? ''))
if (blocked.length) {
- toolCalls = toolCalls.filter((tc) => !MUTATING_TOOLS.has(tc.function?.name ?? ''))
+ toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? ''))
const names = [...new Set(blocked.map((tc) => tc.function.name))].join(', ')
messages.push({
role: 'user',
@@ -1486,10 +1494,6 @@ export function useCodex() {
if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir
if (!toolArgs.timeout) toolArgs.timeout = SHELL_EXECUTE_DEFAULT_TIMEOUT_MS
}
- if (toolName === 'code_execute') {
- if (!toolArgs.cwd && hasValidWorkDir) toolArgs.cwd = workDir
- if (!toolArgs.timeout) toolArgs.timeout = CODE_EXECUTE_DEFAULT_TIMEOUT_MS
- }
// Resolve relative file paths against working directory.
// Absolute-path detection must accept ANY drive letter (C:, D:, E:, …),
// not just C:. Previously `!p.startsWith('C:')` classified
@@ -1997,7 +2001,7 @@ export function useCodex() {
markToolsUnsupported(modelToUse)
hint = '\n\nHint: this model does not support tool calling, so Code mode cannot use it. Pick a model that supports tool calling (Qwen 3, Llama 3.1+, Gemma 4) or an LU Cloud model shown with the tools badge.'
} else if (/timed out/i.test(msg)) {
- hint = '\n\nHint: a tool call exceeded its time budget. For long builds, raise the command timeout, split the work, or run it via shell_execute_background.'
+ hint = '\n\nHint: a tool call exceeded its time budget. For long builds, raise the command timeout, split the work, or start the command with background: true and poll it with task: "status".'
}
// An empty wallet is not a crash and no retry fixes it. Replace the
// status-code line with the plain explanation the other surfaces use.
diff --git a/src/lib/__tests__/prompt-tool-roster.test.ts b/src/lib/__tests__/prompt-tool-roster.test.ts
index 889e54f5..09f24083 100644
--- a/src/lib/__tests__/prompt-tool-roster.test.ts
+++ b/src/lib/__tests__/prompt-tool-roster.test.ts
@@ -114,7 +114,8 @@ function candidateToolWords(text: string): string[] {
describe('no prompt names a tool that does not exist', () => {
it('the registry parsed cleanly, so the rest of this file means something', () => {
- expect(TOOL_NAMES.length).toBeGreaterThan(25)
+ // 15 since the 2.6.6 merge folded the typed shell wrappers away.
+ expect(TOOL_NAMES.length).toBeGreaterThan(12)
expect(TOOL_NAMES).toContain('todo_write')
expect(TOOL_NAMES).toContain('file_edit')
})
@@ -133,7 +134,7 @@ describe('no prompt names a tool that does not exist', () => {
}
it('the relay list parsed, and is genuinely a subset of the desktop one', () => {
- expect(RELAY_TOOL_NAMES.length).toBeGreaterThan(10)
+ expect(RELAY_TOOL_NAMES.length).toBeGreaterThan(8)
expect(RELAY_TOOL_NAMES.length).toBeLessThan(TOOL_NAMES.length)
expect(RELAY_TOOL_NAMES.filter((n) => !TOOL_NAMES.includes(n))).toEqual([])
})
diff --git a/src/lib/__tests__/readonly-enforcement.test.ts b/src/lib/__tests__/readonly-enforcement.test.ts
index 7dfe1ba0..db28ae48 100644
--- a/src/lib/__tests__/readonly-enforcement.test.ts
+++ b/src/lib/__tests__/readonly-enforcement.test.ts
@@ -17,15 +17,17 @@ import { describe, it, expect } from 'vitest'
import { readFileSync } from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'path'
-import { MUTATING_TOOLS } from '../mutating-tools'
+import { MUTATING_TOOLS, allowedInReadOnlyTurn } from '../mutating-tools'
const __dirname = dirname(fileURLToPath(import.meta.url))
const read = (rel: string) => readFileSync(join(__dirname, rel), 'utf8')
type Call = { function: { name: string } }
-/** The guard both hooks apply before a batch executes. */
+/** The guard both hooks apply before a batch executes. Since the 2.6.6 merge
+ * it keeps shell_execute (the executor gates by command); everything else
+ * mutating is still dropped by name. */
const applyGuard = (calls: Call[], readOnly: boolean) =>
- readOnly ? calls.filter((c) => !MUTATING_TOOLS.has(c.function?.name ?? '')) : calls
+ readOnly ? calls.filter((c) => allowedInReadOnlyTurn(c.function?.name ?? '')) : calls
const call = (name: string): Call => ({ function: { name } })
@@ -35,13 +37,15 @@ describe('read-only batch guard', () => {
expect(applyGuard(batch, true).map((c) => c.function.name)).toEqual(['file_read', 'file_search'])
})
- it('drops every mutating tool, not just the file ones', () => {
+ it('drops every mutating tool except the command-gated shell', () => {
const batch = [...MUTATING_TOOLS].map(call)
- expect(applyGuard(batch, true)).toEqual([])
+ // shell_execute survives the name strip on purpose: it carries the git
+ // inspectors now, and its executor refuses non-inspection commands.
+ expect(applyGuard(batch, true).map((c) => c.function.name)).toEqual(['shell_execute'])
})
it('leaves the read tools alone', () => {
- const reads = ['file_read', 'file_list', 'file_search', 'git_status', 'git_diff', 'git_log'].map(call)
+ const reads = ['file_read', 'file_list', 'file_search'].map(call)
expect(applyGuard(reads, true)).toHaveLength(reads.length)
})
@@ -50,16 +54,18 @@ describe('read-only batch guard', () => {
expect(applyGuard(batch, false)).toHaveLength(2)
})
- it('git inspection is not classified as mutating', () => {
- // A reviewer still has to be able to look at the diff it is reviewing.
- for (const t of ['git_status', 'git_diff', 'git_log', 'file_read', 'file_list', 'file_search']) {
+ it('git inspection stays reachable: shell_execute survives the strip', () => {
+ // A reviewer still has to be able to look at the diff it is reviewing,
+ // and since the merge that look goes through shell_execute.
+ expect(allowedInReadOnlyTurn('shell_execute')).toBe(true)
+ for (const t of ['file_read', 'file_list', 'file_search']) {
expect(MUTATING_TOOLS.has(t), `${t} must stay available`).toBe(false)
}
})
it('the tools that can actually change something are all listed', () => {
- for (const t of ['file_write', 'file_edit', 'shell_execute', 'code_execute', 'git_commit', 'git_push', 'gh_pr_create']) {
- expect(MUTATING_TOOLS.has(t), `${t} must be blocked`).toBe(true)
+ for (const t of ['file_write', 'file_edit', 'shell_execute', 'image_generate', 'video_generate', 'run_workflow', 'delegate_task', 'screenshot']) {
+ expect(MUTATING_TOOLS.has(t), `${t} must be listed`).toBe(true)
}
})
})
@@ -68,13 +74,13 @@ describe('both hooks still carry the guard', () => {
it('useCodex filters the batch, not just the catalog', () => {
const src = read('../../hooks/useCodex.ts')
expect(src).toContain('if (settings.codexReviewMode || readOnlyTurn) {')
- expect(src).toContain('toolCalls = toolCalls.filter((tc) => !MUTATING_TOOLS.has(tc.function?.name ?? \'\'))')
+ expect(src).toContain('toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? \'\'))')
})
it('useAgentChat filters the batch too', () => {
const src = read('../../hooks/useAgentChat.ts')
expect(src).toContain('if (opts?.readOnly) {')
- expect(src).toContain('toolCalls = toolCalls.filter((tc) => !MUTATING_TOOLS.has(tc.function?.name ?? \'\'))')
+ expect(src).toContain('toolCalls = toolCalls.filter((tc) => allowedInReadOnlyTurn(tc.function?.name ?? \'\'))')
})
it('the blocklist has exactly one definition', () => {
diff --git a/src/lib/__tests__/tool-classification.test.ts b/src/lib/__tests__/tool-classification.test.ts
index f3ec495f..25de1165 100644
--- a/src/lib/__tests__/tool-classification.test.ts
+++ b/src/lib/__tests__/tool-classification.test.ts
@@ -39,17 +39,9 @@ const READ_ONLY_TOOLS: ReadonlySet<string> = new Set([
'file_read',
'file_list',
'file_search',
- 'git_status',
- 'git_log',
- 'git_diff',
// Reads a PR through `gh pr view` / `gh pr diff`. Owner and repo are
// validated to GitHub's own character set before they reach a shell.
'pr_resume',
- 'shell_task_status',
- 'shell_task_list',
- 'process_list',
- 'system_info',
- 'get_current_time',
'web_search',
'web_fetch',
])
@@ -60,7 +52,8 @@ describe('every built-in tool is classified', () => {
// instead of quietly asserting over an empty list.
expect(arrayStart).toBeGreaterThanOrEqual(0)
expect(arrayEnd).toBeGreaterThan(arrayStart)
- expect(BUILTIN_TOOL_NAMES.length).toBeGreaterThan(20)
+ // 14 since the 2.6.6 merge folded the twelve typed shell wrappers away.
+ expect(BUILTIN_TOOL_NAMES.length).toBeGreaterThan(12)
expect(BUILTIN_TOOL_NAMES).toContain('shell_execute')
expect(BUILTIN_TOOL_NAMES).toContain('pr_resume')
})
@@ -85,11 +78,12 @@ describe('every built-in tool is classified', () => {
it('nothing that spawns a shell is read-only unless its arguments are constrained', () => {
// pr_resume is the one read-only tool that reaches a shell. It is allowed
// there only because parsePrUrl rejects every metacharacter, which
- // shell-injection.test.ts pins. If another shell tool is ever added to the
- // read-only set, that decision needs the same proof.
+ // shell-injection.test.ts pins. The typed git readers left with the 2.6.6
+ // merge; their read-only path is shell_execute, whose command classifier
+ // (isReadOnlyCommand) carries the same proof in its own tests.
const shellReaders = [...READ_ONLY_TOOLS].filter((n) =>
- ['pr_resume', 'git_status', 'git_log', 'git_diff'].includes(n),
+ ['pr_resume', 'shell_execute'].includes(n),
)
- expect(shellReaders.sort()).toEqual(['git_diff', 'git_log', 'git_status', 'pr_resume'])
+ expect(shellReaders).toEqual(['pr_resume'])
})
})
diff --git a/src/lib/__tests__/tool-selection-async.test.ts b/src/lib/__tests__/tool-selection-async.test.ts
index df6180b3..f69f3253 100644
--- a/src/lib/__tests__/tool-selection-async.test.ts
+++ b/src/lib/__tests__/tool-selection-async.test.ts
@@ -40,17 +40,17 @@ describe('tool-selection — selectRelevantToolsAsync', () => {
const tools = [
mkTool('file_read', 'read a file on disk', 'filesystem'),
mkTool('file_write', 'write a file on disk', 'filesystem'),
- mkTool('get_current_time', 'return current local time', 'system'),
+ mkTool('shell_execute', 'run a terminal command', 'terminal'),
]
const embedSpy = vi.fn(fakeEmbed)
const out = await selectRelevantToolsAsync(
- 'what time is it',
+ 'run the build',
tools,
fullPerms,
{ embed: embedSpy, embeddingThreshold: EMBEDDING_ROUTING_THRESHOLD }
)
expect(embedSpy).not.toHaveBeenCalled()
- expect(out.some((t) => t.name === 'get_current_time')).toBe(true)
+ expect(out.some((t) => t.name === 'shell_execute')).toBe(true)
})
it('no embed fn provided: keyword path', async () => {
@@ -68,11 +68,7 @@ describe('tool-selection — selectRelevantToolsAsync', () => {
mkTool('file_write', 'write a file on disk', 'filesystem'),
mkTool('web_search', 'search the web for current information', 'web'),
mkTool('web_fetch', 'fetch a URL and return text', 'web'),
- mkTool('get_current_time', 'return current local date time', 'system'),
mkTool('shell_execute', 'run a terminal command', 'terminal'),
- mkTool('code_execute', 'execute python code', 'terminal'),
- mkTool('system_info', 'os architecture hostname', 'system'),
- mkTool('process_list', 'list running processes', 'system'),
mkTool('screenshot', 'take a screenshot', 'desktop'),
mkTool('image_generate', 'generate an image from prompt', 'image'),
mkTool('run_workflow', 'run a saved workflow', 'workflow'),
@@ -88,9 +84,9 @@ describe('tool-selection — selectRelevantToolsAsync', () => {
fullPerms,
{ embed: fakeEmbed, topN: 3 }
)
- // ALWAYS_INCLUDE means file_read and file_write + get_current_time are in.
+ // ALWAYS_INCLUDE means file_read and file_write are in.
expect(out.some((t) => t.name === 'file_read')).toBe(true)
- expect(out.some((t) => t.name === 'get_current_time')).toBe(true)
+ expect(out.some((t) => t.name === 'file_write')).toBe(true)
})
it('embed failure falls back silently to keyword', async () => {
diff --git a/src/lib/__tests__/tool-selection.test.ts b/src/lib/__tests__/tool-selection.test.ts
index 4cfcbbf9..275d0ced 100644
--- a/src/lib/__tests__/tool-selection.test.ts
+++ b/src/lib/__tests__/tool-selection.test.ts
@@ -33,9 +33,6 @@ const ALL_TOOLS: MCPToolDefinition[] = [
makeTool('file_list', 'filesystem'),
makeTool('file_search', 'filesystem'),
makeTool('shell_execute', 'terminal'),
- makeTool('code_execute', 'terminal'),
- makeTool('system_info', 'system'),
- makeTool('process_list', 'system'),
makeTool('screenshot', 'desktop'),
makeTool('image_generate', 'image'),
makeTool('run_workflow', 'workflow'),
@@ -127,11 +124,10 @@ describe('tool-selection', () => {
expect(names).toContain('file_search')
})
- it('selects shell/code tools for "run" keyword', () => {
+ it('selects the shell for "run" keyword', () => {
const result = selectRelevantTools('run npm install', ALL_TOOLS, ALL_ALLOWED)
const names = toolNames(result)
expect(names).toContain('shell_execute')
- expect(names).toContain('code_execute')
})
it('selects shell/code tools for "git" keyword', () => {
@@ -140,24 +136,22 @@ describe('tool-selection', () => {
expect(names).toContain('shell_execute')
})
- it('selects shell/code tools for "python" keyword', () => {
+ it('selects the shell for "python" keyword', () => {
const result = selectRelevantTools('run this python script', ALL_TOOLS, ALL_ALLOWED)
const names = toolNames(result)
expect(names).toContain('shell_execute')
- expect(names).toContain('code_execute')
})
- it('selects system tools for "cpu" keyword', () => {
+ it('routes the "cpu" keyword to the shell (system tools retired)', () => {
const result = selectRelevantTools('how much cpu am I using', ALL_TOOLS, ALL_ALLOWED)
const names = toolNames(result)
- expect(names).toContain('system_info')
- expect(names).toContain('process_list')
+ expect(names).toContain('shell_execute')
})
it('selects system tools for "memory" keyword', () => {
const result = selectRelevantTools('check memory usage', ALL_TOOLS, ALL_ALLOWED)
const names = toolNames(result)
- expect(names).toContain('system_info')
+ expect(names).toContain('shell_execute')
})
it('selects screenshot tool for "screenshot" keyword', () => {
@@ -260,23 +254,22 @@ describe('tool-selection', () => {
})
it('returns all available if all selected tools are blocked', () => {
- // Block everything except system
+ // Block everything except terminal
const permissions: PermissionMap = {
filesystem: 'blocked',
- terminal: 'blocked',
+ terminal: 'auto',
desktop: 'blocked',
web: 'blocked',
- system: 'auto',
+ system: 'blocked',
image: 'blocked',
video: 'blocked' as any,
workflow: 'blocked',
}
// Message that matches web tools (blocked) and filesystem (blocked)
const result = selectRelevantTools('search and read', ALL_TOOLS, permissions)
- // All selected tools blocked -> returns all available (system_info + process_list)
+ // All selected tools blocked -> returns all available (the shell)
const names = toolNames(result)
- expect(names).toContain('system_info')
- expect(names).toContain('process_list')
+ expect(names).toContain('shell_execute')
})
})
diff --git a/src/lib/mutating-tools.ts b/src/lib/mutating-tools.ts
index 9d018d07..d15681ac 100644
--- a/src/lib/mutating-tools.ts
+++ b/src/lib/mutating-tools.ts
@@ -3,9 +3,16 @@
*
* Two things strip these from a turn's catalog: Code-Review Mode, and a
* read-only slash command (/review, /plan, /diff, /explain, /find, /todo,
- * /security). Read-only inspectors stay — git_status / git_log / git_diff,
- * shell_task_status / shell_task_list, file_read / file_list / file_search —
- * so the agent can still do the looking the command asked for.
+ * /security). Read-only inspectors stay (file_read / file_list /
+ * file_search) so the agent can still do the looking the command asked for.
+ *
+ * Since the 2.6.6 tool merge, shell_execute is the special case: it is
+ * mutating (it can run anything), yet it must SURVIVE the read-only strip,
+ * because the typed inspectors (git_status, git_log, git_diff, task status)
+ * live inside it now. The gate moved from the catalog to the executor:
+ * a read-only turn sets a flag (agent-context) and executeShellExecute only
+ * runs commands isReadOnlyCommand() approves. allowedInReadOnlyTurn() is
+ * what the catalog filters use so this exception lives in one place.
*
* Shared between useCodex and useAgentChat so the same command behaves the same
* in the Code tab and in Agent mode. It lived only in useCodex until 2.5.9,
@@ -15,17 +22,14 @@ export const MUTATING_TOOLS = new Set([
'file_write',
'file_edit',
'shell_execute',
- 'code_execute',
- 'shell_execute_background',
- 'shell_task_kill',
- 'git_commit',
- 'git_push',
- 'project_init',
- 'gh_pr_create',
- 'run_tests',
'image_generate',
'video_generate',
'run_workflow',
'delegate_task',
'screenshot',
])
+
+/** May this tool stay in the catalog during a read-only turn? */
+export function allowedInReadOnlyTurn(name: string): boolean {
+ return name === 'shell_execute' || !MUTATING_TOOLS.has(name)
+}
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index ed0170f3..2a1af4cf 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -84,45 +84,29 @@ const TOOL_GROUPS: ToolGroup[] = [
tools: ['file_search'],
},
{
- keywords: ['run', 'execute', 'command', 'shell', 'terminal', 'bash', 'powershell', 'npm', 'git', 'pip', 'node', 'python', 'install', 'build', 'test', 'compile'],
- tools: ['shell_execute', 'code_execute'],
- },
- {
- // Audit B3: a third of the registry sat in NO group and was therefore
- // invisible to the model forever — all git_*, run_tests, the background
- // shell and its status tools, pr_resume, gh_pr_create, project_init.
- // The typed git tools return parsed porcelain instead of an opaque dump,
- // which is exactly what a small model needs for "commit this".
- keywords: ['git', 'commit', 'push', 'branch', 'merge', 'rebase', 'stage', 'staged', 'diff', 'changelog', 'version control'],
- tools: ['git_status', 'git_diff', 'git_log', 'git_commit', 'git_push'],
- },
- {
- keywords: ['test', 'tests', 'spec', 'vitest', 'jest', 'pytest', 'cargo test', 'failing', 'make it green', 'suite'],
- tools: ['run_tests'],
+ // Since the 2.6.6 merge shell_execute IS git, tests, background tasks
+ // and scaffolding, so every keyword that used to route a typed wrapper
+ // routes the one shell now (plan E4 point 7).
+ keywords: ['run', 'execute', 'command', 'shell', 'terminal', 'bash', 'powershell', 'npm', 'pip', 'node', 'python', 'install', 'build', 'compile',
+ 'git', 'commit', 'push', 'branch', 'merge', 'rebase', 'stage', 'staged', 'diff', 'changelog', 'version control',
+ 'test', 'tests', 'spec', 'vitest', 'jest', 'pytest', 'cargo test', 'failing', 'make it green', 'suite',
+ 'background', 'long running', 'long-running', 'dataset', 'refactor everything', 'task status', 'still running',
+ 'scaffold', 'new project', 'init a', 'initialize', 'bootstrap', 'starter'],
+ tools: ['shell_execute'],
},
{
keywords: ['pull request', 'pull-request', 'open a pr', 'create a pr', 'the pr', 'github', 'gh pr'],
- tools: ['gh_pr_create', 'pr_resume', 'git_status', 'git_diff'],
- },
- {
- // Long-running work belongs on the background bridge: it survives the
- // 10-minute foreground timeout and the model can poll it. The timeout
- // hint in useCodex points at shell_execute_background, so it has to be
- // reachable when builds/installs are on the table (audit B4).
- keywords: ['background', 'install', 'build', 'compile', 'long running', 'long-running', 'dataset', 'refactor everything', 'task status', 'still running'],
- tools: ['shell_execute_background', 'shell_task_status', 'shell_task_list', 'shell_task_kill'],
- },
- {
- keywords: ['scaffold', 'new project', 'init a', 'initialize', 'bootstrap', 'starter'],
- tools: ['project_init'],
+ tools: ['pr_resume', 'shell_execute'],
},
{
keywords: ['delegate', 'sub-agent', 'subagent', 'fan out', 'in parallel', 'parallelize', 'split the work'],
tools: ['delegate_task'],
},
{
+ // system_info / process_list retired (2.6.6): the environment block in
+ // the system prompt covers OS and clock, the shell covers the rest.
keywords: ['system', 'os', 'cpu', 'ram', 'memory', 'process', 'running', 'hostname'],
- tools: ['system_info', 'process_list'],
+ tools: ['shell_execute'],
},
{
keywords: ['screenshot', 'screen', 'desktop', 'capture', 'see my screen'],
@@ -136,22 +120,17 @@ const TOOL_GROUPS: ToolGroup[] = [
keywords: WORKFLOW_KEYWORDS,
tools: ['run_workflow'],
},
- {
- keywords: ['time', 'date', 'day', 'today', 'datum', 'heute', 'tag', 'uhrzeit', 'jetzt', 'now', 'clock', 'hour', 'minute', 'timezone', 'zeitzone'],
- tools: ['get_current_time'],
- },
]
// Tools that should always be available regardless of the prompt — they're
// cheap to include, commonly useful, and often needed mid-run (e.g. after
-// a tool result reveals the user really wanted a file read). Keeping
-// `get_current_time` here means the agent NEVER has to fall back to web
-// for a trivial date question just because the keyword list missed.
+// a tool result reveals the user really wanted a file read). The clock lives
+// in the system prompt's environment block now, so no time tool is needed.
// `todo_write` is here rather than in a keyword group on purpose: the moment a
// task turns out to need a plan is usually mid-run, several tool results after
// the prompt that routed the catalog. Keyword-gating it would mean the agent
// can only plan when the user happened to say "plan".
-export const ALWAYS_INCLUDE = ['file_read', 'file_write', 'file_edit', 'get_current_time', 'todo_write']
+export const ALWAYS_INCLUDE = ['file_read', 'file_write', 'file_edit', 'todo_write']
/**
* The tool cap Small-Model Mode sends to a 3B-8B model.
@@ -226,7 +205,6 @@ export function selectRelevantTools(
// files, which is exactly what CODEX_SYSTEM_PROMPT tells the model to do.
const hasCodeSignal =
selectedNames.has('shell_execute') ||
- selectedNames.has('code_execute') ||
selectedNames.has('file_search') ||
selectedNames.has('file_list')
if (hasCodeSignal) {
diff --git a/src/lib/tool-timeout.ts b/src/lib/tool-timeout.ts
index 9f783399..510e008b 100644
--- a/src/lib/tool-timeout.ts
+++ b/src/lib/tool-timeout.ts
@@ -17,15 +17,9 @@
* app (npm install, cargo/gradle) routinely runs minutes; the old 30 s
* default + 60 s JS cap killed every real build (David 2026-06-04). */
export const SHELL_EXECUTE_DEFAULT_TIMEOUT_MS = 600_000
-export const CODE_EXECUTE_DEFAULT_TIMEOUT_MS = 120_000
const LONG_RUNNING = new Set([
'shell_execute',
- 'code_execute',
- 'shell_execute_background',
- 'run_tests',
- 'git_commit',
- 'git_push',
])
export interface ToolTimeoutSettings {
diff --git a/src/stores/__tests__/permissionStore.test.ts b/src/stores/__tests__/permissionStore.test.ts
index 65b69bc3..93765ced 100644
--- a/src/stores/__tests__/permissionStore.test.ts
+++ b/src/stores/__tests__/permissionStore.test.ts
@@ -188,3 +188,50 @@ describe('permissionStore', () => {
})
})
})
+
+// v3 (2.6.6 tool merge) — per-tool overrides on retired names must land on
+// shell_execute, most restrictive wins, because that is the tool their work
+// actually runs through now.
+describe('retired-name override lift (v3)', () => {
+ it('lifts the strictest retired override onto shell_execute', () => {
+ const persisted = {
+ globalPermissions: { ...DEFAULT_PERMISSIONS },
+ perToolOverrides: { git_push: 'confirm', run_tests: 'auto', git_commit: 'blocked' },
+ }
+ const migrated = migratePermissionState(persisted, 2)
+ expect(migrated.perToolOverrides.shell_execute).toBe('blocked')
+ expect(migrated.perToolOverrides.git_push).toBeUndefined()
+ expect(migrated.perToolOverrides.run_tests).toBeUndefined()
+ expect(migrated.perToolOverrides.git_commit).toBeUndefined()
+ })
+
+ it('never loosens an existing shell_execute override', () => {
+ const persisted = {
+ globalPermissions: { ...DEFAULT_PERMISSIONS },
+ perToolOverrides: { shell_execute: 'blocked', git_push: 'auto' },
+ }
+ const migrated = migratePermissionState(persisted, 2)
+ expect(migrated.perToolOverrides.shell_execute).toBe('blocked')
+ })
+
+ it('tightens a loose shell_execute override when a retired name was stricter', () => {
+ const persisted = {
+ globalPermissions: { ...DEFAULT_PERMISSIONS },
+ perToolOverrides: { shell_execute: 'auto', git_push: 'confirm' },
+ }
+ const migrated = migratePermissionState(persisted, 2)
+ expect(migrated.perToolOverrides.shell_execute).toBe('confirm')
+ })
+
+ it('leaves live-tool overrides alone and is a no-op at version 3', () => {
+ const persisted = {
+ globalPermissions: { ...DEFAULT_PERMISSIONS },
+ perToolOverrides: { file_write: 'blocked', git_push: 'blocked' },
+ }
+ const same = migratePermissionState({ ...persisted, perToolOverrides: { ...persisted.perToolOverrides } }, 3)
+ expect(same.perToolOverrides).toEqual({ file_write: 'blocked', git_push: 'blocked' })
+ const migrated = migratePermissionState(persisted, 2)
+ expect(migrated.perToolOverrides.file_write).toBe('blocked')
+ expect(migrated.perToolOverrides.shell_execute).toBe('blocked')
+ })
+})
diff --git a/src/stores/permissionStore.ts b/src/stores/permissionStore.ts
index 186be845..9ca5234c 100644
--- a/src/stores/permissionStore.ts
+++ b/src/stores/permissionStore.ts
@@ -117,7 +117,7 @@ export const usePermissionStore = create<PermissionState>()(
}),
{
name: 'locally-uncensored-permissions',
- version: 2,
+ version: 3,
migrate: migratePermissionState,
}
)
@@ -132,6 +132,38 @@ export function migratePermissionState(persisted: any, version: number) {
if (version < 2 && persisted?.globalPermissions?.video === 'blocked') {
persisted.globalPermissions.video = DEFAULT_PERMISSIONS.video
}
+ // v3 (2.6.6 tool merge): the typed shell wrappers are gone, their calls run
+ // through shell_execute now. A per-tool override on a retired name would be
+ // silently dead, so lift the overrides onto shell_execute. Most restrictive
+ // wins: a user who forced confirmation on git_push keeps that protection on
+ // the tool the push actually runs through.
+ if (version < 3 && persisted?.perToolOverrides) {
+ // Frozen copy of the names retired in 2.6.6, NOT imported from
+ // builtin-tools: a migration describes the past and must not drift with
+ // the live registry (and the import would drag the whole tool module
+ // into store init).
+ const RETIRED_V3 = [
+ 'git_status', 'git_log', 'git_diff', 'git_commit', 'git_push',
+ 'run_tests', 'gh_pr_create', 'project_init', 'code_execute',
+ 'system_info', 'process_list', 'get_current_time',
+ 'shell_execute_background', 'shell_task_status', 'shell_task_kill', 'shell_task_list',
+ ]
+ const overrides = persisted.perToolOverrides as Record<string, string>
+ const RANK: Record<string, number> = { auto: 0, confirm: 1, blocked: 2 }
+ let strictest: string | undefined
+ for (const name of RETIRED_V3) {
+ const level = overrides[name]
+ if (!level) continue
+ delete overrides[name]
+ if (strictest === undefined || (RANK[level] ?? 0) > (RANK[strictest] ?? 0)) strictest = level
+ }
+ if (strictest !== undefined) {
+ const own = overrides['shell_execute']
+ if (own === undefined || (RANK[strictest] ?? 0) > (RANK[own] ?? 0)) {
+ overrides['shell_execute'] = strictest
+ }
+ }
+ }
return persisted
}
diff --git a/src/types/agents.ts b/src/types/agents.ts
index e9ba6eda..0732f143 100644
--- a/src/types/agents.ts
+++ b/src/types/agents.ts
@@ -18,9 +18,7 @@ export type ToolName =
| "web_fetch"
| "file_read"
| "file_write"
- | "code_execute"
- | "image_generate"
- | "get_current_time";
+ | "image_generate";
export interface ToolParameter {
name: string;