Skip to content

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.

Studio: make unsloth start sampling and reasoning flags apply only to that agent (#12493)

Nilay016a2b518f7c
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 91299bd4d15..06ced6cf878 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -227,7 +227,7 @@ _GPU_MEMORY_MODE_OPTION = typer.Option(
),
)
-# Server knobs. Only used when `unsloth start` auto-starts the server (--serve); they have no effect when attaching to a server someone else already started.
+# Server knobs. Tool flags only configure a server `unsloth start` auto-starts (--serve); reasoning rides in the agent's own config where it can.
_SERVE_OPTION = typer.Option(
True,
"--serve/--no-serve",
@@ -236,7 +236,7 @@ _SERVE_OPTION = typer.Option(
"available after the agent exits. --no-serve errors out instead.",
)
_ENABLE_TOOLS_OPTION = typer.Option(
- False,
+ None,
"--enable-tools/--disable-tools",
rich_help_panel = _PANEL_SERVER,
help = "Server-side tools (web search, code execution) for the auto-started server. "
@@ -261,9 +261,8 @@ _REASONING_OPTION = typer.Option(
"--reasoning",
rich_help_panel = _PANEL_SERVER,
help = (
- "llama-server reasoning mode for an auto-started coding-agent server. "
- "Defaults to auto so the model's chat template decides; use 'on' or 'off' "
- "to override it."
+ "Reasoning mode for this agent session. Defaults to auto so the model's chat "
+ "template decides; use 'on' or 'off' to override it."
),
)
_REASONING_EFFORT_OPTION = typer.Option(
@@ -271,12 +270,12 @@ _REASONING_EFFORT_OPTION = typer.Option(
"--reasoning-effort",
rich_help_panel = _PANEL_SERVER,
help = (
- "Reasoning effort for an auto-started coding-agent server, e.g. 'medium'. The "
+ "Reasoning effort for this agent session, e.g. 'medium'. The "
"levels are the model's own, so pass one its chat template accepts. Default: "
"unset, which keeps the template's level."
),
)
-# Sampling overrides pin a value on the auto-started server, winning over the client and the per-model recommendation. Default unset means the model's recommended sampling is used.
+# Sampling overrides ride in the agent's own config, so only this session uses them; one the agent cannot send pins the auto-started server instead. Default unset means the model's recommended sampling is used.
_TEMPERATURE_OPTION = typer.Option(
None,
"--temperature",
@@ -671,9 +670,9 @@ def _load_options(
class ServerOptions(NamedTuple):
- """Tool-call knobs forwarded to an auto-started `unsloth run` server."""
+ """Start flags: carried fields ride in the agent's requests; the rest configure an auto-started server."""
- enable_tools: bool = False
+ enable_tools: Optional[bool] = None
tool_call_healing: Optional[bool] = None
tool_call_nudging: Optional[bool] = None
reasoning: Optional[Literal["on", "off", "auto"]] = None
@@ -684,6 +683,69 @@ class ServerOptions(NamedTuple):
min_p: Optional[float] = None
repetition_penalty: Optional[float] = None
presence_penalty: Optional[float] = None
+ # Fields the agent's own config sends with each request, kept off the server.
+ carried: frozenset = frozenset()
+ # Carried fields with a value: an inherited UNSLOTH_SAMPLING_* pin would override them.
+ unpinned: frozenset = frozenset()
+
+ def sent_by_agent(self) -> frozenset:
+ # A request cannot ask for the template default back, so auto stays a server setting.
+ unsent = {"reasoning"} if self.reasoning == "auto" else set()
+ if self.reasoning_effort not in _STUDIO_REASONING_EFFORTS:
+ unsent.add("reasoning_effort")
+ return self.carried - unsent
+
+ def request_body(self) -> dict:
+ sent = self.sent_by_agent()
+ body = {
+ name: getattr(self, name)
+ for name in _SAMPLING_FIELDS
+ if name in sent and getattr(self, name) is not None
+ }
+ if "reasoning" in sent and self.reasoning in ("on", "off"):
+ body["enable_thinking"] = self.reasoning == "on"
+ if "reasoning_effort" in sent:
+ body["reasoning_effort"] = self.reasoning_effort
+ return body
+
+
+_SAMPLING_FIELDS = (
+ "temperature",
+ "top_p",
+ "top_k",
+ "min_p",
+ "repetition_penalty",
+ "presence_penalty",
+)
+_REASONING_FIELDS = frozenset({"reasoning", "reasoning_effort"})
+_ALL_REQUEST_FIELDS = frozenset(_SAMPLING_FIELDS) | _REASONING_FIELDS
+_REQUEST_BODY_KEYS = (*_SAMPLING_FIELDS, "enable_thinking", "reasoning_effort")
+_STUDIO_REASONING_EFFORTS = ("none", "minimal", "low", "medium", "high", "max", "xhigh")
+_CODEX_REASONING_EFFORTS = ("none", "minimal", "low", "medium", "high", "xhigh")
+
+
+def _codex_reasoning_effort(
+ reasoning: Optional[str], reasoning_effort: Optional[str]
+) -> Optional[str]:
+ if reasoning == "off":
+ return "none"
+ if reasoning_effort in _CODEX_REASONING_EFFORTS:
+ return reasoning_effort
+ return None
+
+
+def _merge_request_body(container: dict, key: str, body: dict) -> None:
+ current = container.get(key)
+ current = (
+ {k: v for k, v in current.items() if k not in _REQUEST_BODY_KEYS}
+ if isinstance(current, dict)
+ else {}
+ )
+ current.update(body)
+ if current:
+ container[key] = current
+ else:
+ container.pop(key, None)
def _split_repo_variant(model: str) -> tuple:
@@ -1312,16 +1374,13 @@ def _start_studio_server(
elif "UNSLOTH_TOOL_CALL_NUDGE" not in child_env:
child_env["UNSLOTH_TOOL_CALL_NUDGE"] = "1"
# Forward any sampling pin via the env; `unsloth run` reads UNSLOTH_SAMPLING_* and the backend resolver applies it as a hard override. Only set fields the operator specified.
- for _sampling_env, _sampling_value in (
- ("UNSLOTH_SAMPLING_TEMPERATURE", server.temperature),
- ("UNSLOTH_SAMPLING_TOP_P", server.top_p),
- ("UNSLOTH_SAMPLING_TOP_K", server.top_k),
- ("UNSLOTH_SAMPLING_MIN_P", server.min_p),
- ("UNSLOTH_SAMPLING_REPETITION_PENALTY", server.repetition_penalty),
- ("UNSLOTH_SAMPLING_PRESENCE_PENALTY", server.presence_penalty),
- ):
+ for _sampling_name in _SAMPLING_FIELDS:
+ _sampling_env = f"UNSLOTH_SAMPLING_{_sampling_name.upper()}"
+ _sampling_value = getattr(server, _sampling_name)
if _sampling_value is not None:
child_env[_sampling_env] = str(_sampling_value)
+ elif _sampling_name in server.unpinned:
+ child_env.pop(_sampling_env, None)
kwargs: dict = {
"stdout": log,
"stderr": subprocess.STDOUT,
@@ -1426,43 +1485,67 @@ def _require_studio(
server_options: ServerOptions = ServerOptions(),
) -> tuple:
"""Return (base, server). server is a Popen only when WE auto-started it."""
+ sent = server_options.sent_by_agent()
+ server_options = server_options._replace(
+ unpinned = frozenset(name for name in sent if getattr(server_options, name) is not None),
+ **dict.fromkeys(sent),
+ )
+ # What the agent cannot send itself only reaches the env of a server WE launch, which then applies it to every client.
+ _pinned = [
+ "--" + _name.replace("_", "-")
+ for _name in _SAMPLING_FIELDS
+ if getattr(server_options, _name) is not None
+ ]
+ _reasoning_pins = [
+ f"{_flag} {_value}"
+ for _flag, _value in (
+ ("--reasoning", server_options.reasoning),
+ ("--reasoning-effort", server_options.reasoning_effort),
+ )
+ if _value is not None
+ ]
base = find_studio_server()
if base is not None:
- # Attaching to a server someone else started: UNSLOTH_SAMPLING_* pins only reach the server process when WE launch it, so a sampling flag on the attach path cannot take effect. Warn instead of silently dropping it.
- _pinned = [
- _flag
- for _flag, _value in (
- ("--temperature", server_options.temperature),
- ("--top-p", server_options.top_p),
- ("--top-k", server_options.top_k),
- ("--min-p", server_options.min_p),
- ("--repetition-penalty", server_options.repetition_penalty),
- ("--presence-penalty", server_options.presence_penalty),
- )
- if _value is not None
- ]
if _pinned:
typer.echo(
- f"Warning: an Unsloth server is already running at {base}; sampling pins "
- f"({', '.join(_pinned)}) apply only when this command starts the server, so the "
- "running server keeps its current sampling. Stop it with `unsloth studio stop` "
- "and re-run to apply them.",
+ f"Warning: an Unsloth server is already running at {base}, and this agent "
+ f"cannot send {', '.join(_pinned)} itself; they apply only when this command "
+ "starts the server, so the running server keeps its current sampling. Stop it "
+ "with `unsloth studio stop` and re-run to apply them.",
+ err = True,
+ )
+ if _reasoning_pins:
+ typer.echo(
+ f"Warning: an Unsloth server is already running at {base}, and this agent "
+ f"cannot send {', '.join(_reasoning_pins)} itself; it takes effect only when "
+ "this command starts the server, so the running server keeps its current "
+ "reasoning mode. Stop it with `unsloth studio stop` and re-run to apply the "
+ "override.",
err = True,
)
- _reasoning_pins = [
- f"{_flag} {_value}"
- for _flag, _value in (
- ("--reasoning", server_options.reasoning),
- ("--reasoning-effort", server_options.reasoning_effort),
+ _tool_flags = [
+ _on if _value else _off
+ for _value, _on, _off in (
+ (server_options.enable_tools, "--enable-tools", "--disable-tools"),
+ (
+ server_options.tool_call_healing,
+ "--enable-tool-call-healing",
+ "--disable-tool-call-healing",
+ ),
+ (
+ server_options.tool_call_nudging,
+ "--enable-tool-call-nudging",
+ "--disable-tool-call-nudging",
+ ),
)
if _value is not None
]
- if _reasoning_pins:
+ if _tool_flags:
typer.echo(
f"Warning: an Unsloth server is already running at {base}; "
- f"{', '.join(_reasoning_pins)} takes effect only when this command starts "
- "the server, so the running server keeps its current reasoning mode. Stop it "
- "with `unsloth studio stop` and re-run to apply the override.",
+ f"{', '.join(_tool_flags)} takes effect only when this command starts the "
+ "server, so the running server keeps its current tool settings. Stop it with "
+ "`unsloth studio stop` and re-run to apply it.",
err = True,
)
return base, None
@@ -1478,6 +1561,25 @@ def _require_studio(
# Normalize to the port unsloth run actually binds, so the health poll and the returned base hit the same server we launch, not a portless :80.
expected = _effective_base(expected)
load = load or LoadOptions()
+ _server_wide = _pinned + [pin for pin in _reasoning_pins if pin != "--reasoning auto"]
+ if _server_wide:
+ typer.echo(
+ f"Warning: this agent cannot send {', '.join(_server_wide)} itself, so the "
+ "server this command starts applies them to every client until it stops.",
+ err = True,
+ )
+ _dropped = [
+ f"UNSLOTH_SAMPLING_{_name.upper()}"
+ for _name in _SAMPLING_FIELDS
+ if _name in server_options.unpinned
+ and os.environ.get(f"UNSLOTH_SAMPLING_{_name.upper()}")
+ ]
+ if _dropped:
+ typer.echo(
+ f"Warning: this agent's flags replace the inherited {', '.join(_dropped)}, so "
+ "the server this command starts drops those pins for every client.",
+ err = True,
+ )
# Leave a bare GGUF repo's variant unset: the server's own quant preference already picks the best available (UD-Q4_K_XL for Unsloth uploads, else Q4_K_M) and falls back when that exact quant is missing, which forcing a fixed variant here would break.
return _start_studio_server(expected, model, load, server_options)
model_hint = "" if model else " Pass --model to have it start one for you, or"
@@ -2869,7 +2971,12 @@ def _claude_local_command(model_id: str, settings: str, yolo: bool, passthrough:
]
-def _claude_local_env(base: str, key: str, entry: dict) -> dict:
+def _claude_local_env(
+ base: str,
+ key: str,
+ entry: dict,
+ extra_body: Optional[dict] = None,
+) -> dict:
"""Build the local endpoint, cache, display, and compaction environment."""
model_id = entry["id"]
env = {
@@ -2889,6 +2996,8 @@ def _claude_local_env(base: str, key: str, entry: dict) -> dict:
env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] = str(int(window))
env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"] = str(int(window))
env["CLAUDE_AUTOCOMPACT_PCT_OVERRIDE"] = "90"
+ if extra_body:
+ env["CLAUDE_CODE_EXTRA_BODY"] = json.dumps(extra_body)
return env
@@ -2920,6 +3029,9 @@ def _merge_codex_config(existing: str, base: str) -> str:
_CODEX_FALLBACK_PROMPT = Path(__file__).parent.parent / "codex_fallback_prompt.md"
_CODEX_MODEL_CATALOG_MIN_VERSION = (0, 110, 0)
_CODEX_PATCH_LINE_ENDINGS_MIN_VERSION = (0, 148, 0)
+# Older Codex sends no reasoning for a model without reasoning summaries, and older Pi has no samplingParams.
+_CODEX_REASONING_REQUEST_MIN_VERSION = (0, 145, 0)
+_PI_SAMPLING_PARAMS_MIN_VERSION = (0, 84, 0)
def _codex_executable_version(executable: str) -> Optional[tuple[int, int, int]]:
@@ -2948,6 +3060,15 @@ def _codex_supports_model_catalog() -> bool:
return version is not None and version >= _CODEX_MODEL_CATALOG_MIN_VERSION
+def _agent_version_at_least(command: str, minimum: tuple) -> bool:
+ executable = _which_with_install_dirs(command)
+ if executable is None:
+ # Only --no-launch gets here without the agent; its recipe may run elsewhere.
+ return True
+ version = _codex_executable_version(executable)
+ return version is not None and version >= minimum
+
+
def _codex_supports_patch_line_endings() -> bool:
executable = _which_with_install_dirs("codex")
if executable is None:
@@ -2988,7 +3109,12 @@ def _codex_model_catalog(model: dict) -> dict:
return {"models": [entry]}
-def write_codex_config(base: str, model: dict, home: Path) -> None:
+def write_codex_config(
+ base: str,
+ model: dict,
+ home: Path,
+ reasoning_effort: Optional[str] = None,
+) -> None:
home.mkdir(parents = True, exist_ok = True)
config = home / "config.toml"
@@ -3021,6 +3147,8 @@ def write_codex_config(base: str, model: dict, home: Path) -> None:
window = model.get("context_length") or model.get("max_context_length")
if window:
profile_text += f"model_context_window = {int(window)}\n"
+ if reasoning_effort:
+ profile_text += f"model_reasoning_effort = {json.dumps(reasoning_effort)}\n"
profile = home / f"{_CODEX_PROFILE}.config.toml"
if not profile.exists() or profile.read_text(encoding = "utf-8") != profile_text:
profile.write_text(profile_text, encoding = "utf-8")
@@ -3028,11 +3156,17 @@ def write_codex_config(base: str, model: dict, home: Path) -> None:
def write_codex_subagent_bridge(
- base: str, key: str, model: dict, home: Path, *, yolo: bool
+ base: str,
+ key: str,
+ model: dict,
+ home: Path,
+ *,
+ yolo: bool,
+ reasoning_effort: Optional[str] = None,
) -> Path:
"""Write private config for an explicit local Codex child launched through MCP."""
child_home = home / "child"
- write_codex_config(base, model, child_home)
+ write_codex_config(base, model, child_home, reasoning_effort)
path = home / "subagent.json"
_write_private_json(
path,
@@ -3395,7 +3529,10 @@ def write_claude_subagent_plugin(path: Path, server_env: dict) -> Path:
server_env.get("UNSLOTH_CLAUDE_SUBAGENT_CONTEXT_WINDOW", "0") or 0
),
}
- settings = _write_claude_settings(plugin, model_id, _claude_local_env(base, key, entry))
+ local_env = _claude_local_env(base, key, entry)
+ if "CLAUDE_CODE_EXTRA_BODY" in server_env:
+ local_env["CLAUDE_CODE_EXTRA_BODY"] = server_env["CLAUDE_CODE_EXTRA_BODY"]
+ settings = _write_claude_settings(plugin, model_id, local_env)
mcp_env[_CLAUDE_SUBAGENT_SETTINGS_ENV] = str(settings)
if _wsl_windows_executable(["claude"]):
command = "wsl.exe"
@@ -4480,6 +4617,7 @@ def write_openclaw_config(
yolo: bool = False,
workspace_path: Optional[str] = None,
embedding_model: Optional[str] = None,
+ request_body: Optional[dict] = None,
) -> None:
config = _read_json_object(path)
if config is None:
@@ -4525,6 +4663,12 @@ def write_openclaw_config(
agents = _subdict(config, "agents")
defaults = _subdict(agents, "defaults")
_subdict(defaults, "model")["primary"] = f"unsloth/{model['id']}"
+ # OpenClaw applies extra_body last; its own params only read camelCase keys, so top_p would be lost.
+ model_ref = f"unsloth/{model['id']}"
+ model_settings = defaults.get("models")
+ if request_body or (isinstance(model_settings, dict) and model_ref in model_settings):
+ params = _subdict(_subdict(_subdict(defaults, "models"), model_ref), "params")
+ _merge_request_body(params, "extra_body", request_body or {})
# `unsloth start openclaw` is a coding-agent entry point, so the selected project may already contain its own AGENTS.md and git metadata. Do not seed OpenClaw's personal-assistant bootstrap files or initialize a repository in it.
defaults["skipBootstrap"] = True
# OPENCLAW_STATE_DIR does not relocate the workspace. Callers normally pin it to the directory where `unsloth start openclaw` was invoked so OpenClaw edits the same project as every other coding agent. Keep the managed fallback for direct config-writer callers that do not provide an explicit workspace.
@@ -4652,6 +4796,7 @@ def write_opencode_config(
yolo: bool = False,
as_subagent: bool = False,
max_tokens: Optional[int] = None,
+ request_body: Optional[dict] = None,
) -> dict:
config = _read_json_object(path)
if config is None:
@@ -4673,10 +4818,20 @@ def write_opencode_config(
reserved = opencode_compaction_reserved(window, output)
# Without a limit OpenCode assumes context 0 and never compacts. Without input it compacts at context - output and ignores compaction.reserved.
model_entry["limit"] = {"context": window, "input": window, "output": output}
+ provider_options = {"baseURL": f"{base}/v1", "apiKey": key}
+ if request_body:
+ # OpenCode 1.x sends model options, reading the effort only as reasoningEffort; 2.x sends only the provider body.
+ model_entry["options"] = {
+ "reasoningEffort" if name == "reasoning_effort" else name: value
+ for name, value in request_body.items()
+ }
+ if "temperature" in request_body:
+ model_entry["temperature"] = True
+ provider_options["body"] = request_body
_subdict(config, "provider")[_OPENCODE_PROVIDER] = {
"npm": "@ai-sdk/openai-compatible",
"name": "Unsloth Studio",
- "options": {"baseURL": f"{base}/v1", "apiKey": key},
+ "options": provider_options,
"models": {model["id"]: model_entry},
}
# Normal mode pins this as the session model. Subagent mode leaves the user's main/small models alone and exposes the local model to @unsloth and /models.
@@ -4735,7 +4890,12 @@ def write_opencode_config(
return session_permission
-def write_hermes_config(base: str, model: dict, path: Path) -> None:
+def write_hermes_config(
+ base: str,
+ model: dict,
+ path: Path,
+ request_body: Optional[dict] = None,
+) -> None:
import yaml
config: dict = {}
@@ -4783,6 +4943,7 @@ def write_hermes_config(base: str, model: dict, path: Path) -> None:
"base_url": f"{base}/v1",
"api_mode": "openai",
"key_env": _HERMES_ENV_KEY,
+ **({"extra_body": request_body} if request_body else {}),
}
text = yaml.safe_dump(config, sort_keys = False)
if not path.exists() or path.read_text(encoding = "utf-8") != text:
@@ -4798,6 +4959,7 @@ def write_pi_config(
path: Path,
*,
max_tokens: Optional[int] = None,
+ request_body: Optional[dict] = None,
) -> None:
config = _read_json_object(path)
if config is None:
@@ -4818,6 +4980,8 @@ def write_pi_config(
provider_model["maxTokens"] = _agent_output_limit(window, max_tokens)
elif max_tokens:
provider_model["maxTokens"] = max_tokens
+ if request_body:
+ provider_model["samplingParams"] = request_body
_subdict(config, "providers")[_PI_PROVIDER] = {
"api": "openai-completions",
"baseUrl": f"{base}/v1",
@@ -5088,6 +5252,7 @@ def write_pi_subagent_config(
path: Path,
approve: bool = False,
max_tokens: Optional[int] = None,
+ request_body: Optional[dict] = None,
) -> None:
"""Write private bootstrap data for the bundled Pi extension."""
window = model.get("context_length") or model.get("max_context_length")
@@ -5101,11 +5266,17 @@ def write_pi_subagent_config(
"contextWindow": window,
"maxTokens": _agent_output_limit(window, max_tokens),
"approve": approve,
+ **({"samplingParams": request_body} if request_body else {}),
},
)
-def write_dsh_patch(base: str, model: dict, path: Path) -> None:
+def write_dsh_patch(
+ base: str,
+ model: dict,
+ path: Path,
+ request_body: Optional[dict] = None,
+) -> None:
"""Write the dsh loader patch that points the booted profile at Unsloth.
dsh 0.1.7 dropped `settings.yaml`: it now imports a leftover one into the profile only
@@ -5121,6 +5292,17 @@ def write_dsh_patch(base: str, model: dict, path: Path) -> None:
window = int(window)
model_entry["contextWindow"] = window
model_entry["maxTokens"] = opencode_output_limit(window)
+ compat = {"supportsDeveloperRole": False, "maxTokensField": "max_tokens"}
+ if request_body:
+ # dsh sends template kwargs only for a model that declares reasoning levels.
+ model_entry["reasoningEfforts"] = {
+ "off": None,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ }
+ compat["thinkingFormat"] = "chat-template"
+ compat["chatTemplateKwargs"] = request_body
entries = [
{
"id": "llm-pi-ai",
@@ -5133,7 +5315,7 @@ def write_dsh_patch(base: str, model: dict, path: Path) -> None:
"baseURL": f"{base}/v1",
"apiKeyEnv": _DSH_ENV_KEY,
# pi-ai reads an unknown base URL as OpenAI itself.
- "compat": {"supportsDeveloperRole": False, "maxTokensField": "max_tokens"},
+ "compat": compat,
"models": [model_entry],
}
}
@@ -5163,7 +5345,7 @@ def claude(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5190,6 +5372,20 @@ def claude(
# Before the install prompt: _install_agent runs a remote installer, and this can refuse outright, so asking first fetches a tool the run cannot use.
_preflight_agent_gguf(_CLAUDE_GGUF_AGENT, model, serve = serve, launch = launch)
_require_agent_for_launch("claude", install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _ALL_REQUEST_FIELDS,
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5199,19 +5395,7 @@ def claude(
serve = serve,
launch = launch,
preload_check = functools.partial(_attach_gguf_check, _CLAUDE_GGUF_AGENT),
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
# Before the launch owns the server, so a rejection tears it down, not atexit.
try:
@@ -5232,6 +5416,8 @@ def claude(
}
if window:
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())
with _session_config("claude-subagent", launch, persist = persist) as config:
plugin = write_claude_subagent_plugin(config, server_env)
command = [
@@ -5257,7 +5443,7 @@ def claude(
)
return
- env = _claude_local_env(base, key, entry)
+ env = _claude_local_env(base, key, entry, server_options.request_body())
# Claude Code auto-compacts against its native context window; the local env above supplies the loaded model's real window and a 90% threshold instead. --yolo (or its aliases) maps to Claude's own --dangerously-skip-permissions. IS_SANDBOX is left unset on purpose: Claude refuses bypass mode as root unless a sandbox is detected, and we do not want to falsely claim one on the user's host. claude keeps its history in ~/.claude/projects, which --settings/env never relocate, so a session already survives exit; resume it with `claude --continue` or `--resume <id>` passed through.
with _session_config("claude", launch, persist = persist) as config:
settings = _write_claude_settings(config, model_id, env)
@@ -5289,7 +5475,7 @@ def codex(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5312,6 +5498,23 @@ def codex(
# Before the install prompt: _install_agent runs a remote installer, and this can refuse outright, so asking first fetches a tool the run cannot use.
_preflight_agent_gguf(_CODEX_GGUF_AGENT, model, serve = serve, launch = launch)
_require_agent_for_launch("codex", install_hint, launch)
+ codex_effort = _codex_reasoning_effort(reasoning, reasoning_effort)
+ if codex_effort and not _agent_version_at_least("codex", _CODEX_REASONING_REQUEST_MIN_VERSION):
+ codex_effort = None
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _REASONING_FIELDS if codex_effort else frozenset(),
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5321,19 +5524,7 @@ def codex(
serve = serve,
launch = launch,
preload_check = functools.partial(_attach_gguf_check, _CODEX_GGUF_AGENT),
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
# This preflight runs after _connect may have auto-started a server but before _run takes over its lifecycle, so tear the server down here if it rejects the model (a transformers-backend model) rather than leaving it on the atexit backstop.
try:
@@ -5351,6 +5542,7 @@ def codex(
subagent_model,
home,
yolo = yolo,
+ reasoning_effort = codex_effort,
)
parent_home = write_codex_parent_overlay(home / "parent")
command = [
@@ -5381,7 +5573,7 @@ def codex(
*ctx.args,
]
with _session_config("codex", launch, persist = persist) as home:
- write_codex_config(base, entry, home)
+ write_codex_config(base, entry, home, codex_effort)
env = {_CODEX_ENV_KEY: key, "CODEX_HOME": str(home)}
_run(
base,
@@ -5405,7 +5597,7 @@ def openclaw(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5430,6 +5622,20 @@ def openclaw(
else "curl -fsSL https://openclaw.ai/install.sh | bash"
)
_require_agent_for_launch("openclaw", install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _ALL_REQUEST_FIELDS,
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5438,19 +5644,7 @@ def openclaw(
),
serve = serve,
launch = launch,
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
openclaw_args = list(ctx.args)
# Default a bare `unsloth start openclaw` to the local TUI. Anything the caller passes through is forwarded verbatim so OpenClaw parses it under its own grammar (openclaw [global-flags] <command> [options]): an explicit subcommand, a global flag that must precede the command such as --profile/--dev, or a tui option. We cannot reinterpret those safely because a leading "--flag value" is ambiguous between a global (`--profile test`) and a tui option (`--message hi`), and prepending `tui --local` would break the global form, so only the empty case is defaulted.
@@ -5468,6 +5662,7 @@ def openclaw(
yolo = yolo,
workspace_path = "${OPENCLAW_WORKSPACE_DIR}",
embedding_model = _studio_embedding_model(base, key),
+ request_body = server_options.request_body(),
)
# Scope both config and state so OpenClaw never touches the user's ~/.openclaw.
# Off, else OpenClaw re-imports any provider key it cannot see from a login shell.
@@ -5499,7 +5694,7 @@ def opencode(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5522,6 +5717,20 @@ def opencode(
command_name, opencode_v2 = _opencode_command()
install_hint = _npm_install_hint("@opencode-ai/cli@beta" if opencode_v2 else "opencode-ai")
_require_agent_for_launch(command_name, install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _ALL_REQUEST_FIELDS,
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5530,19 +5739,7 @@ def opencode(
),
serve = serve,
launch = launch,
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
if opencode_v2:
typer.echo(
@@ -5573,6 +5770,7 @@ def opencode(
yolo = yolo and not native_auto,
as_subagent = True,
max_tokens = max_tokens,
+ request_body = server_options.request_body(),
)
env = {
"OPENCODE_CONFIG": str(config_path),
@@ -5639,6 +5837,7 @@ def opencode(
config_path,
yolo = yolo and not native_auto,
max_tokens = max_tokens,
+ request_body = server_options.request_body(),
)
# A project's own opencode.json outranks OPENCODE_CONFIG, so the session model pin would silently lose to a repo config; carry it in OPENCODE_CONFIG_CONTENT, which outranks project config, while the API key stays in the private file. Only the config fallback carries a permission: native --auto omits it (auto-approve asks, keep explicit denies) and a non-yolo session omits it too, honoring project rules. V1 filters are ordinary overlays, so scope that session to our provider; V2 turns filters into security policies where global/project rules intentionally win, so keep those policies intact and tell the user above that they must allow our provider. small_model is opencode's separate model for lightweight tasks; pin it to the session model too, or a user/project small_model on another (now filtered) provider would resolve a not-found error mid-session.
inline_config: dict = {
@@ -5669,7 +5868,7 @@ def hermes(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5692,6 +5891,20 @@ def hermes(
command = ["hermes", *_hermes_resume_oneshot_args(native_args)]
install_hint = _hermes_install_hint()
_require_agent_for_launch("hermes", install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _ALL_REQUEST_FIELDS,
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5700,23 +5913,11 @@ def hermes(
),
serve = serve,
launch = launch,
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
with _session_config("hermes", launch, persist = persist) as home:
# HERMES_HOME relocates hermes' whole home dir (config.yaml, sessions, state) like CODEX_HOME, so the user's ~/.hermes is left untouched for the session.
- write_hermes_config(base, entry, home / "config.yaml")
+ write_hermes_config(base, entry, home / "config.yaml", server_options.request_body())
env = {_HERMES_ENV_KEY: key, "HERMES_HOME": str(home)}
_run(base, entry, env, command, launch = launch, install_hint = install_hint)
@@ -5733,7 +5934,7 @@ def pi(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5759,6 +5960,24 @@ def pi(
if as_subagent and not _PI_SUBAGENT_EXTENSION.is_file():
_fail(f"Missing Pi subagent extension: {_PI_SUBAGENT_EXTENSION}")
_require_agent_for_launch("pi", install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _ALL_REQUEST_FIELDS,
+ )
+ if server_options.request_body() and not _agent_version_at_least(
+ "pi", _PI_SAMPLING_PARAMS_MIN_VERSION
+ ):
+ server_options = server_options._replace(carried = frozenset())
base, key, entry = _connect(
api_key,
model,
@@ -5767,19 +5986,7 @@ def pi(
),
serve = serve,
launch = launch,
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
if as_subagent:
subagent_id = _subagent_model_id(base, key, entry, model, gguf_variant)
@@ -5794,6 +6001,7 @@ def pi(
config_path,
approve = yolo,
max_tokens = max_tokens,
+ request_body = server_options.request_body(),
)
command = [
"pi",
@@ -5830,7 +6038,14 @@ def pi(
with _session_config("pi", launch, persist = persist) as home:
# Pi resolves its config dir from PI_CODING_AGENT_DIR first (getAgentDir() prefers it over $HOME/.pi/agent), so pin it at the session dir: an inherited PI_CODING_AGENT_DIR in the user's shell would otherwise send Pi to their real config and skip our provider/key. HOME is relocated too so any other ~/.pi paths stay in the session. The key rides in the config rather than the env.
pi_agent_dir = home / ".pi" / "agent"
- write_pi_config(base, key, entry, pi_agent_dir / "models.json", max_tokens = max_tokens)
+ write_pi_config(
+ base,
+ key,
+ entry,
+ pi_agent_dir / "models.json",
+ max_tokens = max_tokens,
+ request_body = server_options.request_body(),
+ )
write_pi_user_resources(pi_agent_dir, home)
env = {"HOME": str(home), "PI_CODING_AGENT_DIR": str(pi_agent_dir)}
if os.name == "nt" or os.environ.get("WSL_DISTRO_NAME"):
@@ -5862,7 +6077,7 @@ def dsh(
load_in_4bit: bool = _LOAD_4BIT_OPTION,
tensor_parallel: bool = _TENSOR_PARALLEL_OPTION,
gpu_memory_mode: Optional[Literal["auto", "manual"]] = _GPU_MEMORY_MODE_OPTION,
- enable_tools: bool = _ENABLE_TOOLS_OPTION,
+ enable_tools: Optional[bool] = _ENABLE_TOOLS_OPTION,
tool_call_healing: Optional[bool] = _TOOL_CALL_HEALING_OPTION,
tool_call_nudging: Optional[bool] = _TOOL_CALL_NUDGING_OPTION,
reasoning: Optional[Literal["on", "off", "auto"]] = _REASONING_OPTION,
@@ -5882,6 +6097,20 @@ def dsh(
_reject_as_subagent("dsh", ctx.args)
install_hint = _npm_install_hint(_DSH_PACKAGE)
_require_agent_for_launch("dsh", install_hint, launch)
+ server_options = ServerOptions(
+ enable_tools = enable_tools,
+ tool_call_healing = tool_call_healing,
+ tool_call_nudging = tool_call_nudging,
+ reasoning = reasoning,
+ reasoning_effort = reasoning_effort,
+ temperature = temperature,
+ top_p = top_p,
+ top_k = top_k,
+ min_p = min_p,
+ repetition_penalty = repetition_penalty,
+ presence_penalty = presence_penalty,
+ carried = _REASONING_FIELDS,
+ )
base, key, entry = _connect(
api_key,
model,
@@ -5890,23 +6119,11 @@ def dsh(
),
serve = serve,
launch = launch,
- server_options = ServerOptions(
- enable_tools = enable_tools,
- tool_call_healing = tool_call_healing,
- tool_call_nudging = tool_call_nudging,
- reasoning = reasoning,
- reasoning_effort = reasoning_effort,
- temperature = temperature,
- top_p = top_p,
- top_k = top_k,
- min_p = min_p,
- repetition_penalty = repetition_penalty,
- presence_penalty = presence_penalty,
- ),
+ server_options = server_options,
)
with _session_config("dsh", launch, persist = persist) as home:
patch = home / _DSH_PATCH_FILE
- write_dsh_patch(base, entry, patch)
+ write_dsh_patch(base, entry, patch, server_options.request_body())
# A Windows dsh under WSL gets DSH_HOME translated through WSLENV, but not argv.
command = _dsh_command(ctx.args, _agent_config_path(patch, ["dsh"]))
env = {
diff --git a/unsloth_cli/pi_subagent.ts b/unsloth_cli/pi_subagent.ts
index 2406e496027..5853bb4956c 100644
--- a/unsloth_cli/pi_subagent.ts
+++ b/unsloth_cli/pi_subagent.ts
@@ -30,6 +30,7 @@ const apiKey = typeof config.apiKey === "string" ? config.apiKey : "";
const approve = config.approve === true;
const contextWindow = positiveInt(config.contextWindow, 32768);
const maxTokens = positiveInt(config.maxTokens, Math.min(Math.floor(contextWindow / 4), 8192));
+const samplingParams = (config.samplingParams ?? {}) as Record<string, unknown>;
let activeAgents = 0;
const waitingAgents: Array<() => boolean> = [];
@@ -302,6 +303,7 @@ export default function unslothSubagent(pi: ExtensionAPI): void {
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow,
maxTokens,
+ ...(Object.keys(samplingParams).length > 0 ? { samplingParams } : {}),
},
],
});
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index d823e349676..5f975184b4a 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -3335,6 +3335,33 @@ def test_start_studio_server_respects_inherited_tool_call_env(monkeypatch):
assert env["UNSLOTH_TOOL_CALL_NUDGE"] == "1"
+def test_start_studio_server_drops_an_inherited_pin_the_agent_overrides(monkeypatch):
+ captured = {}
+
+ class FakePopen:
+ def __init__(self, command, **kwargs):
+ captured["env"] = kwargs["env"]
+ self.pid = 1
+
+ def poll(self):
+ return None
+
+ monkeypatch.setattr(start.subprocess, "Popen", FakePopen)
+ monkeypatch.setattr(start, "_studio_healthy", lambda base, timeout = 3.0: True)
+ monkeypatch.setattr(start, "_log_tail", lambda path, lines = 20: "API Key: sk-unsloth-x")
+ monkeypatch.setattr(start.time, "sleep", lambda _s: None)
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", "0.7")
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_P", "0.5")
+ start._start_studio_server(
+ "http://127.0.0.1:8888",
+ "unsloth/M-GGUF",
+ start.LoadOptions(),
+ start.ServerOptions(unpinned = frozenset({"temperature"})),
+ )
+ assert "UNSLOTH_SAMPLING_TEMPERATURE" not in captured["env"]
+ assert captured["env"]["UNSLOTH_SAMPLING_TOP_P"] == "0.5"
+
+
def test_start_studio_server_forwards_sampling_via_env(monkeypatch):
# Sampling pins ride to the child server through UNSLOTH_SAMPLING_*; unset ones stay absent
# so the backend keeps the per-model recommendation.
@@ -3395,29 +3422,303 @@ def test_require_studio_warns_on_sampling_pin_when_reusing_server(monkeypatch, c
assert "--top-p" not in err
-def test_require_studio_no_sampling_warning_without_pins(monkeypatch, capsys):
- # Reusing a server with no sampling pins stays silent (tool flags are out of scope here).
+def test_require_studio_no_warning_without_server_flags(monkeypatch, capsys):
monkeypatch.setattr(start, "find_studio_server", lambda: BASE)
base, server = start._require_studio(
"unsloth/M-GGUF",
start.LoadOptions(),
serve = True,
- server_options = start.ServerOptions(enable_tools = True),
+ server_options = start.ServerOptions(),
)
assert base == BASE and server is None
assert capsys.readouterr().err == ""
[email protected]("reasoning", ["on", "off", "auto"])
+def test_require_studio_warns_on_tool_flags_when_reusing_server(monkeypatch, capsys):
+ monkeypatch.setattr(start, "find_studio_server", lambda: BASE)
+ base, server = start._require_studio(
+ "unsloth/M-GGUF",
+ start.LoadOptions(),
+ serve = True,
+ server_options = start.ServerOptions(
+ enable_tools = True, tool_call_healing = False, tool_call_nudging = None
+ ),
+ )
+ assert base == BASE and server is None
+ err = capsys.readouterr().err
+ assert "already running" in err
+ assert "--enable-tools" in err and "--disable-tool-call-healing" in err
+ assert "nudging" not in err
+
+
+_SESSION_FLAGS = ["--temperature", "0.3", "--top-k", "40", "--reasoning", "off"]
+_SESSION_BODY = {"temperature": 0.3, "top_k": 40, "enable_thinking": False}
+
+
+def _session_request_body(agent, root, output):
+ yaml = pytest.importorskip("yaml")
+ home = root / "agents" / agent
+ model_ref = f"unsloth/{MODEL['id']}"
+ if agent == "pi":
+ config = json.loads((home / ".pi" / "agent" / "models.json").read_text())
+ return config["providers"]["unsloth"]["models"][0].get("samplingParams")
+ if agent == "hermes":
+ config = yaml.safe_load((home / "config.yaml").read_text())
+ return config["providers"]["unsloth"].get("extra_body")
+ if agent == "openclaw":
+ config = json.loads((home / "openclaw.json").read_text())
+ models = config["agents"]["defaults"].get("models", {})
+ return models.get(model_ref, {}).get("params", {}).get("extra_body")
+ if agent == "opencode":
+ provider = json.loads((home / "opencode.json").read_text())["provider"]
+ provider = provider[start._OPENCODE_PROVIDER]
+ options = provider["models"][MODEL["id"]].get("options")
+ assert provider["options"].get("body") == options
+ return options
+ if agent == "claude":
+ settings = Path(shlex.split(re.search(r"--settings (\S+)", output).group(1))[0])
+ extra = json.loads(settings.read_text())["env"].get("CLAUDE_CODE_EXTRA_BODY")
+ return json.loads(extra) if extra else None
+ raise AssertionError(agent)
+
+
[email protected]("agent", ["pi", "hermes", "openclaw", "opencode", "claude"])
+def test_session_flags_ride_in_the_agent_config_on_a_running_server(
+ agent, fake_studio, tmp_path, monkeypatch
+):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(start.start_app, [agent, "--no-launch", *_SESSION_FLAGS])
+ assert result.exit_code == 0, result.output
+ assert "already running" not in result.output
+ assert _session_request_body(agent, tmp_path, result.output) == _SESSION_BODY
+
+
[email protected]("agent", ["pi", "hermes", "openclaw", "opencode", "claude"])
+def test_session_flags_from_an_earlier_run_do_not_stick(agent, fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ for argv in ([agent, "--no-launch", *_SESSION_FLAGS], [agent, "--no-launch"]):
+ result = CliRunner().invoke(start.start_app, argv)
+ assert result.exit_code == 0, result.output
+ assert not _session_request_body(agent, tmp_path, result.output)
+
+
+def test_openclaw_session_flags_keep_the_users_own_extra_body(fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "agents" / "openclaw" / "openclaw.json"
+ config_path.parent.mkdir(parents = True)
+ model_ref = f"unsloth/{MODEL['id']}"
+ config_path.write_text(
+ json.dumps(
+ {
+ "agents": {
+ "defaults": {
+ "models": {
+ model_ref: {"params": {"extra_body": {"tool_choice": "required"}}}
+ }
+ }
+ }
+ }
+ )
+ )
+ result = CliRunner().invoke(
+ start.start_app, ["openclaw", "--no-launch", "--temperature", "0.3"]
+ )
+ assert result.exit_code == 0, result.output
+ assert _session_request_body("openclaw", tmp_path, result.output) == {
+ "tool_choice": "required",
+ "temperature": 0.3,
+ }
+ result = CliRunner().invoke(start.start_app, ["openclaw", "--no-launch"])
+ assert result.exit_code == 0, result.output
+ assert _session_request_body("openclaw", tmp_path, result.output) == {"tool_choice": "required"}
+
+
+def test_opencode_session_temperature_needs_the_capability(fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ config_path = tmp_path / "agents" / "opencode" / "opencode.json"
+ for argv, capability in ((["--temperature", "0.3"], True), (["--top-k", "40"], None)):
+ result = CliRunner().invoke(start.start_app, ["opencode", "--no-launch", *argv])
+ assert result.exit_code == 0, result.output
+ provider = json.loads(config_path.read_text())["provider"][start._OPENCODE_PROVIDER]
+ assert provider["models"][MODEL["id"]].get("temperature") is capability
+
+
+def test_pi_subagent_carries_the_session_flags(fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(
+ start.start_app, ["pi", "--as-subagent", "--no-launch", *_SESSION_FLAGS]
+ )
+ assert result.exit_code == 0, result.output
+ assert "already running" not in result.output
+ config = json.loads((tmp_path / "agents" / "pi-subagent" / "subagent.json").read_text())
+ assert config["samplingParams"] == _SESSION_BODY
+
+
+def test_codex_carries_reasoning_and_warns_about_sampling(fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(start.start_app, ["codex", "--no-launch", *_SESSION_FLAGS])
+ assert result.exit_code == 0, result.output
+ profile = (tmp_path / "agents" / "codex" / f"{start._CODEX_PROFILE}.config.toml").read_text()
+ assert 'model_reasoning_effort = "none"' in profile
+ assert "cannot send --temperature, --top-k itself" in result.output
+ assert "--reasoning" not in result.output
+ result = CliRunner().invoke(start.start_app, ["codex", "--no-launch"])
+ assert result.exit_code == 0, result.output
+ profile = (tmp_path / "agents" / "codex" / f"{start._CODEX_PROFILE}.config.toml").read_text()
+ assert "model_reasoning_effort" not in profile
+
+
+def test_codex_warns_about_reasoning_it_cannot_express(fake_studio, tmp_path, monkeypatch):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(start.start_app, ["codex", "--no-launch", "--reasoning", "on"])
+ assert result.exit_code == 0, result.output
+ assert "cannot send --reasoning on itself" in result.output
+ profile = (tmp_path / "agents" / "codex" / f"{start._CODEX_PROFILE}.config.toml").read_text()
+ assert "model_reasoning_effort" not in profile
+
+
[email protected]("mode", ["--persist", "--no-launch"])
[email protected]("agent, version", [("codex", (0, 144, 0)), ("pi", (0, 83, 0))])
+def test_agent_too_old_to_send_the_flags_keeps_the_server_pin(
+ agent, version, mode, fake_studio, tmp_path, monkeypatch
+):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setattr(start, "_which_with_install_dirs", lambda name: f"/bin/{name}")
+ monkeypatch.setattr(start, "_codex_executable_version", lambda executable: version)
+ monkeypatch.setattr(start, "_launch", lambda *args, **kwargs: None)
+ result = CliRunner().invoke(start.start_app, [agent, mode, *_SESSION_FLAGS])
+ assert result.exit_code == 0, result.output
+ assert "cannot send --temperature, --top-k itself" in result.output
+ assert "cannot send --reasoning off itself" in result.output
+ if agent == "pi":
+ models = tmp_path / "agents" / "pi" / ".pi" / "agent" / "models.json"
+ provider = json.loads(models.read_text())["providers"]["unsloth"]
+ assert "samplingParams" not in provider["models"][0]
+ else:
+ profile = (
+ tmp_path / "agents" / "codex" / f"{start._CODEX_PROFILE}.config.toml"
+ ).read_text()
+ assert "model_reasoning_effort" not in profile
+
+
+def test_opencode_v1_reads_the_effort_as_reasoning_effort_option(
+ fake_studio, tmp_path, monkeypatch
+):
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(
+ start.start_app, ["opencode", "--no-launch", "--reasoning-effort", "low"]
+ )
+ assert result.exit_code == 0, result.output
+ provider = json.loads((tmp_path / "agents" / "opencode" / "opencode.json").read_text())
+ provider = provider["provider"][start._OPENCODE_PROVIDER]
+ assert provider["models"][MODEL["id"]]["options"] == {"reasoningEffort": "low"}
+ assert provider["options"]["body"] == {"reasoning_effort": "low"}
+
+
+def test_dsh_carries_reasoning_and_warns_about_sampling(fake_studio, tmp_path, monkeypatch):
+ yaml = pytest.importorskip("yaml")
+ monkeypatch.chdir(tmp_path)
+ result = CliRunner().invoke(start.start_app, ["dsh", "--no-launch", *_SESSION_FLAGS])
+ assert result.exit_code == 0, result.output
+ assert "cannot send --temperature, --top-k itself" in result.output
+ assert "--reasoning" not in result.output
+ patch = tmp_path / "agents" / "dsh" / start._DSH_PATCH_FILE
+ provider = yaml.safe_load(patch.read_text())[0]["config"]["providers"][start._DSH_PROVIDER]
+ assert provider["compat"]["thinkingFormat"] == "chat-template"
+ assert provider["compat"]["chatTemplateKwargs"] == {"enable_thinking": False}
+ assert "off" in provider["models"][0]["reasoningEfforts"]
+
+
+ "agent, server_keeps",
+ [("pi", {}), ("codex", {"temperature": 0.3, "top_k": 40})],
+)
+def test_spawned_server_keeps_only_what_the_agent_cannot_send(
+ agent, server_keeps, fake_studio, monkeypatch
+):
+ monkeypatch.setattr(start, "find_studio_server", lambda: None)
+ started = {}
+ fake = SimpleNamespace(pid = 999, poll = lambda: None)
+
+ def fake_start(
+ base,
+ model,
+ load,
+ server_options = None,
+ ):
+ started["options"] = server_options
+ start._auto_served_server = fake
+ return base, fake
+
+ monkeypatch.setattr(start, "_start_studio_server", fake_start)
+ monkeypatch.setattr(start, "_shutdown_server", lambda server: None)
+ monkeypatch.setattr(start.shutil, "which", lambda _: f"/usr/local/bin/{agent}")
+ monkeypatch.setattr(start, "_codex_executable_version", lambda executable: (1, 0, 0))
+ monkeypatch.setattr(start.subprocess, "run", lambda command, env: SimpleNamespace(returncode = 0))
+ result = CliRunner().invoke(
+ start.start_app, [agent, "--model", "unsloth/Qwen3-1.7B-GGUF", *_SESSION_FLAGS]
+ )
+ assert result.exit_code == 0, result.output
+ options = started["options"]
+ sampling = {name: getattr(options, name) for name in ("temperature", "top_k")}
+ assert {k: v for k, v in sampling.items() if v is not None} == server_keeps
+ assert options.reasoning is None
+ assert options.unpinned == {"reasoning", *({"temperature", "top_k"} - set(server_keeps))}
+ assert ("applies them to every client" in result.output) == bool(server_keeps)
+
+
[email protected]("reasoning, warns", [("on", True), ("auto", False)])
+def test_require_studio_warns_when_the_started_server_pins_reasoning(
+ monkeypatch, capsys, reasoning, warns
+):
+ monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")
+ monkeypatch.setattr(start, "find_studio_server", lambda: None)
+ monkeypatch.setattr(
+ start, "_start_studio_server", lambda base, model, load, server: (base, None)
+ )
+ start._require_studio(
+ "unsloth/M-GGUF", serve = True, server_options = start.ServerOptions(reasoning = reasoning)
+ )
+ assert ("every client" in capsys.readouterr().err) is warns
+
+
[email protected]("inherited", ["0.7", None])
+def test_require_studio_warns_when_a_flag_drops_an_inherited_pin(monkeypatch, capsys, inherited):
+ monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")
+ if inherited:
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TEMPERATURE", inherited)
+ else:
+ monkeypatch.delenv("UNSLOTH_SAMPLING_TEMPERATURE", raising = False)
+ monkeypatch.setenv("UNSLOTH_SAMPLING_TOP_P", "0.5")
+ monkeypatch.setattr(start, "find_studio_server", lambda: None)
+ monkeypatch.setattr(
+ start, "_start_studio_server", lambda base, model, load, server: (base, None)
+ )
+ options = start.ServerOptions(temperature = 0.3, carried = frozenset({"temperature"}))
+ start._require_studio("unsloth/M-GGUF", serve = True, server_options = options)
+ err = capsys.readouterr().err
+ assert ("replace the inherited UNSLOTH_SAMPLING_TEMPERATURE" in err) is bool(inherited)
+ assert "UNSLOTH_SAMPLING_TOP_P" not in err
+
+
+ "reasoning, carried",
+ [
+ ("on", frozenset()),
+ ("off", frozenset()),
+ ("auto", frozenset()),
+ ("auto", start._ALL_REQUEST_FIELDS),
+ ],
+)
def test_require_studio_warns_on_explicit_reasoning_when_reusing_server(
- monkeypatch, capsys, reasoning
+ monkeypatch, capsys, reasoning, carried
):
monkeypatch.setattr(start, "find_studio_server", lambda: BASE)
base, server = start._require_studio(
"unsloth/M-GGUF",
start.LoadOptions(),
serve = True,
- server_options = start.ServerOptions(reasoning = reasoning),
+ server_options = start.ServerOptions(reasoning = reasoning, carried = carried),
)
assert base == BASE and server is None
err = capsys.readouterr().err
@@ -3493,8 +3794,8 @@ def test_require_studio_warns_on_explicit_reasoning_effort_when_reusing_server(m
assert "unsloth studio stop" in err
-def test_start_claude_parses_sampling_flags(fake_studio, monkeypatch):
- # `unsloth start claude ... --temperature 0.3 --top-k 40` routes the pins into ServerOptions.
+def test_start_claude_sends_sampling_flags_itself(fake_studio, monkeypatch):
+ # Claude sends the flags itself, so the server it starts is left at its defaults.
monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")
monkeypatch.setattr(start, "find_studio_server", lambda: None)
captured = {}
@@ -3513,7 +3814,11 @@ def test_start_claude_parses_sampling_flags(fake_studio, monkeypatch):
monkeypatch.setattr(start, "_start_studio_server", fake_start)
monkeypatch.setattr(start, "_shutdown_server", lambda server: None)
monkeypatch.setattr(start.shutil, "which", lambda _: "/usr/local/bin/claude")
- monkeypatch.setattr(start.subprocess, "run", lambda command, env: SimpleNamespace(returncode = 0))
+ monkeypatch.setattr(
+ start.subprocess,
+ "run",
+ lambda command, env: captured.update(env = env) or SimpleNamespace(returncode = 0),
+ )
result = CliRunner().invoke(
start.start_app,
@@ -3531,9 +3836,12 @@ def test_start_claude_parses_sampling_flags(fake_studio, monkeypatch):
)
assert result.exit_code == 0, result.output
so = captured["server_options"]
- assert so.temperature == 0.3 and so.top_k == 40 and so.top_p is None
- assert so.reasoning == "on"
- assert so.reasoning_effort is None
+ assert so.temperature is None and so.top_k is None and so.reasoning is None
+ assert json.loads(captured["env"]["CLAUDE_CODE_EXTRA_BODY"]) == {
+ "temperature": 0.3,
+ "top_k": 40,
+ "enable_thinking": True,
+ }
def test_connect_model_bare_id_matches_loaded_without_reload(fake_studio):
@@ -6560,8 +6868,9 @@ def test_dsh_permission_mode_overrides_an_inherited_bypass(
def test_start_dsh_forwards_reasoning_effort(fake_studio, monkeypatch):
- # --reasoning-effort is a shared server option: it must reach ServerOptions rather
- # than pass through to `dsh web`, which does not accept it.
+ # --reasoning-effort is a shared option: it must reach the dsh config rather than
+ # pass through to `dsh web`, which does not accept it.
+ yaml = pytest.importorskip("yaml")
monkeypatch.setenv("UNSLOTH_STUDIO_URL", "http://127.0.0.1:8888")
monkeypatch.setattr(start, "find_studio_server", lambda: None)
captured = {}
@@ -6589,6 +6898,7 @@ def test_start_dsh_forwards_reasoning_effort(fake_studio, monkeypatch):
**kwargs,
):
captured["command"] = command
+ captured["patch"] = Path(command[command.index("--patch") + 1]).read_text()
return SimpleNamespace(returncode = 0)
monkeypatch.setattr(start.subprocess, "run", run)
@@ -6598,8 +6908,10 @@ def test_start_dsh_forwards_reasoning_effort(fake_studio, monkeypatch):
["dsh", "--model", "unsloth/gemma-4-E2B-it-GGUF", "--reasoning-effort", "high"],
)
assert result.exit_code == 0, result.output
- assert captured["server_options"].reasoning_effort == "high"
+ assert captured["server_options"].reasoning_effort is None
assert "--reasoning-effort" not in captured["command"]
+ provider = yaml.safe_load(captured["patch"])[0]["config"]["providers"][start._DSH_PROVIDER]
+ assert provider["compat"]["chatTemplateKwargs"] == {"reasoning_effort": "high"}
# ── WSLENV path translation + PowerShell quoting (helper units) ──