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: stop telling the model it is sandboxed under Full access (#8562)
Daniel Handac7b51a057c
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex fe52585cc63..2afaa4173b9 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -8939,6 +8939,107 @@ def _build_sandbox_paths_note() -> str:)+# Full access (permission_mode='full') edits, applied to the sandboxed text+# rather than writing a second copy of it. Everything the two modes share -- the+# relative-path advice, the persisted workdir, the download-link note -- is prose+# that gets tuned over time, and a parallel copy would drift out of sync in+# silence. Only the claims the sandbox makes true are touched. A rewording that+# stops one of these matching is caught by test_full_access_tool_prompt.py, which+# asserts the sandboxed markers are gone from the result on both platforms.+_FULL_ACCESS_SUBSTITUTIONS = (+ # The only sentence in the python description that names the sandbox. Just+ # dropped, not reworded: where the code runs is said once, by the paths note+ # below, which both tools carry.+ ("Execute Python code in a sandbox and", "Execute Python code and"),+ # POSIX: a blanket denial is wrong with the sandbox off, and so is a blanket+ # promise. POSIX has no sentence saying where the code runs, so it is added+ # here; Windows already has one.+ (+ "; absolute paths like /mnt/data or /tmp/outputs do not exist.",+ ". This runs wherever Unsloth Studio is running, which may be a remote host "+ "or a container with only some paths mounted.{clause}",+ ),+ # Windows already says where the code runs and never denies absolute paths,+ # so there is nothing false to remove; state the capability instead. "the+ # user's own machine" is narrowed at the same time: --secure and -H 0.0.0.0+ # are documented remote modes (README), and the tools run on the host serving+ # Studio, which is then not the device the user is looking at.+ (+ " You are on Windows, and this runs on the user's own machine.",+ " You are on Windows, and this runs wherever Unsloth Studio is running, "+ "which may be a remote host or a container with only some paths "+ "mounted.{clause}",+ ),+)+++# What "the sandbox is off" actually means for paths, per tool. Shared by both+# platform substitutions: the split is the shim, not the OS. _build_bypass_env+# keeps _SANDBOX_SITE_DIR on PYTHONPATH for BOTH tools, so sitecustomize.py still+# loads, and being a CPython startup hook is what separates them. Measured:+#+# python, parent exists -> writes the real absolute path+# python, absent prefix -> _remap keeps the SUFFIX under the workdir+# (/mnt/data/reports/out.csv -> ./reports/out.csv)+# and returns before the generic fallback, so no+# basename collapse and no anti-clobber+# python, other missing parent -> the fallback keeps only the base name, and+# raises when an UNRELATED file holds it; the+# .unsloth_sandbox_remap.json sidecar lets a rewrite+# of the same invented path re-serve its own target+# python, prefix present -> a real /mnt/data mount is never shadowed, so a+# prefix is special only while absent, which is why+# the clause names one inside a conditional and+# never categorically+# python, unpatched API -> only open/io.open/os.open and the mkdir family are+# wrapped: os.rename and os.symlink raise, while+# shutil.copy writes the rewritten file through open+# and then raises in copymode+# terminal -> the shell's own rules, except for Python it+# launches, which is patched like the python tool+_FULL_ACCESS_CLAUSE = {+ "python": (+ " The code sandbox is disabled, so absolute paths under a directory that "+ "exists do resolve. Two different rewrites apply when the directory does "+ "not exist: under a code-interpreter convention prefix (/mnt/data, "+ "/mnt/outputs, /tmp/outputs, /home/sandbox, /workspace) the rest of the "+ "path is kept relative to the working directory, replacing any file "+ "already sitting there; under any other missing directory only the base "+ "name is kept, and the write fails outright if that name is taken by an "+ "unrelated file, though rewriting the same absolute path just replaces "+ "what your own earlier call left there. Both reach only open() and the "+ "mkdir calls, so os.rename, os.symlink and the like are never rewritten "+ "and simply fail, and a helper such as shutil.copy can write the "+ "rewritten file and still raise on a later step. Report where a file "+ "actually landed rather than the path you asked for."+ ),+ "terminal": (+ " The code sandbox is disabled, so absolute paths do resolve as the shell "+ "resolves them. Python you launch from here is the exception: it loads the "+ "same shim as the python tool and gets the same rewrites, so a create "+ "under a directory that does not exist lands in the working directory."+ ),+}+++def _to_full_access(description: str, tool_name: str) -> str:+ """Rewrite a sandboxed tool description for Full access.++ Under bypass_permissions the loops pass disable_sandbox=True:+ _build_bypass_env / _bypass_preexec skip the static analysis, the command+ blocklist and the rlimits, so the host filesystem really is reachable.+ Handing a model the sandboxed text in that mode makes it answer "I am+ sandboxed and cannot see your files" to a question one tool call would have+ answered. Untouched clauses are the ones still true in both modes: the+ workdir is the per-session dir either way (_build_bypass_env repoints HOME /+ TMPDIR / TEMP / TMP at it), and so is the download-link note.+ """+ clause = _FULL_ACCESS_CLAUSE[tool_name]+ for sandboxed, full_access in _FULL_ACCESS_SUBSTITUTIONS:+ description = description.replace(sandboxed, full_access.format(clause = clause))+ return description++def _build_terminal_shell_note() -> str:"""Shell-specific note, on the TERMINAL description only.@@ -9007,6 +9108,57 @@ TERMINAL_TOOL = {},}+# Full access runs these two without the sandbox, so it gets its own pair of+# schemas rather than a per-request rebuild: the descriptions are+# platform-derived constants either way. The sandboxed pair stays the module+# default, so every existing importer keeps the safe wording. The shell note is+# unaffected by the substitutions and carries through as-is.+PYTHON_TOOL_FULL_ACCESS = {+ "type": "function",+ "function": {+ **PYTHON_TOOL["function"],+ "description": _to_full_access(PYTHON_TOOL["function"]["description"], "python"),+ },+}++TERMINAL_TOOL_FULL_ACCESS = {+ "type": "function",+ "function": {+ **TERMINAL_TOOL["function"],+ "description": _to_full_access(TERMINAL_TOOL["function"]["description"], "terminal"),+ },+}++_FULL_ACCESS_TOOL_BY_NAME = {+ "python": PYTHON_TOOL_FULL_ACCESS,+ "terminal": TERMINAL_TOOL_FULL_ACCESS,+}+++def apply_full_access_tool_descriptions(tools: list[dict]) -> list[dict]:+ """Swap python/terminal for their Full access schemas.++ Only the two sandboxed built-ins are touched; web_search, render_html,+ search_knowledge_base and MCP tools are passed through untouched, and a list+ without either built-in is returned as-is so callers can apply this+ unconditionally. The input list is never mutated -- ALL_TOOLS entries are+ module globals shared across requests.+ """+ if not tools:+ return tools+ swapped = False+ out: list[dict] = []+ for tool in tools:+ name = (tool.get("function") or {}).get("name") if isinstance(tool, dict) else None+ replacement = _FULL_ACCESS_TOOL_BY_NAME.get(name)+ if replacement is None:+ out.append(tool)+ else:+ out.append(replacement)+ swapped = True+ return out if swapped else tools++RENDER_HTML_TOOL = {"type": "function","function": {diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 5071e27673f..65353dccfcb 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -1714,6 +1714,33 @@ class ChatCountTokensRequest(BaseModel):None,description = "[x-unsloth] Strip leaked tool-call markup from replayed history",)+ permission_mode: Optional[str] = Field(+ None,+ description = "[x-unsloth] Permission level the completion would send. Only 'full' changes "+ "the prompt: it swaps the python/terminal descriptions for the unsandboxed pair and adds a "+ "sentence to the tool nudge, so a count that omits it prices a prompt the completion will "+ "not send.",+ )+ bypass_permissions: Optional[bool] = Field(+ None,+ description = "[x-unsloth] Equivalent of permission_mode='full'. Declared explicitly (not "+ "left to extra='allow') so an omitted flag reads as None instead of raising AttributeError.",+ )++ @field_validator("permission_mode", mode = "before")+ @classmethod+ def _coerce_permission_mode(cls, value: Any) -> Any:+ return _normalize_permission_mode(value)++ @model_validator(mode = "after")+ def _fold_full_permission_into_bypass(self) -> "ChatCountTokensRequest":+ """Mirrors ChatCompletionRequest: the prompt builders read only the+ bypass flag, so 'full' has to reach them the same way here."""+ if self.permission_mode == "full":+ self.bypass_permissions = True+ elif self.bypass_permissions:+ self.permission_mode = "full"+ return selfclass ToolConfirmRequest(BaseModel):diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 46ba6e78c61..d6cbcee4d4b 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -3096,6 +3096,35 @@ _TOOL_CODE_TIP = ("Use code execution for math, calculations, data processing, or to parse ""and analyze information from tool results.")+# Full access only, and only alongside python/terminal. The schemas alone do not+# undo the model's prior: asked "can you see the files on my laptop" it answers+# "no, I am sandboxed" from training data rather than reading its own tool list,+# so the environment is stated outright and the guess sent to a tool call.+# Fixed order so the sentence reads the same whichever way the caller listed them.+_LOCAL_CODE_TOOLS = ("python", "terminal")+++def _full_access_tip(code_tools: list[str]) -> str:+ """The Full access sentence, naming only the code tools actually selected.++ enabled_tools=["python"] leaves terminal out of the request's schemas, so+ naming it here would advertise a tool the loop would refuse to run.+ """+ if len(code_tools) == 1:+ subject = f"The {code_tools[0]} tool runs"+ else:+ subject = "The " + " and ".join(code_tools) + " tools run"+ return (+ subject + " where Unsloth Studio is running, with the code sandbox and the "+ "approval prompts disabled, so you can inspect and change whatever that "+ "process can reach. That is not necessarily the device the user is viewing "+ "this on, and it may be a remote host or a container that mounts only some "+ "of its host's paths. When asked what you can see or do, check with a tool "+ "call rather than assuming you are isolated from it, and report what the "+ "call actually returned rather than what a whole machine would hold."+ )++_TOOL_ARTIFACT_TIP = ("For HTML, CSS, or JavaScript canvas requests, call render_html once when ""it is available with one complete self-contained HTML document in the code "@@ -3105,17 +3134,29 @@ _TOOL_ARTIFACT_TIP = ()-def _build_tool_action_nudge(*, tools: list[dict], model_name: str) -> str:+def _build_tool_action_nudge(+ *,+ tools: list[dict],+ model_name: str,+ full_access: bool = False,+ full_access_only: bool = False,+) -> str:+ """``full_access_only`` returns the Full access sentence alone, for a caller+ that wants to state the environment without also introducing the general+ tool guidance (and the date) to a path that has never carried it."""tool_names = {(tool.get("function") or {}).get("name")for tool in toolsif isinstance(tool, dict) and isinstance(tool.get("function"), dict)}has_web = "web_search" in tool_names- has_code = "python" in tool_names or "terminal" in tool_names+ code_tools = [name for name in _LOCAL_CODE_TOOLS if name in tool_names]+ has_code = bool(code_tools)has_artifact = "render_html" in tool_namesif not (has_web or has_code or has_artifact):return ""+ if full_access_only:+ return _full_access_tip(code_tools) if (full_access and has_code) else ""model_size_b = _extract_model_size_b(model_name)compact_web_tip = model_size_b is not None and model_size_b < 9@@ -3124,6 +3165,8 @@ def _build_tool_action_nudge(*, tools: list[dict], model_name: str) -> str:tool_tip_parts.append(_TOOL_WEB_COMPACT_TIP if compact_web_tip else _TOOL_WEB_EXPANDED_TIP)if has_code:tool_tip_parts.append(_TOOL_CODE_TIP)+ if full_access:+ tool_tip_parts.append(_full_access_tip(code_tools))if has_artifact:tool_tip_parts.append(_TOOL_ARTIFACT_TIP)return (@@ -3152,8 +3195,16 @@ async def _select_request_tools(caller's opt-in (empty when MCP-only), the RAG tool dropped without aretrieval scope, then enabled MCP tools appended. An empty result means thecaller should skip the tool loop, so a model-emitted built-in call can't- piggy-back on the empty allow-list."""- from core.inference.tools import ALL_TOOLS, get_enabled_mcp_tools+ piggy-back on the empty allow-list.++ Under Full access the python/terminal schemas are swapped for the ones that+ describe the unsandboxed run, since that is what the loop actually does+ (disable_sandbox = bypass_permissions)."""+ from core.inference.tools import (+ ALL_TOOLS,+ apply_full_access_tool_descriptions,+ get_enabled_mcp_tools,+ )if not tools_on:# MCP-only request: skip built-ins, leave room for MCP tools.@@ -3166,6 +3217,11 @@ async def _select_request_tools(# Drop the RAG tool without a scope: nothing to search over.if not payload.rag_scope:tools = [t for t in tools if t["function"]["name"] != "search_knowledge_base"]+ # Built-ins only, so this runs before the MCP append: an MCP tool's+ # description is the server's to write, and Full access says nothing about+ # how that server runs.+ if payload.bypass_permissions:+ tools = apply_full_access_tool_descriptions(tools)if mcp_allowed:tools = tools + await get_enabled_mcp_tools()return tools@@ -11337,6 +11393,21 @@ async def _proxy_to_external_provider(# The Studio loop owns its schemas. Do not also expose a caller-supplied# catalog: Codex would return calls that this server is not authorized to run.tool_payloads = studio_tool_payloads+ # This path runs python/terminal locally too (disable_sandbox =+ # bypass_permissions), so it has the same false-isolation problem.+ # Only the Full access sentence is added: the path has never carried+ # the general tool nudge, and widening it would change every+ # non-Full-access Codex run as a side effect.+ if payload.bypass_permissions:+ _codex_full_access_nudge = _build_tool_action_nudge(+ tools = studio_tool_payloads,+ model_name = model,+ full_access = True,+ full_access_only = True,+ )+ chat_messages = _append_to_codex_instructions(+ chat_messages, _codex_full_access_nudge+ )cancel_event = threading.Event()cancel_keys = tuple(key for key in (payload.cancel_id, payload.session_id) if key)@@ -12683,6 +12754,7 @@ async def openai_chat_completions(_nudge = _build_tool_action_nudge(tools = tools_to_use,model_name = model_name,+ full_access = bool(payload.bypass_permissions),)# Nudge the model to ground in attached documents instead of memory.@@ -14184,6 +14256,7 @@ async def openai_chat_completions(_sf_nudge = _build_tool_action_nudge(tools = _sf_tools_to_use,model_name = model_name,+ full_access = bool(payload.bypass_permissions),)# RAG nudge, mirroring the GGUF path.@@ -18095,6 +18168,28 @@ def _validate_anthropic_client_tools(tools) -> None:)+def _append_to_codex_instructions(messages: list[dict], addition: str) -> list[dict]:+ """Append text to the leading system message, or prepend one.++ Not _append_to_system_message: that one also accepts a `developer` turn, but+ _responses_input folds only `system` turns into the Responses instructions+ and drops every other role bar user/assistant/tool, so text parked on a+ developer message never reaches the model. `developer` is an accepted+ ChatMessage role, so a request can carry one and no system turn at all.+ """+ if not addition:+ return messages+ copied = [dict(msg) for msg in messages]+ for msg in copied:+ if msg.get("role") != "system":+ continue+ content = msg.get("content", "")+ if isinstance(content, str):+ msg["content"] = content.rstrip() + "\n\n" + addition+ return copied+ return [{"role": "system", "content": addition}, *copied]++def _append_to_system_message(messages: list[dict], addition: str) -> list[dict]:"""Append text to the leading system/developer message, or prepend one."""if not addition:@@ -18224,6 +18319,7 @@ async def chat_count_tokens(_build_tool_action_nudge(tools = tools_to_use,model_name = _llama_public_model_id(llama_backend, payload.model),+ full_access = bool(payload.bypass_permissions),),tools_to_use,rag_scope = payload.rag_scope,@@ -18939,7 +19035,7 @@ async def anthropic_messages(err_type = "invalid_request_error",),)- from core.inference.tools import ALL_TOOLS+ from core.inference.tools import ALL_TOOLS, apply_full_access_tool_descriptions# ask/auto (and an omitted mode selecting a gate-needing terminal/python# tool) were already rejected before the auto-switch above, so an invalid@@ -18950,11 +19046,17 @@ async def anthropic_messages(requested_studio_tools,payload.enabled_tools,)+ # Mirrors _select_request_tools: this path builds its own selection, so+ # the Full access swap has to be repeated rather than inherited.+ _full_access = bool(getattr(payload, "bypass_permissions", False))+ if _full_access:+ openai_tools = apply_full_access_tool_descriptions(openai_tools)# Build tool-use system prompt nudge (same logic as /chat/completions)_nudge = _build_tool_action_nudge(tools = openai_tools,model_name = model_name,+ full_access = _full_access,)if _nudge:diff --git a/studio/backend/tests/test_full_access_tool_prompt.py b/studio/backend/tests/test_full_access_tool_prompt.pynew file mode 100644index 00000000000..b315e72b7ea--- /dev/null+++ b/studio/backend/tests/test_full_access_tool_prompt.py@@ -0,0 +1,407 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""What the model is TOLD about its environment under Full access.++permission_mode='full' folds to bypass_permissions=True, which the tool loops+pass on as disable_sandbox=True: the static analysis, the command blocklist and+the rlimit pre-exec are all skipped and absolute host paths resolve. The+python/terminal schemas used to be module constants describing the sandboxed+run regardless, and the tool nudge never mentioned the mode at all, so the model+was told it was isolated from a machine it could in fact read. Asked "are you+able to see the files on my laptop", it answered "no, I operate in a sandboxed+environment" without ever calling a tool.++These tests pin the two halves of the fix: the schemas swap under Full access,+and the nudge states the mode so the model checks instead of guessing. Every+other mode keeps the sandboxed wording verbatim.+"""++import asyncio+import sys++import pytest++from core.inference import tools+from core.inference.tools import (+ ALL_TOOLS,+ PYTHON_TOOL,+ PYTHON_TOOL_FULL_ACCESS,+ TERMINAL_TOOL,+ TERMINAL_TOOL_FULL_ACCESS,+ apply_full_access_tool_descriptions,+)+from models.inference import ChatCompletionRequest, ChatCountTokensRequest+from routes.inference import (+ _append_to_codex_instructions,+ _build_tool_action_nudge,+ _full_access_tip,+ _select_request_tools,+)+++def _desc(tool: dict) -> str:+ return tool["function"]["description"]+++def _named(tools: list[dict], name: str) -> dict:+ return next(t for t in tools if t["function"]["name"] == name)+++# ── Schemas ───────────────────────────────────────────────────────────+++def test_sandboxed_descriptions_are_unchanged():+ """The default pair is what every existing importer gets."""+ assert "in a sandbox" in _desc(PYTHON_TOOL)+ assert "do not exist" in _desc(PYTHON_TOOL) or "Windows" in _desc(PYTHON_TOOL)+ assert "return stdout/stderr" in _desc(TERMINAL_TOOL)+++ "tool",+ [PYTHON_TOOL_FULL_ACCESS, TERMINAL_TOOL_FULL_ACCESS],+ ids = ["python", "terminal"],+)+def test_full_access_descriptions_drop_the_isolation_claim(tool):+ description = _desc(tool)+ assert "in a sandbox" not in description+ # The one claim that is outright false with the sandbox off.+ assert "do not exist" not in description+ assert "sandbox is disabled" in description+ assert "wherever Unsloth Studio is running" in description+ # Docker is a documented deployment, where only mounted paths are visible,+ # so the reach is the Studio process's, not a whole machine's.+ assert "container with only some paths mounted" in description+ # The remote modes (--secure / -H 0.0.0.0, README) put the tools on the host+ # serving Studio, not on the device the user is looking at, so the prompt+ # must not claim the two are the same.+ assert "user's own machine" not in description+ # The workdir really is still the per-session dir in bypass mode+ # (_build_bypass_env repoints HOME/TMPDIR/TEMP/TMP at it), so the relative+ # path advice and the download-link note both have to survive.+ assert "persists for this conversation" in description+ assert "download link" in description+++def test_full_access_schemas_keep_name_and_parameters():+ """Only the description changes: a differing name or schema would break the+ dispatcher and every caller that matches on them."""+ for sandboxed, full in (+ (PYTHON_TOOL, PYTHON_TOOL_FULL_ACCESS),+ (TERMINAL_TOOL, TERMINAL_TOOL_FULL_ACCESS),+ ):+ assert full["type"] == sandboxed["type"]+ assert full["function"]["name"] == sandboxed["function"]["name"]+ assert full["function"]["parameters"] == sandboxed["function"]["parameters"]++[email protected]("platform", ["linux", "darwin", "win32"])[email protected]("tool_name", ["python", "terminal"])+def test_the_substitutions_land_on_every_platform(monkeypatch, platform, tool_name):+ """The module constants are built once for the host platform, so a Linux+ runner would never exercise the Windows branch. Rebuild the note per+ platform and re-derive, which is also the guard against a rewording of+ _build_sandbox_paths_note silently turning the substitutions into no-ops:+ the sandboxed markers would survive into the result below."""+ monkeypatch.setattr(sys, "platform", platform)+ sandboxed = "Execute Python code in a sandbox and return stdout/stderr." + (+ tools._build_sandbox_paths_note()+ )+ full = tools._to_full_access(sandboxed, tool_name)++ assert full != sandboxed+ assert "in a sandbox" not in full+ assert "do not exist" not in full+ assert "sandbox is disabled" in full+ assert "do resolve" in full+ assert "user's own machine" not in full+ assert "wherever Unsloth Studio is running" in full+ # _build_bypass_env keeps _SANDBOX_SITE_DIR on PYTHONPATH, so sitecustomize+ # still heals these onto the workdir under Full access. A blanket "absolute+ # paths resolve" would have the model report a write that went elsewhere.+ # The clause is per tool on BOTH platforms: the split is the shim, not the OS.+ # sitecustomize is a CPython startup hook, so it patches python (and any+ # python the terminal launches) wherever it runs, while a plain shell gets+ # nothing. Measured: parent exists -> real path; parent missing -> <cwd>/base,+ # unless that name is taken, where it raises.+ if tool_name == "python":+ assert "absolute paths under a directory that exists do resolve" in full+ # Two branches, measured: an absent convention prefix keeps the SUFFIX+ # (/mnt/data/reports/out.csv -> ./reports/out.csv) and overwrites an+ # existing file; any other missing parent keeps only the base name and+ # raises when that name is taken. Describing one as both was wrong.+ assert "the rest of the path is kept relative to the working directory" in full+ assert "replacing any file already sitting there" in full+ assert "only the base name is kept" in full+ # Measured: a DIFFERENT invented path with the same basename raises, but+ # rewriting the SAME invented path is permitted via the remap sidecar.+ assert "fails outright if that name is taken by an unrelated file" in full+ assert "rewriting the same absolute path just replaces" in full+ # Only open/io.open/os.open and the mkdir family are wrapped. Measured:+ # os.rename and os.symlink raise, and shutil.copy writes the rewritten+ # file through open and then raises in copymode.+ assert "reach only open() and the mkdir calls" in full+ assert "shutil.copy can write the rewritten file and still raise" in full+ else:+ assert "absolute paths do resolve as the shell resolves them" in full+ # _build_bypass_env sets PYTHONPATH for the terminal subprocess too, so+ # python launched from a shell command carries the same shim.+ assert "Python you launch from here is the exception" in full+ assert "gets the same rewrites" in full+ # No categorical claim about the convention paths in either: on a host where+ # /mnt/data is a real mount the shim never shadows it, so "not real" is wrong,+ # and the parent-directory rule already covers the absent case.+ # /mnt/data may be named, but only inside the conditional describing what+ # happens while it is ABSENT; a real mount is never shadowed, so no+ # categorical "not real" claim may survive.+ assert "not real there" not in full+ if tool_name == "python":+ assert "when the directory does not exist" in full+ # True in both modes, so untouched.+ assert "persists for this conversation" in full+ assert "download link" in full+ if platform == "win32":+ assert "You are on Windows" in full+++def test_python_full_access_description_still_omits_the_shell():+ """Same reason as the sandboxed one: naming a shell there points a model at+ subprocess/os.system instead of the terminal tool."""+ assert "shell" not in _desc(PYTHON_TOOL_FULL_ACCESS).lower()+++def test_terminal_full_access_keeps_the_shell_note():+ """The shell note is platform-derived and applies in either mode; dropping+ it on Windows brings back the cmd/bash confusion it exists to prevent."""+ for marker in ("cmd, not bash", "bash (Git for Windows)"):+ assert (marker in _desc(TERMINAL_TOOL)) == (marker in _desc(TERMINAL_TOOL_FULL_ACCESS))+++def test_swap_leaves_other_tools_alone_and_does_not_mutate():+ before = list(ALL_TOOLS)+ swapped = apply_full_access_tool_descriptions(list(ALL_TOOLS))+ assert _named(swapped, "python") is PYTHON_TOOL_FULL_ACCESS+ assert _named(swapped, "terminal") is TERMINAL_TOOL_FULL_ACCESS+ for name in ("web_search", "render_html", "search_knowledge_base"):+ assert _named(swapped, name) is _named(ALL_TOOLS, name)+ # The module global is shared across requests, so the swap must not touch it.+ assert ALL_TOOLS == before+ assert _desc(_named(ALL_TOOLS, "python")) == _desc(PYTHON_TOOL)+++def test_swap_is_a_no_op_without_the_sandboxed_builtins():+ tools = [t for t in ALL_TOOLS if t["function"]["name"] == "web_search"]+ assert apply_full_access_tool_descriptions(tools) is tools+ assert apply_full_access_tool_descriptions([]) == []+++# ── Request-level selection ───────────────────────────────────────────+++def _select(**payload_kwargs) -> list[dict]:+ payload = ChatCompletionRequest(+ model = "test-model",+ messages = [{"role": "user", "content": "hi"}],+ enable_tools = True,+ enabled_tools = ["python", "terminal", "web_search"],+ stream = True,+ **payload_kwargs,+ )+ return asyncio.run(_select_request_tools(payload, tools_on = True, mcp_allowed = False))++[email protected]("mode", ["ask", "auto", "off"])+def test_non_full_modes_keep_the_sandboxed_schemas(mode):+ tools = _select(permission_mode = mode)+ assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL)+ assert _desc(_named(tools, "terminal")) == _desc(TERMINAL_TOOL)+++def test_omitted_mode_keeps_the_sandboxed_schemas():+ tools = _select()+ assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL)+++ "payload_kwargs",+ [{"permission_mode": "full"}, {"bypass_permissions": True}],+ ids = ["permission_mode", "legacy_bypass_flag"],+)+def test_full_access_selection_swaps_the_schemas(payload_kwargs):+ """Both spellings fold to bypass_permissions=True, so both must swap."""+ tools = _select(**payload_kwargs)+ assert _desc(_named(tools, "python")) == _desc(PYTHON_TOOL_FULL_ACCESS)+ assert _desc(_named(tools, "terminal")) == _desc(TERMINAL_TOOL_FULL_ACCESS)+ assert _named(tools, "web_search") is _named(ALL_TOOLS, "web_search")+++# ── Nudge ─────────────────────────────────────────────────────────────++_CODE_TOOLS = [PYTHON_TOOL, TERMINAL_TOOL]+_WEB_ONLY = [t for t in ALL_TOOLS if t["function"]["name"] == "web_search"]+++def test_nudge_is_unchanged_without_full_access():+ plain = _build_tool_action_nudge(tools = _CODE_TOOLS, model_name = "test-8B")+ assert "sandbox" not in plain+ assert "code execution" in plain+ assert plain == _build_tool_action_nudge(+ tools = _CODE_TOOLS, model_name = "test-8B", full_access = False+ )+++def test_nudge_states_the_environment_under_full_access():+ nudge = _build_tool_action_nudge(tools = _CODE_TOOLS, model_name = "test-8B", full_access = True)+ assert "where Unsloth Studio is running" in nudge+ assert "code sandbox and the approval prompts disabled" in nudge+ # Containerized Studio sees only its mounts, so the claim is scoped to what+ # the process can reach rather than to the machine.+ assert "whatever that process can reach" in nudge+ assert "container that mounts only some" in nudge+ # Scoped to the two local tools: execute_tool passes disable_sandbox to+ # python/terminal only, web_search is a network call, and an MCP tool may run+ # on a remote server, so an unqualified "tool calls run here" is wrong when+ # any of those are enabled alongside.+ assert nudge.count("The python and terminal tools run where") == 1+++ ("enabled", "expected"),+ [+ (["python"], "The python tool runs where"),+ (["terminal"], "The terminal tool runs where"),+ (["python", "terminal"], "The python and terminal tools run where"),+ # Order comes from _LOCAL_CODE_TOOLS, not from the caller's list.+ (["terminal", "python"], "The python and terminal tools run where"),+ ],+ ids = ["python_only", "terminal_only", "both", "reversed"],+)+def test_the_tip_names_only_the_selected_code_tools(enabled, expected):+ """enabled_tools=["python"] leaves terminal out of the request's schemas, so+ naming it would advertise a tool the loop would refuse to run."""+ tools = [t for t in ALL_TOOLS if t["function"]["name"] in enabled]+ nudge = _build_tool_action_nudge(tools = tools, model_name = "test-8B", full_access = True)+ assert expected in nudge+ for absent in {"python", "terminal"} - set(enabled):+ assert f"The {absent} tool runs where" not in nudge+ assert f"and {absent} tools run where" not in nudge+ # Studio can be served remotely, so the tools' host is not necessarily the+ # device in front of the user.+ assert "not necessarily the device the user is viewing this on" in nudge+ # The actual reported failure: the model asserted isolation instead of+ # checking, so the nudge has to redirect that guess to a tool call.+ assert "check with a tool call" in nudge+++def test_full_access_only_returns_the_sentence_alone():+ """The Codex studio-tools path has never carried the general tool nudge, so+ it takes the Full access sentence without the date or the base guidance."""+ only = _build_tool_action_nudge(+ tools = _CODE_TOOLS, model_name = "test-8B", full_access = True, full_access_only = True+ )+ assert only == _full_access_tip(["python", "terminal"])+ assert "The current date is" not in only+ assert "Tools are available when they materially improve" not in only+++ "kwargs",+ [{"full_access": False}, {"full_access": True, "tools": _WEB_ONLY}],+ ids = ["not_full_access", "no_code_tool"],+)+def test_full_access_only_is_empty_when_it_does_not_apply(kwargs):+ tools = kwargs.pop("tools", _CODE_TOOLS)+ assert (+ _build_tool_action_nudge(tools = tools, model_name = "test-8B", full_access_only = True, **kwargs)+ == ""+ )+++def test_full_access_tip_needs_a_code_tool():+ """web_search alone runs nothing locally, so the sandbox sentence would be+ noise (and false)."""+ nudge = _build_tool_action_nudge(tools = _WEB_ONLY, model_name = "test-8B", full_access = True)+ assert "where Unsloth Studio is running" not in nudge+ assert nudge == _build_tool_action_nudge(tools = _WEB_ONLY, model_name = "test-8B")+++def test_full_access_tip_needs_tools_at_all():+ assert _build_tool_action_nudge(tools = [], model_name = "test-8B", full_access = True) == ""+++# ── Token count parity ────────────────────────────────────────────────+++def _count_request(**kwargs) -> ChatCountTokensRequest:+ return ChatCountTokensRequest(+ model = "test-model",+ messages = [{"role": "user", "content": "hi"}],+ enable_tools = True,+ enabled_tools = ["python", "terminal"],+ **kwargs,+ )+++# ── Codex studio-tools instructions ───────────────────────────────────+++def test_codex_instructions_skip_a_developer_message():+ """_responses_input folds only `system` turns into the Responses+ instructions and drops every other role bar user/assistant/tool, so a nudge+ appended to a `developer` turn would never reach the model. `developer` is an+ accepted ChatMessage role, so this shape is reachable."""+ messages = [+ {"role": "developer", "content": "house style"},+ {"role": "user", "content": "hi"},+ ]+ out = _append_to_codex_instructions(messages, "NUDGE")+ assert out[0] == {"role": "system", "content": "NUDGE"}+ assert out[1] == messages[0]+ assert messages[0]["content"] == "house style"+++def test_codex_instructions_extend_an_existing_system_message():+ messages = [{"role": "system", "content": "base"}, {"role": "user", "content": "hi"}]+ out = _append_to_codex_instructions(messages, "NUDGE")+ assert out[0]["content"] == "base\n\nNUDGE"+ assert len(out) == 2+ assert messages[0]["content"] == "base"+++def test_codex_instructions_are_a_no_op_without_an_addition():+ messages = [{"role": "user", "content": "hi"}]+ assert _append_to_codex_instructions(messages, "") is messages+++def test_count_request_reads_the_flag_when_omitted():+ """The count route reaches for payload.bypass_permissions unconditionally,+ so the field has to exist rather than arrive via extra='allow'."""+ assert _count_request().bypass_permissions is None+++ "kwargs",+ [{"permission_mode": "full"}, {"bypass_permissions": True}],+ ids = ["permission_mode", "legacy_bypass_flag"],+)+def test_count_request_folds_full_access(kwargs):+ request = _count_request(**kwargs)+ assert request.bypass_permissions is True+ assert request.permission_mode == "full"++[email protected]("mode", ["ask", "auto", "off"])+def test_count_request_leaves_other_modes_alone(mode):+ assert _count_request(permission_mode = mode).bypass_permissions is None+++def test_count_request_selection_matches_the_completion():+ """The whole point of carrying the flag: the counted tool list is the one+ the completion will render."""+ counted = asyncio.run(+ _select_request_tools(+ _count_request(permission_mode = "full"), tools_on = True, mcp_allowed = False+ )+ )+ assert _desc(_named(counted, "python")) == _desc(PYTHON_TOOL_FULL_ACCESS)diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 9f486e98cc1..41c419d7d7b 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -1660,6 +1660,7 @@ export async function buildLocalTokenCountExtras(ragMode,ragTopK,autoHealToolCalls,+ bypassPermissions,} = useChatRuntimeStore.getState();if (!supportsTools) return {};@@ -1677,13 +1678,21 @@ export async function buildLocalTokenCountExtras() {// Explicit false, not an omitted field: the server defaults tools on for a// request that never mentions them, so every pill being off has to say so.- return { enable_tools: false };+ // The permission level rides along because `--enable-tools` still outranks+ // that false in _effective_enable_tools, so a CLI policy can inject+ // python/terminal into a pill-less request and the count would otherwise+ // price sandboxed schemas against an unsandboxed completion. Inert whenever+ // the false stands and no tool list is built.+ return { enable_tools: false, bypass_permissions: bypassPermissions };}return {enable_tools: true,// Auto-Heal off leaves leaked tool markup in the real prompt, so the count keeps it.auto_heal_tool_calls: autoHealToolCalls,+ // Full access swaps the python/terminal descriptions and adds a nudge+ // sentence, so the count needs the flag to price the same prompt.+ bypass_permissions: bypassPermissions,enabled_tools: [...(ragOn ? ["search_knowledge_base"] : []),...(toolsEnabled ? ["web_search"] : []),