Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: send routine coding work to the local model with unsloth start --auto-route (#13478)
Nilayb0a7f1e34453
diff --git a/unsloth_cli/claude_subagent_mcp.py b/unsloth_cli/claude_subagent_mcp.pyindex ff3a3577b9e..5ff302bbae8 100644--- a/unsloth_cli/claude_subagent_mcp.py+++ b/unsloth_cli/claude_subagent_mcp.py@@ -18,7 +18,11 @@ from typing import Any, Callablefrom unsloth_cli.commands.start import (_CLAUDE_ENV_UNSET,+ _CLAUDE_SUBAGENT_AUTO_ROUTE_ENV,+ _CLAUDE_SUBAGENT_FALLBACK_ENV,_CLAUDE_SUBAGENT_SETTINGS_ENV,+ _SUBAGENT_AUTO_ROUTE_DESCRIPTION,+ _SUBAGENT_AUTO_ROUTE_INSTRUCTIONS,_SUBAGENT_DESCRIPTION,_SUBAGENT_INSTRUCTIONS,_SUBAGENT_PLAN_DESCRIPTION,@@ -465,12 +469,43 @@ def serve(signal.signal(signum, handler)+def _with_fallback(run_agent: Callable[..., str], marker: str) -> Callable[..., str]:+ def run(task: str, cancel_event: threading.Event) -> str:+ try:+ text = run_agent(task, cancel_event)+ except Exception as exc:+ if cancel_event.is_set():+ raise+ Path(marker).touch()+ raise RuntimeError(+ f"{exc}\n\nThe local agent failed, so your own Read, Grep, Glob, Bash, "+ "PowerShell, Monitor, NotebookRead and Agent tools are unblocked until the "+ "next successful unsloth_agent call. "+ "Do this step yourself."+ ) from exc+ Path(marker).unlink(missing_ok = True)+ return text++ return run++def main() -> None:+ auto_route = os.environ.get(_CLAUDE_SUBAGENT_AUTO_ROUTE_ENV) == "1"+ marker = os.environ.get(_CLAUDE_SUBAGENT_FALLBACK_ENV)+ run_agent = run_local_agent+ run_read_only_agent = lambda task, cancel_event: run_local_agent(+ task, cancel_event, read_only = True+ )+ if marker:+ # With --auto-route the parent's own tools are blocked, so a failed local run would otherwise lose the task.+ run_agent = _with_fallback(run_agent, marker)+ run_read_only_agent = _with_fallback(run_read_only_agent, marker)serve(- run_read_only_agent = lambda task, cancel_event: run_local_agent(- task, cancel_event, read_only = True- ),+ run_agent = run_agent,+ tool_description = _SUBAGENT_AUTO_ROUTE_DESCRIPTION if auto_route else None,+ run_read_only_agent = run_read_only_agent,read_only_tool_name = "unsloth_plan_agent",+ instructions = _SUBAGENT_AUTO_ROUTE_INSTRUCTIONS if auto_route else None,)diff --git a/unsloth_cli/codex_subagent_mcp.py b/unsloth_cli/codex_subagent_mcp.pyindex b047e92e262..cefd046a939 100644--- a/unsloth_cli/codex_subagent_mcp.py+++ b/unsloth_cli/codex_subagent_mcp.py@@ -16,6 +16,7 @@ from typing import Anyfrom unsloth_cli.claude_subagent_mcp import _bounded, _stop_child, servefrom unsloth_cli.commands.start import (+ _CODEX_AUTO_ROUTE_TOOL_DESCRIPTION,_CODEX_ENV_KEY,_CODEX_ENV_UNSET,_CODEX_PROFILE,@@ -50,9 +51,10 @@ def _config() -> dict:return config-def _result_text(stdout: str) -> str:+def _events(stdout: str) -> tuple[list[str], list[str], list[dict]]:messages = []errors = []+ commands = []for line in stdout.splitlines():try:event = json.loads(line)@@ -69,20 +71,43 @@ def _result_text(stdout: str) -> str:and item["text"].strip()):messages.append(item["text"].strip())+ if (+ event.get("type") == "item.completed"+ and isinstance(item, dict)+ and item.get("type") == "command_execution"+ ):+ commands.append(item)if event.get("type") in ("error", "turn.failed"):detail = event.get("message") or event.get("error")if isinstance(detail, dict):detail = detail.get("message") or json.dumps(detail)if detail:errors.append(str(detail))+ return messages, errors, commands+++def _result_text(stdout: str, show_last_command: bool = False) -> str:+ messages, errors, commands = _events(stdout)if errors:raise RuntimeError(_bounded(errors[-1]))- if messages:- return _bounded(messages[-1])- raise RuntimeError("The local Codex agent returned no readable result.")+ if not messages:+ raise RuntimeError("The local Codex agent returned no readable result.")+ if show_last_command and commands:+ # A small local model can report an edit that its own command never made; the raw output lets the parent check.+ last = commands[-1]+ output = str(last.get("aggregated_output") or "")[-2000:]+ return _bounded(+ f"{messages[-1]}\n\nLast command it ran: {last.get('command')}\n"+ f"Exit code: {last.get('exit_code')}\nOutput:\n{output}"+ )+ return _bounded(messages[-1])-def run_local_agent(task: str, cancel_event: threading.Event | None = None) -> str:+def run_local_agent(+ task: str,+ cancel_event: threading.Event | None = None,+ show_last_command: bool = False,+) -> str:config = _config()executable = _prefer_windows_cmd_sibling(shutil.which("codex"))if executable is None:@@ -101,6 +126,9 @@ def run_local_agent(task: str, cancel_event: threading.Event | None = None) -> s"--oss","--profile",_CODEX_PROFILE,+ # Codex otherwise waits forever for a refused connection, so a stopped server hung the parent's call.+ "-c",+ "features.unbounded_connection_retries=false",*permissions,"exec","--ephemeral",@@ -156,20 +184,43 @@ def run_local_agent(task: str, cancel_event: threading.Event | None = None) -> s_stop_child(process)raiseif process.returncode != 0:- detail = stderr.strip() or stdout.strip()+ # stderr is codex's own banner; the last error event says why the run stopped.+ errors = _events(stdout)[1]+ detail = (errors[-1] if errors else "") or stderr.strip() or stdout.strip()raise RuntimeError(_bounded(detail) or f"Local Codex exited with code {process.returncode}.")- return _result_text(stdout)+ return _result_text(stdout, show_last_command)def main() -> None:if len(sys.argv) > 1:os.environ[_CODEX_SUBAGENT_CONFIG_ENV] = sys.argv[1]+ try:+ auto_route = _config().get("auto_route") is True+ except RuntimeError:+ auto_route = False+ run_agent = run_local_agent+ if auto_route:++ def run_agent(task: str, cancel_event: threading.Event) -> str:+ try:+ return run_local_agent(task, cancel_event, show_last_command = True)+ except Exception as exc:+ if cancel_event.is_set():+ raise+ # The parent's shell is off with --auto-route, so it must not pretend the step ran.+ raise RuntimeError(+ f"{exc}\n\nThe local agent failed and your own shell is disabled in this "+ "session, so this step was not done. Tell the user so plainly."+ ) from exc+serve(- run_agent = run_local_agent,+ run_agent = run_agent,tool_name = _CODEX_SUBAGENT_MCP_TOOL,- tool_description = _CODEX_SUBAGENT_TOOL_DESCRIPTION,+ tool_description = (+ _CODEX_AUTO_ROUTE_TOOL_DESCRIPTION if auto_route else _CODEX_SUBAGENT_TOOL_DESCRIPTION+ ),instructions = _SERVER_INSTRUCTIONS,)diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.pyindex 6413841c08e..cd0b03bf42f 100644--- a/unsloth_cli/commands/start.py+++ b/unsloth_cli/commands/start.py@@ -88,6 +88,55 @@ _SUBAGENT_DESCRIPTION = ("Local coding subagent powered by Unsloth for debugging, implementation, and codebase ""research. Use when the user asks to spawn an Unsloth or local agent.")+_AUTO_ROUTE_DESCRIPTION = (+ "Local coding subagent powered by Unsloth. In this session it is the only way to reach "+ "files and the shell: {blocked}. "+ "Give it the complete task in one message (codebase search, reading or summarizing files, "+ "running tests or commands, mechanical edits with a clear spec) and review its result "+ "before answering. Keep talking with the user and planning and design decisions to "+ "yourself."+)+_SUBAGENT_AUTO_ROUTE_DESCRIPTION = _AUTO_ROUTE_DESCRIPTION.format(+ blocked = (+ "your own Read, Grep, Glob, Bash, PowerShell, Monitor, NotebookRead and Agent calls "+ "are blocked"+ )+)+# Without tools of its own the parent cannot check a small model's answer except by asking for the evidence.+_AUTO_ROUTE_VERIFY = (+ " It is a small local model and can be wrong: ask it for the raw command output behind an "+ "answer you rely on, such as a search that found nothing or an edit, and say so if you "+ "cannot confirm it."+)+_AUTO_ROUTE_CHECK = (+ _AUTO_ROUTE_VERIFY + " If it fails, tell the user plainly; you cannot do the step yourself."+)+_OPENCODE_AUTO_ROUTE_DESCRIPTION = (+ _AUTO_ROUTE_DESCRIPTION.format(+ blocked = "your own read, grep, glob, list, lsp, bash and edit tools are blocked"+ )+ + _AUTO_ROUTE_VERIFY+ + " If it fails, do that step with your own read and bash if they work, or else tell the "+ "user plainly that it was not done."+)+_OPENCODE_PLAN_SUBAGENT_NAME = "unsloth-plan"+_OPENCODE_AUTO_ROUTE_PLAN_DESCRIPTION = (+ "Read-only local coding subagent powered by Unsloth for planning and codebase research. "+ "In plan mode it is the only way to read files: your own read, grep, glob, list, lsp and "+ "bash tools are blocked. Give it the complete question in one message."+)+_OPENCODE_HIDDEN_TOOLS = ("grep", "glob", "list", "lsp")+# OpenCode's free tier refuses a request without read or bash, so on V1 the route plugin blocks their calls instead of a permission rule removing them.+_OPENCODE_ROUTED_TOOLS = ("read", "bash")+_OPENCODE_ROUTE_PLUGIN = "unsloth-auto-route.js"+_SUBAGENT_AUTO_ROUTE_INSTRUCTIONS = (+ "Files and the shell in this session are reachable only through the unsloth_agent tool; "+ "your own Read, Grep, Glob, Bash, PowerShell, Monitor, NotebookRead and Agent calls are "+ "blocked by a hook. Give the "+ "tool the complete task in one message, with the paths and commands it needs, and review "+ "its result before answering. Keep talking with the user and planning and design "+ "decisions to yourself. In plan mode call unsloth_plan_agent instead."+)_SUBAGENT_INSTRUCTIONS = ("You are a local coding subagent powered by Unsloth. Complete the assigned task directly, ""use the available tools when useful, verify your work, and return a concise result to the "@@ -104,6 +153,9 @@ _SUBAGENT_PLAN_INSTRUCTIONS = ()_CLAUDE_SUBAGENT_MCP_MODULE = "unsloth_cli.claude_subagent_mcp"_CLAUDE_SUBAGENT_SETTINGS_ENV = "UNSLOTH_CLAUDE_SUBAGENT_SETTINGS"+_CLAUDE_SUBAGENT_AUTO_ROUTE_ENV = "UNSLOTH_CLAUDE_SUBAGENT_AUTO_ROUTE"+_CLAUDE_SUBAGENT_FALLBACK_ENV = "UNSLOTH_CLAUDE_SUBAGENT_FALLBACK"+_CLAUDE_ROUTE_FALLBACK_FILE = "local-agent-failed"_CLAUDE_SUBAGENT_TOOL = "mcp__plugin_unsloth-local-agent_unsloth__unsloth_agent"_CLAUDE_SUBAGENT_PLAN_TOOL = "mcp__plugin_unsloth-local-agent_unsloth__unsloth_plan_agent"_CODEX_SUBAGENT_MCP_MODULE = "unsloth_cli.codex_subagent_mcp"@@ -123,6 +175,21 @@ _CODEX_SUBAGENT_ROUTING_INSTRUCTIONS = ("result, call wait, or use a built-in subagent before calling the tool. Use built-in ""subagents for other delegation requests.")+_CODEX_AUTO_ROUTE_TOOL_DESCRIPTION = (+ _AUTO_ROUTE_DESCRIPTION.format(blocked = "your own shell is disabled") + _AUTO_ROUTE_CHECK+)+_CODEX_AUTO_ROUTE_INSTRUCTIONS = (+ "Your own shell is disabled in this session, so files and commands are reachable only "+ "through the spawn_local_agent MCP tool. Call it without being asked for codebase search, "+ "reading or summarizing files, running tests or commands, and mechanical edits, with the "+ "complete task in one message, and review its result before answering. Keep talking with "+ "the user and planning and design decisions to yourself." + _AUTO_ROUTE_CHECK+)+_CODEX_AUTO_ROUTE_FLAGS = [+ arg+ for feature in ("shell_tool", "multi_agent", "view_image")+ for arg in ("-c", f"features.{feature}=false")+]_PI_SUBAGENT_EXTENSION = Path(__file__).parent.parent / "pi_subagent.ts"_PI_USER_RESOURCE_DIRS = ("extensions", "skills", "prompts", "themes", "npm", "git")_PI_USER_RESOURCE_SETTINGS = ("packages", "extensions", "skills", "prompts", "themes")@@ -396,6 +463,13 @@ _AS_SUBAGENT_OPTION = typer.Option(rich_help_panel = _PANEL_SESSION,help = "Keep the coding agent's current model and add Unsloth as a local subagent.",)+_AUTO_ROUTE_OPTION = typer.Option(+ False,+ "--auto-route",+ rich_help_panel = _PANEL_SESSION,+ help = "Keep the agent's current model and let it hand routine, self-contained work to a "+ "local Unsloth subagent without being asked.",+)_APP_OPTION = typer.Option(False,"--app",@@ -875,6 +949,12 @@ def _reject_as_subagent(agent: str, args: list) -> None:# Reject early, or the flag reaches the agent binary after Unsloth loaded the model.if any(arg == "--as-subagent" or arg.startswith("--as-subagent=") for arg in args):_fail(f"--as-subagent is not supported for {agent}.")+ _reject_auto_route(agent, args)+++def _reject_auto_route(agent: str, args: list) -> None:+ if any(arg == "--auto-route" or arg.startswith("--auto-route=") for arg in args):+ _fail(f"--auto-route is not supported for {agent}.")def _http_error_detail(exc: urllib.error.HTTPError) -> str:@@ -3249,6 +3329,7 @@ def write_codex_subagent_bridge(*,yolo: bool,reasoning_effort: Optional[str] = None,+ auto_route: bool = False,) -> Path:"""Write private config for an explicit local Codex child launched through MCP."""child_home = home / "child"@@ -3260,6 +3341,7 @@ def write_codex_subagent_bridge("api_key": key,"codex_home": str(child_home),"bypass_permissions": yolo,+ **({"auto_route": True} if auto_route else {}),},)return path@@ -3381,7 +3463,7 @@ def _create_directory_junction(source: Path, target: Path) -> bool:return result.returncode == 0-def write_codex_parent_overlay(overlay: Path) -> Path:+def write_codex_parent_overlay(overlay: Path, auto_route: bool = False) -> Path:"""Add local-agent routing without replacing the cloud parent's configuration."""overlay.mkdir(parents = True, exist_ok = True, mode = 0o700)@@ -3468,6 +3550,8 @@ def write_codex_parent_overlay(overlay: Path) -> Path:if other.is_file() or other.is_symlink():other.unlink()routing = _CODEX_SUBAGENT_ROUTING_INSTRUCTIONS+ if auto_route:+ routing = f"{routing}\n\n{_CODEX_AUTO_ROUTE_INSTRUCTIONS}"combined = f"{inherited}\n\n{routing}\n" if inherited else f"{routing}\n"_write_private_text(overlay / instruction_name, combined)return overlay@@ -3478,11 +3562,49 @@ def _agent_config_path(path: Path, command: list) -> str:return _wsl_windows_path(path) if _wsl_windows_executable(command) else str(path)+_OPENCODE_ROUTE_PLUGIN_SCRIPT = """\+const LOCAL = new Set(%(local)s);+const ROUTED = new Set(%(routed)s);+const HIDDEN = new Set(["title", "summary", "compaction"]);+const agents = new Map();+// Set when a local run fails, so the parent can do that step itself until the next local run succeeds.+let failed = false;++export const UnslothAutoRoute = async () => ({+ "chat.params": async ({ sessionID, agent }) => {+ if (!HIDDEN.has(agent)) agents.set(sessionID, agent);+ },+ event: async ({ event }) => {+ const { sessionID, error } = event.properties ?? {};+ if (event.type === "session.error" && LOCAL.has(agents.get(sessionID)) && error?.name !== "MessageAbortedError") failed = true;+ },+ "tool.execute.after": async ({ tool, args }) => {+ if (tool === "task" && LOCAL.has(args?.subagent_type)) failed = false;+ },+ "tool.execute.before": async ({ tool, sessionID }) => {+ const agent = agents.get(sessionID);+ if (failed || !ROUTED.has(tool) || LOCAL.has(agent)) return;+ throw new Error(+ "Blocked by Unsloth --auto-route: files and the shell are only reachable through the local " ++ "agent. Hand the complete task to the @" + (agent === "plan" ? %(plan)s : %(build)s) ++ " subagent with the task tool instead.",+ );+ },+});+""" % {+ "local": json.dumps([_SUBAGENT_NAME, _OPENCODE_PLAN_SUBAGENT_NAME]),+ "routed": json.dumps(list(_OPENCODE_ROUTED_TOOLS)),+ "plan": json.dumps(_OPENCODE_PLAN_SUBAGENT_NAME),+ "build": json.dumps(_SUBAGENT_NAME),+}++def _opencode_subagent_inline_config(path: Path,permission: dict,command: str = "opencode",v2: bool = False,+ auto_route: bool = False,) -> dict:"""Keep the local provider visible without hiding the parent's allowed providers."""inline: dict = {}@@ -3570,6 +3692,42 @@ def _opencode_subagent_inline_config()if permission:inline["permission"] = permission+ plugin = path.parent / _OPENCODE_ROUTE_PLUGIN+ if auto_route and not v2:+ _write_private_text(plugin, _OPENCODE_ROUTE_PLUGIN_SCRIPT)+ # OpenCode adds each layer's plugins to the others', so only an inherited inline list needs keeping.+ plugins = inline.get("plugin")+ inline["plugin"] = [+ *(plugins if isinstance(plugins, list) else []),+ _agent_config_path(plugin, [command]),+ ]+ else:+ # A persisted session dir may still hold the plugin from an earlier --auto-route run.+ plugin.unlink(missing_ok = True)+ if auto_route:+ # The V2 CLI has no tool hooks, so there read and bash fall back to permission rules.+ denied = _OPENCODE_HIDDEN_TOOLS + (_OPENCODE_ROUTED_TOOLS if v2 else ())+ permission = {+ **dict.fromkeys((*denied, "edit"), "deny"),+ "task": {"*": "deny", _SUBAGENT_NAME: "allow"},+ }+ # Plan keeps its own edit rules (it may write only its plan file) and reaches the read-only agent.+ plan_permission = {+ **dict.fromkeys(denied, "deny"),+ "task": {"*": "deny", _OPENCODE_PLAN_SUBAGENT_NAME: "allow"},+ }+ # An agent's own permission outranks the global one, so restrict by name every agent a user can be in (an @mention skips the task rule).+ agents = _subdict(inline, "agent")+ configured = effective.get("agent")+ names = {+ "build",+ "general",+ "explore",+ *(configured if isinstance(configured, dict) else ()),+ }+ for name in names - {"plan", _SUBAGENT_NAME, _OPENCODE_PLAN_SUBAGENT_NAME}:+ _subdict(_subdict(agents, name), "permission").update(permission)+ _subdict(_subdict(agents, "plan"), "permission").update(plan_permission)return inline@@ -3598,6 +3756,39 @@ if mode == "plan":sys.exit(0)'''+_CLAUDE_ROUTE_GATE_SCRIPT = """\+import json, os, sys++# The local agent server leaves this file after a failed run, so the parent can do that step itself.+if os.path.exists(os.path.join(os.path.dirname(__file__), "local-agent-failed")):+ sys.exit(0)+print(json.dumps({"hookSpecificOutput": {+ "hookEventName": "PreToolUse",+ "permissionDecision": "deny",+ "permissionDecisionReason": (+ "Blocked by Unsloth --auto-route: files and the shell are only reachable through "+ "the local agent. Call the unsloth_agent tool with the complete task instead."+ ),+}}))+sys.exit(0)+"""+# PowerShell is the shell on Windows without Git Bash, Monitor runs commands too, and Agent (Task before Claude Code 2) would hand the same work to a cloud subagent.+_CLAUDE_ROUTE_GATE_MATCHER = "Read|Grep|Glob|Bash|PowerShell|Monitor|NotebookRead|Agent|Task"+++def _claude_hook(gate: Path) -> dict:+ return {+ "type": "command",+ # Run through runpy rather than handing the path to the interpreter: a missing gate is then an ordinary traceback (exit 1, fails open) instead of exit 2, which Claude treats as a blocking error and would deny the tool in every mode. The path is base64'd because this string goes through a shell: a temp root holding $(..) or a backtick expands under sh, %VAR% under cmd, and the gate then silently fails open. base64's alphabet has no metacharacter in either.+ "command": (+ f'"{sys.executable}" -c '+ f'"import base64,runpy; runpy.run_path('+ f"base64.b64decode('{_b64_path(gate)}').decode())\""+ ),+ # A hook with no timeout stalls the parent for as long as it hangs; measured unbounded past 400s.+ "timeout": 10,+ }+def write_claude_subagent_plugin(path: Path, server_env: dict) -> Path:"""Write a session plugin that exposes the local Claude child through MCP."""@@ -3637,6 +3828,10 @@ def write_claude_subagent_plugin(path: Path, server_env: dict) -> Path:*([_CLAUDE_SUBAGENT_SETTINGS_ENV] if base and key and model_id else []),),)+ auto_route = server_env.get(_CLAUDE_SUBAGENT_AUTO_ROUTE_ENV) == "1"+ fallback = plugin / "hooks" / _CLAUDE_ROUTE_FALLBACK_FILE+ if auto_route and command != "wsl.exe":+ mcp_env[_CLAUDE_SUBAGENT_FALLBACK_ENV] = str(fallback)_write_private_json(plugin / ".claude-plugin" / "plugin.json",{@@ -3661,43 +3856,35 @@ def write_claude_subagent_plugin(path: Path, server_env: dict) -> Path:)# Claude already refuses the editing tool in plan mode, since it advertises readOnlyHint false. This PreToolUse hook replaces that dead end with a reason naming the read-only tool to call instead. Skipped under the WSL bridge, where the gate is a Linux path but the hook would run beside the Windows claude.gate = plugin / "hooks" / "plan_gate.py"+ route_gate = plugin / "hooks" / "route_gate.py"+ # A persisted plugin dir may still hold gates, or a failure left by an earlier session.+ fallback.unlink(missing_ok = True)+ if command == "wsl.exe" or not auto_route:+ route_gate.unlink(missing_ok = True)if command == "wsl.exe":- # A persisted plugin dir may still hold a gate from an earlier non-WSL run.for stale in (gate, plugin / "hooks" / "hooks.json"):stale.unlink(missing_ok = True)else:_write_private_text(gate, _CLAUDE_PLAN_GATE_SCRIPT)- _write_private_json(- plugin / "hooks" / "hooks.json",- {- "hooks": {- "PreToolUse": [- {- "matcher": _CLAUDE_SUBAGENT_TOOL,- "hooks": [- {- "type": "command",- # Run through runpy rather than handing the path to the interpreter: a missing gate is then an ordinary traceback (exit 1, fails open) instead of exit 2, which Claude treats as a blocking error and would deny the tool in every mode. The path is base64'd because this string goes through a shell: a temp root holding $(..) or a backtick expands under sh, %VAR% under cmd, and the gate then silently fails open. base64's alphabet has no metacharacter in either.- "command": (- f'"{sys.executable}" -c '- f'"import base64,runpy; runpy.run_path('- f"base64.b64decode('{_b64_path(gate)}').decode())\""- ),- # A hook with no timeout stalls the parent for as long as it hangs; measured unbounded past 400s.- "timeout": 10,- }- ],- }- ]- }- },- )+ entries = [{"matcher": _CLAUDE_SUBAGENT_TOOL, "hooks": [_claude_hook(gate)]}]+ if auto_route:+ _write_private_text(route_gate, _CLAUDE_ROUTE_GATE_SCRIPT)+ entries.append(+ {"matcher": _CLAUDE_ROUTE_GATE_MATCHER, "hooks": [_claude_hook(route_gate)]}+ )+ _write_private_json(plugin / "hooks" / "hooks.json", {"hooks": {"PreToolUse": entries}})skill = plugin / "skills" / "local-agent" / "SKILL.md"skill.parent.mkdir(parents = True, exist_ok = True, mode = 0o700)+ when = (+ "Use it for routine, self-contained work (codebase search, reading files, running "+ "tests or commands, mechanical edits) without being asked, and whenever the user asks "+ "for an Unsloth or local agent."+ if auto_route+ else "Use when the user asks to spawn an Unsloth agent or local agent."+ )skill.write_text("---\n"- "description: Delegate a task to the local agent powered by Unsloth. Use when the "- "user asks to spawn an Unsloth agent or local agent.\n"+ f"description: Delegate a task to the local agent powered by Unsloth. {when}\n""---\n\n""Call the Unsloth local agent tool once with the complete task. In plan mode, call ""the read-only Unsloth plan agent instead. Return its result to the user without "@@ -6365,10 +6552,15 @@ def claude(yolo: bool = _YOLO_OPTION,persist: bool = _PERSIST_OPTION,as_subagent: bool = _AS_SUBAGENT_OPTION,+ auto_route: bool = _AUTO_ROUTE_OPTION,):"""Point Claude Code at the running Unsloth server and start it."""# Route a leading `org/name` positional to --model; forward the rest to the agent.model, ctx.args[:] = _consume_positional_model(model, ctx.args)+ # The route gate is a hook the Windows claude cannot run from WSL, so its own tools would stay on.+ if auto_route and _wsl_windows_executable(["claude"]):+ _fail("--auto-route needs claude installed inside WSL, not the Windows claude.")+ as_subagent = as_subagent or auto_routeinstall_hint = ("irm https://claude.ai/install.ps1 | iex"if os.name == "nt"@@ -6423,6 +6615,8 @@ def claude(server_env["UNSLOTH_CLAUDE_SUBAGENT_CONTEXT_WINDOW"] = str(int(window))if server_options.request_body():server_env["CLAUDE_CODE_EXTRA_BODY"] = json.dumps(server_options.request_body())+ if auto_route:+ server_env[_CLAUDE_SUBAGENT_AUTO_ROUTE_ENV] = "1"with _session_config("claude-subagent", launch, persist = persist) as config:plugin = write_claude_subagent_plugin(config, server_env)command = [@@ -6436,7 +6630,11 @@ def claude(]typer.echo("Unsloth is available as a local agent. "- "Ask Claude to spawn an Unsloth or local agent."+ + (+ "Claude hands routine work to it on its own."+ if auto_route+ else "Ask Claude to spawn an Unsloth or local agent."+ ))_run(base,@@ -6495,11 +6693,13 @@ def codex(yolo: bool = _YOLO_OPTION,persist: bool = _PERSIST_OPTION,as_subagent: bool = _AS_SUBAGENT_OPTION,+ auto_route: bool = _AUTO_ROUTE_OPTION,app: bool = _CODEX_APP_OPTION,):"""Point OpenAI Codex at the running Unsloth server and start it."""# Route a leading `org/name` positional to --model; forward the rest to the agent.model, ctx.args[:] = _consume_positional_model(model, ctx.args)+ as_subagent = as_subagent or auto_route_check_app_flags(app, ctx.args, as_subagent)running = _recover_codex_app()if app and running is not None:@@ -6559,17 +6759,23 @@ def codex(home,yolo = yolo,reasoning_effort = codex_effort,+ auto_route = auto_route,)- parent_home = write_codex_parent_overlay(home / "parent")+ parent_home = write_codex_parent_overlay(home / "parent", auto_route = auto_route)command = ["codex",*_codex_subagent_flags(bridge_config),+ *(_CODEX_AUTO_ROUTE_FLAGS if auto_route else []),*_yolo_command_flags("codex", yolo),*ctx.args,]typer.echo("Unsloth is available as a local agent. "- "Ask Codex to spawn an Unsloth or local agent."+ + (+ "Codex hands routine work to it on its own."+ if auto_route+ else "Ask Codex to spawn an Unsloth or local agent."+ ))_run(base,@@ -6732,11 +6938,13 @@ def opencode(yolo: bool = _YOLO_OPTION,persist: bool = _PERSIST_OPTION,as_subagent: bool = _AS_SUBAGENT_OPTION,+ auto_route: bool = _AUTO_ROUTE_OPTION,app: bool = _APP_OPTION,):"""Point OpenCode at the running Unsloth server and start it."""# Route a leading `org/name` positional to --model; forward the rest to the agent.model, ctx.args[:] = _consume_positional_model(model, ctx.args)+ as_subagent = as_subagent or auto_route_check_app_flags(app, ctx.args, as_subagent)command_name, opencode_v2 = _opencode_command()install_hint = _npm_install_hint("@opencode-ai/cli@beta" if opencode_v2 else "opencode-ai")@@ -6810,16 +7018,32 @@ def opencode(session_permission,command = command_name,v2 = opencode_v2,+ auto_route = auto_route,)# A project opencode.json outranks the session file and could field-merge its own agent.unsloth over ours. Pin ours in the inline overlay so it wins.- inline_config.setdefault("agent", {})[_SUBAGENT_NAME] = {- "description": _SUBAGENT_DESCRIPTION,+ agents = inline_config.setdefault("agent", {})+ agents[_SUBAGENT_NAME] = {+ "description": (+ _OPENCODE_AUTO_ROUTE_DESCRIPTION if auto_route else _SUBAGENT_DESCRIPTION+ ),"mode": "subagent","model": f"{_OPENCODE_PROVIDER}/{subagent_model['id']}","prompt": _SUBAGENT_INSTRUCTIONS,}+ if auto_route:+ # A task subagent does not inherit the parent agent's rules, so both keep their tools.+ agents[_OPENCODE_PLAN_SUBAGENT_NAME] = {+ "description": _OPENCODE_AUTO_ROUTE_PLAN_DESCRIPTION,+ "mode": "subagent",+ "model": f"{_OPENCODE_PROVIDER}/{subagent_model['id']}",+ "prompt": _SUBAGENT_PLAN_INSTRUCTIONS,+ "permission": {"edit": "deny", "bash": "deny"},+ }env["OPENCODE_CONFIG_CONTENT"] = json.dumps(inline_config)- typer.echo("Unsloth is available as @unsloth and in /models.")+ typer.echo(+ "Unsloth is available as @unsloth and in /models."+ + (" OpenCode hands routine work to it on its own." if auto_route else "")+ )_run(base,subagent_model,@@ -6997,6 +7221,7 @@ def pi("""Point Pi (coding agent) at the running Unsloth server and start it."""# Route a leading `org/name` positional to --model; forward the rest to the agent.model, ctx.args[:] = _consume_positional_model(model, ctx.args)+ _reject_auto_route("pi", ctx.args)install_hint = _npm_install_hint("@earendil-works/pi-coding-agent",ignore_scripts = True,diff --git a/unsloth_cli/tests/test_claude_subagent_mcp.py b/unsloth_cli/tests/test_claude_subagent_mcp.pyindex c81fd65bd0b..a39b4a4fb89 100644--- a/unsloth_cli/tests/test_claude_subagent_mcp.py+++ b/unsloth_cli/tests/test_claude_subagent_mcp.py@@ -8,6 +8,7 @@ import jsonimport osimport subprocessimport sys+import threadingimport timeimport pytest@@ -53,6 +54,74 @@ def test_protocol_lists_and_calls_local_agent():}+def test_main_advertises_the_routing_rule_only_with_auto_route(monkeypatch):+ captured = {}+ monkeypatch.setattr(bridge, "serve", lambda **kwargs: captured.update(kwargs))+ monkeypatch.delenv("UNSLOTH_CLAUDE_SUBAGENT_AUTO_ROUTE", raising = False)+ bridge.main()+ assert captured.get("tool_description") is None+ assert captured.get("instructions") is None++ monkeypatch.setenv("UNSLOTH_CLAUDE_SUBAGENT_AUTO_ROUTE", "1")+ bridge.main()+ initialized = bridge._response(+ {"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {}},+ instructions = captured.get("instructions"),+ )+ assert "unsloth_agent tool" in initialized["result"]["instructions"]+ assert "NotebookRead and Agent calls are blocked" in initialized["result"]["instructions"]+ listed = bridge._response(+ {"jsonrpc": "2.0", "id": 1, "method": "tools/list"},+ tool_description = captured.get("tool_description"),+ run_read_only_agent = lambda task: task,+ read_only_tool_name = captured["read_only_tool_name"],+ )+ tools = {tool["name"]: tool["description"] for tool in listed["result"]["tools"]}+ assert "calls are blocked" in tools["unsloth_agent"]+ assert "codebase search" in tools["unsloth_agent"]+ assert tools["unsloth_plan_agent"] == bridge._SUBAGENT_PLAN_DESCRIPTION+++def _failing_agent(message):+ def run(*args, **kwargs):+ raise RuntimeError(message)++ return run+++def test_failed_local_run_unblocks_the_parent_until_the_next_success(tmp_path):+ marker = tmp_path / "local-agent-failed"+ run = bridge._with_fallback(_failing_agent("Connection refused"), str(marker))+ with pytest.raises(RuntimeError) as failure:+ run("task", threading.Event())+ assert "Connection refused" in str(failure.value)+ assert "unblocked" in str(failure.value)+ assert marker.exists()+ succeed = bridge._with_fallback(lambda task, event: "LOCAL_OK", str(marker))+ assert succeed("task", threading.Event()) == "LOCAL_OK"+ assert not marker.exists()++ cancelled = threading.Event()+ cancelled.set()+ with pytest.raises(RuntimeError, match = "cancelled"):+ bridge._with_fallback(_failing_agent("cancelled"), str(marker))("task", cancelled)+ assert not marker.exists()+++def test_main_wraps_both_tools_only_with_auto_route(monkeypatch, tmp_path):+ captured = {}+ monkeypatch.setattr(bridge, "serve", lambda **kwargs: captured.update(kwargs))+ monkeypatch.delenv(bridge._CLAUDE_SUBAGENT_FALLBACK_ENV, raising = False)+ bridge.main()+ assert captured["run_agent"] is bridge.run_local_agent+ monkeypatch.setenv(bridge._CLAUDE_SUBAGENT_FALLBACK_ENV, str(tmp_path / "local-agent-failed"))+ monkeypatch.setattr(bridge, "run_local_agent", _failing_agent("down"))+ bridge.main()+ for name in ("run_agent", "run_read_only_agent"):+ with pytest.raises(RuntimeError, match = "unblocked"):+ captured[name]("task", threading.Event())++def test_protocol_exposes_read_only_agent_for_claude_plan_mode():listed = bridge._response({"jsonrpc": "2.0", "id": 1, "method": "tools/list"},diff --git a/unsloth_cli/tests/test_codex_subagent_mcp.py b/unsloth_cli/tests/test_codex_subagent_mcp.pyindex 0c724e16a9e..1af5f2b72df 100644--- a/unsloth_cli/tests/test_codex_subagent_mcp.py+++ b/unsloth_cli/tests/test_codex_subagent_mcp.py@@ -7,6 +7,7 @@ import ioimport jsonimport osimport subprocess+import threadingimport pytest@@ -27,6 +28,48 @@ def _write_config(tmp_path, *, bypass_permissions = False):return path[email protected]("auto_route", [None, True])+def test_main_describes_the_tool_for_auto_route(tmp_path, monkeypatch, auto_route):+ path = _write_config(tmp_path)+ if auto_route:+ path.write_text(json.dumps({**json.loads(path.read_text()), "auto_route": True}))+ captured = {}+ monkeypatch.setattr(bridge, "serve", lambda **kwargs: captured.update(kwargs))+ monkeypatch.setattr(bridge.sys, "argv", ["bridge", str(path)])+ monkeypatch.delenv(bridge._CODEX_SUBAGENT_CONFIG_ENV, raising = False)+ bridge.main()+ expected = (+ bridge._CODEX_AUTO_ROUTE_TOOL_DESCRIPTION+ if auto_route+ else bridge._CODEX_SUBAGENT_TOOL_DESCRIPTION+ )+ assert captured["tool_description"] == expected++[email protected]("auto_route", [None, True])+def test_auto_route_failure_says_the_step_was_not_done(tmp_path, monkeypatch, auto_route):+ path = _write_config(tmp_path)+ if auto_route:+ path.write_text(json.dumps({**json.loads(path.read_text()), "auto_route": True}))+ captured = {}+ monkeypatch.setattr(bridge, "serve", lambda **kwargs: captured.update(kwargs))+ monkeypatch.setattr(bridge.sys, "argv", ["bridge", str(path)])++ def fail(+ task,+ cancel_event = None,+ **kwargs,+ ):+ raise RuntimeError("Connection refused")++ monkeypatch.setattr(bridge, "run_local_agent", fail)+ bridge.main()+ with pytest.raises(RuntimeError) as failure:+ captured["run_agent"]("task", threading.Event())+ assert "Connection refused" in str(failure.value)+ assert ("was not done" in str(failure.value)) is bool(auto_route)++def test_protocol_uses_codex_specific_tool_name():requests = "\n".join([@@ -128,10 +171,12 @@ def test_local_child_uses_explicit_unsloth_profile(assert bridge.run_local_agent("reply exactly LOCAL_OK") == "LOCAL_OK"command = captured["command"]assert command[:4] == ["/usr/local/bin/codex", "--oss", "--profile", "unsloth_api"]+ # A refused connection to the local server must fail the run, not wait for the network forever.+ assert command[4:6] == ["-c", "features.unbounded_connection_retries=false"]if bypass_permissions:assert "--dangerously-bypass-approvals-and-sandbox" in commandelse:- assert command[4:8] == ["--sandbox", "workspace-write", "--ask-for-approval", "never"]+ assert command[6:10] == ["--sandbox", "workspace-write", "--ask-for-approval", "never"]assert command[command.index("exec") + 1 : command.index("exec") + 4] == ["--ephemeral","--json",@@ -197,6 +242,58 @@ def test_local_child_prioritizes_failed_turn_over_progress():bridge._result_text(output)+def test_auto_route_result_shows_the_last_command_the_child_ran():+ events = [+ {+ "type": "item.completed",+ "item": {+ "type": "command_execution",+ "command": "sed -i 's/\\d{3}/555/' about.txt && cat about.txt",+ "aggregated_output": "Office phone: 555-0147\n",+ "exit_code": 0,+ },+ },+ {+ "type": "item.completed",+ "item": {"type": "agent_message", "text": "Updated to 555-0199."},+ },+ ]+ output = "\n".join(json.dumps(event) for event in events)+ assert bridge._result_text(output) == "Updated to 555-0199."+ shown = bridge._result_text(output, show_last_command = True)+ assert shown.startswith("Updated to 555-0199.")+ assert "Office phone: 555-0147" in shown+ assert "cat about.txt" in shown+++def test_failed_child_reports_its_last_error_not_its_banner(monkeypatch, tmp_path):+ config = _write_config(tmp_path)+ monkeypatch.setenv(bridge._CODEX_SUBAGENT_CONFIG_ENV, str(config))+ monkeypatch.setattr(bridge.shutil, "which", lambda _: "/usr/local/bin/codex")+ reason = "stream disconnected before completion: error sending request"++ class Process:+ pid = 1234+ returncode = 1++ def communicate(self, timeout):+ events = [+ {"type": "turn.started"},+ {"type": "turn.failed", "error": {"message": reason}},+ ]+ return "\n".join(+ json.dumps(event) for event in events+ ), "Reading additional input from stdin...\n"++ def poll(self):+ return self.returncode++ monkeypatch.setattr(bridge.subprocess, "Popen", lambda *args, **kwargs: Process())+ with pytest.raises(RuntimeError) as failure:+ bridge.run_local_agent("hello")+ assert str(failure.value) == reason++def test_local_child_process_is_stopped_on_cancellation(monkeypatch, tmp_path):config = _write_config(tmp_path)monkeypatch.setenv(bridge._CODEX_SUBAGENT_CONFIG_ENV, str(config))diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.pyindex 3c8566d5fa1..e0591ff00ce 100644--- a/unsloth_cli/tests/test_start.py+++ b/unsloth_cli/tests/test_start.py@@ -14,6 +14,7 @@ import reimport shleximport shutilimport signal+import subprocessimport sysimport threadingimport time@@ -1361,6 +1362,14 @@ def test_unsupported_agents_reject_as_subagent(agent, flag):assert f"--as-subagent is not supported for {agent}." in result.output[email protected]("agent", ["openclaw", "hermes", "dsh", "vibe"])[email protected]("flag", ["--auto-route", "--auto-route=true"])+def test_unsupported_agents_reject_auto_route(agent, flag):+ result = CliRunner().invoke(start.start_app, [agent, flag])+ assert result.exit_code == 1+ assert f"--auto-route is not supported for {agent}." in result.output++@pytest.mark.parametrize("agent", ["claude", "codex", "openclaw", "opencode", "hermes", "pi", "dsh", "vibe"])@@ -1809,6 +1818,301 @@ def test_connect_claude_as_subagent_preserves_cloud_parent(fake_studio, tmp_pathassert "Ask Claude to spawn an Unsloth or local agent." in result.output+def test_claude_auto_route_tells_the_parent_to_delegate_routine_work(fake_studio, tmp_path):+ result = CliRunner().invoke(+ start.start_app,+ ["claude", "--as-subagent", "--auto-route", "--no-launch", "hello"],+ )+ assert result.exit_code == 0, result.output+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ assert _launch_command(result.output) == [+ "claude",+ "--plugin-dir",+ str(plugin),+ f"--allowedTools={start._CLAUDE_SUBAGENT_TOOL},{start._CLAUDE_SUBAGENT_PLAN_TOOL}",+ "hello",+ ]+ mcp = json.loads((plugin / ".mcp.json").read_text())["mcpServers"]["unsloth"]+ assert mcp["env"][start._CLAUDE_SUBAGENT_AUTO_ROUTE_ENV] == "1"+ skill = (plugin / "skills" / "local-agent" / "SKILL.md").read_text()+ assert "without being asked" in skill+ assert "Use when the user asks" not in skill+ assert "Claude hands routine work to it on its own." in result.output+++def test_claude_auto_route_alone_adds_the_local_subagent(fake_studio, tmp_path):+ result = CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"])+ assert result.exit_code == 0, result.output+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ command = _launch_command(result.output)+ assert command[:3] == ["claude", "--plugin-dir", str(plugin)]+ assert "--model" not in command+ mcp = json.loads((plugin / ".mcp.json").read_text())["mcpServers"]["unsloth"]+ assert mcp["env"][start._CLAUDE_SUBAGENT_AUTO_ROUTE_ENV] == "1"+ assert "Claude hands routine work to it on its own." in result.output+++def test_claude_auto_route_blocks_the_parents_own_file_and_shell_tools(fake_studio, tmp_path):+ result = CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"])+ assert result.exit_code == 0, result.output+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ plan_gate, route_gate = json.loads((plugin / "hooks" / "hooks.json").read_text())["hooks"][+ "PreToolUse"+ ]+ assert plan_gate["matcher"] == start._CLAUDE_SUBAGENT_TOOL+ assert route_gate["matcher"] == "Read|Grep|Glob|Bash|PowerShell|Monitor|NotebookRead|Agent|Task"+ [hook] = route_gate["hooks"]+ assert hook["type"] == "command"+ assert start._b64_path(plugin / "hooks" / "route_gate.py") in hook["command"]+ assert 0 < hook["timeout"] <= 30+ payload = json.dumps({"tool_name": "Read", "tool_input": {"file_path": "about.txt"}})+ for run in (+ lambda: subprocess.run(+ [sys.executable, str(plugin / "hooks" / "route_gate.py")],+ input = payload,+ capture_output = True,+ text = True,+ timeout = 30,+ ),+ lambda: subprocess.run(+ hook["command"], input = payload, shell = True, capture_output = True, text = True, timeout = 30+ ),+ ):+ denied = run()+ assert denied.returncode == 0, denied.stderr+ output = json.loads(denied.stdout)["hookSpecificOutput"]+ assert output["hookEventName"] == "PreToolUse"+ assert output["permissionDecision"] == "deny"+ assert "unsloth_agent" in output["permissionDecisionReason"]+ assert "--auto-route" in output["permissionDecisionReason"]+++def test_claude_auto_route_gate_lets_the_parent_work_after_a_local_failure(fake_studio, tmp_path):+ result = CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"])+ assert result.exit_code == 0, result.output+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ marker = plugin / "hooks" / start._CLAUDE_ROUTE_FALLBACK_FILE+ mcp = json.loads((plugin / ".mcp.json").read_text())["mcpServers"]["unsloth"]+ assert mcp["env"][start._CLAUDE_SUBAGENT_FALLBACK_ENV] == str(marker)++ def gate():+ return subprocess.run(+ [sys.executable, str(plugin / "hooks" / "route_gate.py")],+ input = json.dumps({"tool_name": "Read"}),+ capture_output = True,+ text = True,+ timeout = 30,+ )++ assert json.loads(gate().stdout)["hookSpecificOutput"]["permissionDecision"] == "deny"+ marker.touch()+ allowed = gate()+ assert allowed.returncode == 0 and allowed.stdout == ""+++def test_claude_persisted_plugin_drops_auto_route_state_without_the_flag(fake_studio, tmp_path):+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ marker = plugin / "hooks" / start._CLAUDE_ROUTE_FALLBACK_FILE+ assert (+ CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"]).exit_code+ == 0+ )+ marker.touch()+ assert (+ CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"]).exit_code+ == 0+ )+ assert not marker.exists()+ marker.touch()+ result = CliRunner().invoke(start.start_app, ["claude", "--as-subagent", "--no-launch"])+ assert result.exit_code == 0, result.output+ assert sorted(p.name for p in (plugin / "hooks").iterdir()) == ["hooks.json", "plan_gate.py"]+ mcp = json.loads((plugin / ".mcp.json").read_text())["mcpServers"]["unsloth"]+ assert start._CLAUDE_SUBAGENT_FALLBACK_ENV not in mcp["env"]+++def test_claude_as_subagent_without_auto_route_keeps_only_the_plan_gate(fake_studio, tmp_path):+ result = CliRunner().invoke(start.start_app, ["claude", "--as-subagent", "--no-launch"])+ assert result.exit_code == 0, result.output+ plugin = tmp_path / "agents" / "claude-subagent" / "unsloth-local-agent"+ [plan_gate] = json.loads((plugin / "hooks" / "hooks.json").read_text())["hooks"]["PreToolUse"]+ assert plan_gate["matcher"] == start._CLAUDE_SUBAGENT_TOOL+ assert sorted(p.name for p in (plugin / "hooks").iterdir()) == ["hooks.json", "plan_gate.py"]+++def test_claude_auto_route_rejects_the_windows_claude_under_wsl(fake_studio, monkeypatch, tmp_path):+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda command: "/mnt/c/claude.exe")+ result = CliRunner().invoke(start.start_app, ["claude", "--auto-route", "--no-launch"])+ assert result.exit_code == 1+ assert "--auto-route needs claude installed inside WSL" in result.output+ assert not (tmp_path / "agents" / "claude-subagent").exists()++[email protected]("flag", ["--auto-route", "--auto-route=true"])+def test_pi_rejects_auto_route(flag):+ result = CliRunner().invoke(start.start_app, ["pi", "--as-subagent", flag])+ assert result.exit_code == 1+ assert "--auto-route is not supported for pi." in result.output++[email protected]("auto_route", [False, True])+def test_opencode_auto_route_adds_a_read_only_plan_agent(fake_studio, monkeypatch, auto_route):+ captured = {}++ def inline_config(path, permission, **kwargs):+ captured.update(kwargs)+ return {}++ monkeypatch.setattr(start, "_opencode_subagent_inline_config", inline_config)+ flag = "--auto-route" if auto_route else "--as-subagent"+ result = CliRunner().invoke(start.start_app, ["opencode", flag, "--no-launch"])+ assert result.exit_code == 0, result.output+ assert captured["auto_route"] is auto_route+ agents = _opencode_inline_config(result.output)["agent"]+ if not auto_route:+ assert set(agents) == {"unsloth"}+ assert agents["unsloth"]["description"] == start._SUBAGENT_DESCRIPTION+ return+ assert set(agents) == {"unsloth", "unsloth-plan"}+ assert agents["unsloth"]["description"] == start._OPENCODE_AUTO_ROUTE_DESCRIPTION+ assert "permission" not in agents["unsloth"]+ plan = agents["unsloth-plan"]+ assert plan["mode"] == "subagent"+ assert plan["model"] == agents["unsloth"]["model"]+ assert plan["prompt"] == start._SUBAGENT_PLAN_INSTRUCTIONS+ assert plan["permission"] == {"edit": "deny", "bash": "deny"}+ assert "hands routine work to it on its own" in result.output+++def _opencode_effective_config(monkeypatch, effective):+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda name: "/usr/bin/opencode")+ monkeypatch.setattr(+ start.subprocess,+ "run",+ lambda *a, **k: subprocess.CompletedProcess(a, 0, json.dumps(effective), ""),+ )+++def test_opencode_auto_route_restricts_every_agent_the_user_can_be_in(monkeypatch, tmp_path):+ effective = {+ "agent": {+ "reviewer": {"mode": "primary", "permission": {"read": "allow"}},+ "helper": {"mode": "subagent"},+ }+ }+ monkeypatch.delenv("OPENCODE_CONFIG_CONTENT", raising = False)+ _opencode_effective_config(monkeypatch, effective)+ path = tmp_path / "opencode.json"+ plain = start._opencode_subagent_inline_config(path, {})+ assert "agent" not in plain and "plugin" not in plain+ assert not (tmp_path / start._OPENCODE_ROUTE_PLUGIN).exists()+ agents = start._opencode_subagent_inline_config(path, {}, auto_route = True)["agent"]+ assert set(agents) == {"build", "plan", "general", "explore", "reviewer", "helper"}+ for name in ("build", "general", "explore", "reviewer", "helper"):+ permission = agents[name]["permission"]+ for tool in ("grep", "glob", "list", "lsp", "edit"):+ assert permission[tool] == "deny"+ # OpenCode's free tier rejects a request without read or bash, so the plugin blocks them instead.+ assert not {"read", "bash"} & set(permission)+ # Last match wins in OpenCode, so the catch-all deny must come before the allow.+ assert list(permission["task"].items()) == [("*", "deny"), ("unsloth", "allow")]+ plan = agents["plan"]["permission"]+ assert plan["grep"] == plan["lsp"] == "deny"+ assert not {"read", "bash", "edit"} & set(plan)+ assert list(plan["task"].items()) == [("*", "deny"), ("unsloth-plan", "allow")]+++def test_opencode_auto_route_blocks_read_and_bash_with_a_session_plugin(monkeypatch, tmp_path):+ monkeypatch.delenv("OPENCODE_CONFIG_CONTENT", raising = False)+ _opencode_effective_config(monkeypatch, {})+ inline = start._opencode_subagent_inline_config(tmp_path / "opencode.json", {}, auto_route = True)+ plugin = tmp_path / start._OPENCODE_ROUTE_PLUGIN+ assert inline["plugin"] == [str(plugin)]+ script = plugin.read_text()+ assert script == start._OPENCODE_ROUTE_PLUGIN_SCRIPT+ assert 'const ROUTED = new Set(["read", "bash"]);' in script+ assert 'const LOCAL = new Set(["unsloth", "unsloth-plan"]);' in script+ assert '"tool.execute.before"' in script and '"chat.params"' in script+ assert "Hand the complete task to the @" in script+ assert "plugin" not in start._opencode_subagent_inline_config(tmp_path / "opencode.json", {})+ assert not plugin.exists()+++def test_opencode_auto_route_recipe_loads_the_route_plugin(fake_studio, monkeypatch, tmp_path):+ monkeypatch.delenv("OPENCODE_CONFIG_CONTENT", raising = False)+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda name: None)+ plugin = tmp_path / "agents" / "opencode-subagent" / start._OPENCODE_ROUTE_PLUGIN+ result = CliRunner().invoke(start.start_app, ["opencode", "--auto-route", "--no-launch"])+ assert result.exit_code == 0, result.output+ inline = _opencode_inline_config(result.output)+ assert inline["plugin"] == [str(plugin)]+ assert plugin.read_text() == start._OPENCODE_ROUTE_PLUGIN_SCRIPT+ assert "read" not in inline["agent"]["build"]["permission"]+ result = CliRunner().invoke(start.start_app, ["opencode", "--as-subagent", "--no-launch"])+ assert result.exit_code == 0, result.output+ inline = _opencode_inline_config(result.output)+ assert "plugin" not in inline+ assert set(inline["agent"]) == {"unsloth"}+ assert not plugin.exists()+++def test_opencode_auto_route_keeps_the_users_plugins(monkeypatch, tmp_path):+ inherited = {"plugin": ["opencode-wakatime", ["./mine.js", {"level": 2}]]}+ monkeypatch.setenv("OPENCODE_CONFIG_CONTENT", json.dumps(inherited))+ _opencode_effective_config(monkeypatch, {"plugin": ["from-global"]})+ inline = start._opencode_subagent_inline_config(tmp_path / "opencode.json", {}, auto_route = True)+ assert inline["plugin"] == [+ *inherited["plugin"],+ str(tmp_path / start._OPENCODE_ROUTE_PLUGIN),+ ]+++def test_opencode_auto_route_keeps_an_inherited_agent_config(monkeypatch, tmp_path):+ inherited = {"agent": {"build": {"permission": {"webfetch": "ask"}, "steps": 5}}}+ monkeypatch.setenv("OPENCODE_CONFIG_CONTENT", json.dumps(inherited))+ inline = start._opencode_subagent_inline_config(+ tmp_path / "opencode.json", {}, v2 = True, auto_route = True+ )+ build = inline["agent"]["build"]+ assert build["steps"] == 5+ assert build["permission"]["webfetch"] == "ask"+ assert build["permission"]["read"] == build["permission"]["bash"] == "deny"+ assert inline["agent"]["plan"]["permission"]["read"] == "deny"+ assert "plugin" not in inline+ assert not (tmp_path / start._OPENCODE_ROUTE_PLUGIN).exists()++[email protected]("auto_route", [False, True])+def test_codex_auto_route_disables_only_the_parents_shell(+ fake_studio, tmp_path, monkeypatch, auto_route+):+ monkeypatch.setattr(start, "_codex_supports_model_catalog", lambda: True)+ source_home = tmp_path / "user-codex"+ source_home.mkdir()+ monkeypatch.setenv("CODEX_HOME", str(source_home))+ flag = "--auto-route" if auto_route else "--as-subagent"+ result = CliRunner().invoke(start.start_app, ["codex", flag, "--no-launch"])+ assert result.exit_code == 0, result.output+ command = _launch_command(result.output)+ home = tmp_path / "agents" / "codex-subagent"+ bridge = json.loads((home / "subagent.json").read_text())+ instructions = (home / "parent" / "AGENTS.md").read_text()+ child_profile = (home / "child" / f"{start._CODEX_PROFILE}.config.toml").read_text()+ assert "shell_tool" not in child_profile+ assert start._CODEX_SUBAGENT_ROUTING_INSTRUCTIONS in instructions+ if not auto_route:+ assert not any(value.startswith("features.") for value in command)+ assert "auto_route" not in bridge+ assert start._CODEX_AUTO_ROUTE_INSTRUCTIONS not in instructions+ return+ features = [command[i + 1] for i, value in enumerate(command) if value == "-c"]+ for feature in ("shell_tool", "multi_agent", "view_image"):+ assert f"features.{feature}=false" in features+ assert bridge["auto_route"] is True+ assert start._CODEX_AUTO_ROUTE_INSTRUCTIONS in instructions+ assert "Codex hands routine work to it on its own." in result.output++@pytest.mark.skipif(os.name == "nt", reason = "WSL scenario")def test_claude_subagent_plugin_uses_wsl_for_windows_claude(monkeypatch, tmp_path):monkeypatch.setenv("WSL_DISTRO_NAME", "Ubuntu")