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: approved host calls keep chat-installed packages, helper modules and CLIs (#14543)
Daniel Hand0c4c9feb51f
diff --git a/studio/backend/core/inference/sandbox_site/sitecustomize.py b/studio/backend/core/inference/sandbox_site/sitecustomize.pyindex 51c4b831ea3..fdedd76b0a0 100644--- a/studio/backend/core/inference/sandbox_site/sitecustomize.py+++ b/studio/backend/core/inference/sandbox_site/sitecustomize.py@@ -305,3 +305,60 @@ try:_install()except Exception: # noqa: BLE001 - a broken shim must never break user codepass++# Approved host calls keep chat-installed packages importable, including Python started by Terminal.+# Append only after the normal site setup; no .pth execution or stdlib/installed-package shadowing.+_host_packages = os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES")+if _host_packages and _host_packages not in sys.path:+ sys.path.append(_host_packages)+++# Helper modules the approved script imports by name come from the chat folder, after everything+# else, so they never shadow anything. Served by a last-resort finder for exactly those names rather+# than sys.path: site imports `usercustomize` after this file, and a library probing an optional+# import must not find a module an earlier sandboxed call planted there.+class _HostWorkdirFinder:+ _skip = frozenset(("sitecustomize", "usercustomize"))++ def __init__(self, workdir, names):+ self._workdir = workdir+ self._names = frozenset(names) - self._skip++ def find_spec(+ self,+ name,+ path = None,+ target = None,+ ):+ if path is not None or name not in self._names:+ return None+ import importlib.machinery++ spec = importlib.machinery.PathFinder.find_spec(name, [self._workdir])+ if spec is not None and spec.origin and spec.origin.endswith(".py"):+ # A requested helper's own absolute imports come from the chat folder too, as before.+ try:+ import ast++ with open(spec.origin, "rb") as f:+ tree = ast.parse(f.read())+ found = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ found.update(alias.name.split(".")[0] for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:+ found.add(node.module.split(".")[0])+ self._names = self._names | (frozenset(found) - self._skip)+ except Exception: # noqa: BLE001 - an unreadable helper just adds nothing+ pass+ return spec+++_host_workdir = os.environ.get("_UNSLOTH_HOST_WORKDIR")+_host_modules = [n for n in os.environ.get("_UNSLOTH_HOST_WORKDIR_MODULES", "").split(",") if n]+if (+ _host_workdir+ and _host_modules+ and not any(isinstance(f, _HostWorkdirFinder) for f in sys.meta_path)+):+ sys.meta_path.append(_HostWorkdirFinder(_host_workdir, _host_modules))diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 0ecd2a13f07..d02759eea79 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -10178,11 +10178,46 @@ def _requested_execution_mode(tool_execution_mode: str, disable_sandbox: bool) -_with_session_packages = os_sandbox.with_session_packages+def _script_top_level_imports(script: str) -> "list[str]":+ """Top-level module names an approved script imports by absolute name; none if it does not parse."""+ try:+ tree = ast.parse(script)+ except (SyntaxError, ValueError):+ return []+ names = set()+ for node in ast.walk(tree):+ if isinstance(node, ast.Import):+ names.update(alias.name.split(".")[0] for alias in node.names)+ elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:+ names.add(node.module.split(".")[0])+ return sorted(names)+++def _requested_chat_clis(scripts: str, text: str, dest: str) -> "str | None":+ """Copy the chat-installed CLIs whose names appear as words in *text* into *dest*; *dest* if any."""+ try:+ entries = os.listdir(scripts)+ except OSError:+ return None+ # Windows resolves commands case-insensitively.+ fold = str.lower if os.name == "nt" else str+ words = {fold(word) for word in re.findall(r"[\w.+-]+", text)}+ copied = False+ for entry in entries:+ stem = os.path.splitext(entry)[0] if os.name == "nt" else entry+ source = os.path.join(scripts, entry)+ if (fold(entry) in words or fold(stem) in words) and os.path.isfile(source):+ os.makedirs(dest, exist_ok = True)+ shutil.copy2(source, os.path.join(dest, entry))+ copied = True+ return dest if copied else None++def _host_access_launch(plan, script: "str | None") -> "tuple[tuple, dict, str]":"""argv and env for an approved host-access launch: nothing it loads comes from the sandbox-writable workdir.HOME and (for the python tool) the script move to a private per-call directory outside every workdir, and the- session packages stay off PYTHONPATH/PATH; earlier sandboxed calls can write all of those in the workdir. The+ session packages and the helpers the script imports only ever go last on sys.path/PATH; earlier sandboxed calls can write all of those in the workdir. Thecwd stays the workdir, so relative paths in the approved code resolve as before."""private = tempfile.mkdtemp(prefix = "unsloth-host-call-")@@ -10192,25 +10227,34 @@ def _host_access_launch(plan, script: "str | None") -> "tuple[tuple, dict, str]"if sys.platform == "win32":env["HOMEDRIVE"], env["HOMEPATH"] = os.path.splitdrive(private)argv = tuple(plan.argv)+ packages = os.path.join(plan.workdir, os_sandbox.SESSION_PACKAGES_RELPATH)+ if os.path.isdir(packages):+ # The trusted sitecustomize appends these after installed packages for Python and Terminal alike.+ env["_UNSLOTH_HOST_SESSION_PACKAGES"] = packages+ env["PYTHONNOUSERSITE"] = "1"+ # Chat-installed CLIs the approved call names resolve too, but only after every system executable.+ # Copies of just those: a tool probing for a command it lacks never reaches the rest of the folder.+ requested = _requested_chat_clis(+ os.path.join(packages, "Scripts" if os.name == "nt" else "bin"),+ script if script is not None else " ".join(map(str, argv)),+ os.path.join(private, ".unsloth-chat-bin"),+ )+ if requested:+ env["PATH"] = os.pathsep.join(+ part for part in (env.get("PATH", ""), requested) if part+ )if script is not None and argv:+ # Helper modules the approved script itself imports stay importable from the chat folder, after+ # everything else. Only those names: a library probing an optional import never reaches the folder.+ helpers = _script_top_level_imports(script)+ if helpers:+ env["_UNSLOTH_HOST_WORKDIR"] = plan.workdir+ env["_UNSLOTH_HOST_WORKDIR_MODULES"] = ",".join(helpers)# Written here, not read back from the workdir copy: a sandboxed call could have replaced that file.path = os.path.join(private, os.path.basename(argv[-1]))fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)with os.fdopen(fd, "w", encoding = "utf-8") as f:f.write(script)- packages = os.path.join(plan.workdir, os_sandbox.SESSION_PACKAGES_RELPATH)- if os.path.isdir(packages):- # Chat-installed packages go last on sys.path, so the sandbox-writable folder cannot shadow anything.- launcher = os.path.join(private, "unsloth_host_launch.py")- fd = os.open(launcher, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)- with os.fdopen(fd, "w", encoding = "utf-8") as f:- f.write(- "import runpy, sys\n"- f"sys.path.append({packages!r})\n"- f"sys.argv[0] = {path!r}\n"- f"runpy.run_path({path!r}, run_name = '__main__')\n"- )- path = launcherargv = (*argv[:-1], path)# The script's own folder stays off sys.path too (CPython >= 3.11).env["PYTHONSAFEPATH"] = "1"diff --git a/studio/backend/tests/test_tool_sandbox_hardening.py b/studio/backend/tests/test_tool_sandbox_hardening.pyindex a6da8626563..1e9cda403af 100644--- a/studio/backend/tests/test_tool_sandbox_hardening.py+++ b/studio/backend/tests/test_tool_sandbox_hardening.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport errnoimport os+import shleximport socketimport subprocessimport sys@@ -61,6 +62,145 @@ def test_an_approved_host_call_loads_nothing_from_the_workdir(tmp_path, monkeypaassert not os.path.exists(os.path.dirname(lines["FILE"]))+@_POSIX+def test_an_approved_terminal_call_reuses_chat_packages_without_shadowing(tmp_path, monkeypatch):+ workdir = _planted_workdir(tmp_path)+ # Terminal deliberately retains cwd imports; exercise only the session-package precedence here.+ (workdir / "csv.py").unlink()+ packages = workdir / os_sandbox.SESSION_PACKAGES_RELPATH+ (packages / "usercustomize.py").write_text("print('PLANTED usercustomize')\n", encoding = "utf-8")+ host_file = tmp_path / "notes.csv"+ host_file.write_text("a,b\n", encoding = "utf-8")+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))+ code = (+ "import chatpkg, csv, sys; "+ "print('PKG', chatpkg.VALUE); "+ "print('ROWS', list(csv.reader(open(sys.argv[1]))))"+ )+ command = "python -c " + shlex.quote(code) + " " + shlex.quote(str(host_file))+ assert tools._reaches_host_paths("terminal", command)+ for _ in range(2):+ out = tools._bash_exec(command, None, 60, "hardening-chat", host_access_approved = True)+ assert "PKG from-session-packages" in out, out+ assert "ROWS [['a', 'b']]" in out, out+ assert "PLANTED" not in out, out+++@_POSIX+def test_approved_calls_import_chat_helpers_without_shadowing_the_stdlib(tmp_path, monkeypatch):+ workdir = _planted_workdir(tmp_path)+ (workdir / "helper.py").write_text("VALUE = 'from-chat-folder'\n", encoding = "utf-8")+ for name in ("json.py", "os.py"):+ (workdir / name).write_text("print('PLANTED', __file__)\n", encoding = "utf-8")+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))+ code = "import helper, json, os; print('HELPER', helper.VALUE); print('JSON', json.dumps([1]), json.__file__)\n"+ for _ in range(2):+ out = tools._python_exec(+ code + f"open({str(tmp_path / 'host.txt')!r}, 'w').close()\n",+ None,+ 60,+ "hardening-chat",+ host_access_approved = True,+ )+ assert "HELPER from-chat-folder" in out, out+ assert "JSON [1]" in out and str(workdir) not in out.split("JSON", 1)[1], out+ assert "PLANTED" not in out, out+ # Terminal-started Python keeps importing helpers from the chat folder too.+ (workdir / "json.py").unlink()+ command = (+ "python -c "+ + shlex.quote("import helper; print('HELPER', helper.VALUE)")+ + " "+ + str(tmp_path)+ )+ assert tools._reaches_host_paths("terminal", command)+ out = tools._bash_exec(command, None, 60, "hardening-chat", host_access_approved = True)+ assert "HELPER from-chat-folder" in out, out+ assert "PLANTED" not in out, out+++def test_chat_cli_names_match_case_insensitively_on_windows(tmp_path, monkeypatch):+ scripts = tmp_path / "Scripts"+ scripts.mkdir()+ (scripts / "ruff.exe").write_bytes(b"MZ")+ (scripts / "other.exe").write_bytes(b"MZ")+ monkeypatch.setattr(tools.os, "name", "nt")+ dest = tools._requested_chat_clis(str(scripts), "RUFF check C:\\data", str(tmp_path / "bin"))+ assert dest is not None and sorted(os.listdir(dest)) == ["ruff.exe"]+++def test_chat_folder_only_supplies_the_helpers_the_script_imports(tmp_path):+ """Startup hooks and optional imports a library probes never come from the chat folder."""+ assert tools._script_top_level_imports(+ "import helper, os.path\nfrom pkg.sub import x\nfrom . import y\n"+ ) == [+ "helper",+ "os",+ "pkg",+ ]+ assert tools._script_top_level_imports("def (") == []+ workdir = tmp_path / "chat"+ workdir.mkdir()+ (workdir / "helper.py").write_text("import config\nVALUE = config.X\n", encoding = "utf-8")+ (workdir / "config.py").write_text("X = 1\n", encoding = "utf-8")+ for name in ("usercustomize.py", "optional_dep.py"):+ (workdir / name).write_text("print('PLANTED')\n", encoding = "utf-8")+ site_dir = os.path.join(os.path.dirname(tools.__file__), "sandbox_site")+ env = dict(+ os.environ,+ PYTHONPATH = site_dir,+ _UNSLOTH_HOST_WORKDIR = str(workdir),+ _UNSLOTH_HOST_WORKDIR_MODULES = "helper,usercustomize",+ )+ code = (+ "import importlib.util as u, sys, helper; "+ "print('HOOK', u.find_spec('usercustomize'), u.find_spec('optional_dep'), 'HELPER', helper.VALUE, "+ f"{str(workdir)!r} in sys.path)"+ )+ for _ in range(2):+ out = subprocess.run(+ [sys.executable, "-c", code],+ env = env,+ cwd = str(tmp_path),+ capture_output = True,+ text = True,+ timeout = 60,+ ).stdout+ assert "HOOK None None HELPER 1 False" in out, out+ assert "PLANTED" not in out, out+++@_POSIX+def test_an_approved_terminal_call_runs_chat_clis_after_system_ones(tmp_path, monkeypatch):+ workdir = _planted_workdir(tmp_path)+ bin_dir = workdir / os_sandbox.SESSION_PACKAGES_RELPATH / "bin"+ bin_dir.mkdir()+ for name, body in (+ ("chatcli", "echo CHATCLI ok"),+ ("cat", "echo PLANTED cat"),+ ("unsloth-missing-tool", "echo PLANTED probe"),+ ):+ (bin_dir / name).write_text(f"#!/bin/sh\n{body}\n", encoding = "utf-8")+ (bin_dir / name).chmod(0o755)+ host_file = tmp_path / "notes.csv"+ host_file.write_text("a,b\n", encoding = "utf-8")+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(workdir))+ # A probe for a command the call never names (`command -v`, as tools probe for ffmpeg) misses the chat folder.+ # The name is built at run time, so it never appears in the command text.+ command = (+ "chatcli && cat "+ + shlex.quote(str(host_file))+ + " && { command -v $(printf %s unsloth-missing; printf %s -tool) || echo PROBE-MISSED; }"+ )+ assert tools._reaches_host_paths("terminal", command)+ for _ in range(2):+ out = tools._bash_exec(command, None, 60, "hardening-chat", host_access_approved = True)+ assert "CHATCLI ok" in out, out+ assert "a,b" in out, out+ assert "PROBE-MISSED" in out, out+ assert "PLANTED" not in out, out++@_POSIXdef test_an_approved_host_launch_env_drops_every_workdir_input(tmp_path):workdir = _planted_workdir(tmp_path)@@ -82,7 +222,9 @@ def test_an_approved_host_launch_env_drops_every_workdir_input(tmp_path):assert prepared.env["HOME"] != str(workdir)packages = str(workdir / os_sandbox.SESSION_PACKAGES_RELPATH)assert packages not in prepared.env.get("PYTHONPATH", "").split(os.pathsep)- assert not any(part.startswith(packages) for part in prepared.env["PATH"].split(os.pathsep))+ # The chat bin folder itself is never on PATH; only CLIs the call names are, last.+ path = prepared.env["PATH"].split(os.pathsep)+ assert not any(part.startswith(packages) for part in path)assert not prepared.argv[-1].startswith(str(workdir))# The approved code, not whatever the workdir copy was replaced with.ran = subprocess.run(