Skip to content

Studio: approved host calls keep chat-installed packages, helper modules and CLIs - #14543

Merged
danielhanchen merged 9 commits into
mainfrom
studio-host-terminal-session-packages
Oct 23, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
studio-host-terminal-session-packages

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Follow-up to #14429.

Problem. If a call reaches a host path (for example, a command that reads a file in the user's home) and the user approves it, it runs outside the chat sandbox with a private HOME. #14429 also stopped loading anything from the chat folder in these calls, because sandboxed calls can write there. That broke three things that worked before #14429:

  • Python started by an approved Terminal command lost the packages installed in the chat (.unsloth-packages). In an owner chat, install openpyxl through Terminal, then approve python -c "import openpyxl ..." ~/sales.xlsx: it failed with ModuleNotFoundError. Studio: harden the tool sandbox around host launches, probes and workdir paths #14429 restored these packages for the Python tool through a small launcher, but the launcher only exists when there is a script.
  • An approved Python tool call could no longer import helper for a helper.py that an earlier call wrote into the chat folder. The script now runs from a private dir with PYTHONSAFEPATH=1, so the chat folder is not on sys.path.
  • Command-line tools that pip put in .unsloth-packages/bin (for example black file.py) were no longer found in approved calls (command not found).

Change.

  • The approved host launch puts the chat's packages folder in _UNSLOTH_HOST_SESSION_PACKAGES and the chat folder in _UNSLOTH_HOST_WORKDIR. The existing sandbox sitecustomize, which is already first on that launch's PYTHONPATH, appends the packages folder to the end of sys.path after normal site setup. The chat folder is not put on sys.path. For an approved Python tool call, the launch passes the top-level module names the script itself imports (parsed with ast), and a finder appended at the end of sys.meta_path serves only those names from the chat folder, only when nothing else provides them, and never sitecustomize or usercustomize. A library probing an optional import never reaches the chat folder. The packages folder works for the Python tool and for any Python a Terminal command starts, and it replaces the per-script launcher.
  • Chat-installed CLIs in .unsloth-packages/bin (Scripts on Windows) resolve only when the approved command or script names them: those files are copied into the call's private directory, which goes last on PATH. The chat bin folder itself is never on PATH, so a tool probing for a command it lacks (for example ffmpeg) never reaches it.
  • Both folders come after the standard library, installed packages and system executables, so nothing planted there can shadow them. A json.py or os.py in the chat folder, or a cat in .unsloth-packages/bin, is never picked up first, and an unnamed CLI there is never picked up at all. The approved script still runs from the private dir with PYTHONSAFEPATH=1. A planted usercustomize.py never runs: PYTHONNOUSERSITE=1 is set when the packages folder exists, and the chat folder finder skips startup hooks, so ~/.local packages keep working for a system Python. HOME stays private.
  • Sandboxed calls, and launches that are not approved host access, are unchanged. The env is built fresh for every launch, and sitecustomize skips a path that is already on sys.path, so repeat runs give the same result.

Terminal commands still run with the chat folder as cwd. So python -c in Terminal keeps its usual cwd-first imports, as #14429 left them.

Testing.

  • New test_an_approved_terminal_call_reuses_chat_packages_without_shadowing: an approved Terminal python -c imports a chat-installed package and reads a host file, twice. A planted usercustomize.py does not run. Fails on main, passes here.
  • New test_approved_calls_import_chat_helpers_without_shadowing_the_stdlib: an approved Python tool call imports helper.py from the chat folder, twice. Planted json.py / os.py in the chat folder are not loaded, and json comes from the standard library. An approved Terminal python -c also imports the helper. Fails without this change (ModuleNotFoundError: No module named 'helper'), passes with it.
  • New test_an_approved_terminal_call_runs_chat_clis_after_system_ones: an approved Terminal call runs a CLI from .unsloth-packages/bin. A planted cat there does not replace the system cat. Fails without this change (chatcli: command not found), passes with it.
  • test_an_approved_host_launch_env_drops_every_workdir_input now checks that the chat bin is only the last PATH entry.
  • New test_chat_folder_only_supplies_the_helpers_the_script_imports: checks the import-name parsing, and that with the chat folder exposed for helper, neither usercustomize nor an unrequested optional_dep can be found while helper imports, twice. Checked by hand against the previous finder: a planted optional_dep.py loaded there and does not now.
  • Earlier version of the same test: with the chat folder exposed, usercustomize cannot be found while helper still imports, and the chat folder is not on sys.path. Fails if the chat folder is appended to sys.path instead. Also checked by hand with the system /usr/bin/python3 (user site enabled): a planted usercustomize.py ran before this change and does not now.
  • test_tool_sandbox_hardening.py: 27 passed after the name allowlist. With test_managed_tool_confinement_hardening.py and test_sandbox_sitecustomize.py: 58 passed, 1 skipped.
  • All test_tool*.py, test_sandbox_linux.py, test_sandbox_probe.py, test_sandbox_sitecustomize.py (29 files): 1336 passed, 3 skipped.
  • test_an_approved_terminal_call_runs_chat_clis_after_system_ones now also checks that a command -v probe for a chat CLI the command never names misses the chat folder, and test_an_approved_host_launch_env_drops_every_workdir_input that the chat bin folder is not on PATH. Both fail without the CLI scoping and pass with it; test_tool_sandbox_hardening.py: 27 passed.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T12:38:27.390637Z 402f3d0 Manual request
🔒 Security Review ✅ Completed 2026-10-22T09:48:24.784809Z 7efdd55 Manual request

Security findings

Advisory findings (1)

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

The account paying for this security review has reached its Codex usage limits. The payer can check the Codex usage dashboard. For personal accounts, using credits requires enabling “Use credits for security reviews” in Code review settings. If you do not manage the paying account, contact this repository's admins.

danielhanchen added a commit that referenced this pull request Oct 21, 2026
… again (#14544)

`pre-commit.ci` is red on every PR opened or pushed since #14490 merged
(#14510, #14515, #14543 so far), and it cannot push its autofix ("a
conflict occurred when applying fixes to the pr").

#14490 landed `_run_single_flight(*args, _run = run, _lock = lock,
**kwargs)` in `unsloth/kernels/moe/grouped_gemm/interface.py` on one
line, which is not what `ruff-format-with-kwargs` produces, and
pre-commit.ci runs the hook over all files. Running the hook over all
4525 tracked Python files on main changes only this one signature.

This PR is that formatter output and nothing else. It is a fixed point:
running the hook again leaves it unchanged.

## Testing

- `tests/test_formatter_fixed_point.py` on main: fails, naming
`unsloth/kernels/moe/grouped_gemm/interface.py`.
- Same test on this branch: 16 passed.
@danielhanchen danielhanchen changed the title Studio: approved Terminal calls keep packages installed earlier in the chat Studio: approved host calls keep chat-installed packages, helper modules and CLIs Oct 22, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7efdd5514e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/backend/core/inference/tools.py Outdated
scripts = os.path.join(packages, "Scripts" if os.name == "nt" else "bin")
env["PATH"] = os.pathsep.join(part for part in (env.get("PATH", ""), scripts) if part)
# Helper modules written into the chat folder stay importable, appended after the session packages.
env["_UNSLOTH_HOST_WORKDIR"] = plan.workdir

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Disable user customization before appending the workdir

When a chat has no .unsloth-packages directory, PYTHONNOUSERSITE is not set, but this variable still causes sitecustomize to append the sandbox-writable workdir during interpreter startup. Python subsequently imports usercustomize, so a usercustomize.py planted by an earlier sandboxed call executes implicitly in an approved Python host-access call before the approved script, with access to host paths. Set PYTHONNOUSERSITE unconditionally whenever _UNSLOTH_HOST_WORKDIR is exposed.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 868a2da. The chat folder is no longer put on sys.path. A finder appended at the end of sys.meta_path serves top-level helper modules from it and never resolves sitecustomize or usercustomize, so a planted usercustomize.py cannot run even with the user site enabled. PYTHONNOUSERSITE stays as it was, so ~/.local packages keep working for Terminal Python. Covered by test_chat_folder_never_supplies_startup_hooks, which fails on the previous commit.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ Codex Security Review

Here are some automated security review suggestions for this pull request.

Reviewed commit: 7efdd5514e

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment on lines +313 to +317
os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES"),
os.environ.get("_UNSLOTH_HOST_WORKDIR"),
):
if _host_path and _host_path not in sys.path:
sys.path.append(_host_path)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛡️ Codex Security Review

P2 Badge Security: Keep chat paths out of approved host Python

Condition: in an owner chat, after the user approves a host-reaching Terminal call that launches a Python CLI. These lines append model-writable .unsloth-packages and the chat directory to every descendant interpreter. Appending last prevents simple shadowing, but not plugin enumeration or imports of missing names: a planted pytest11 entry point was auto-loaded by the trusted system pytest binary and read an unrelated host file, while the parent-equivalent environment did not. Because this approved path has no OS isolation, implicit code gets broader host access than the command the user reviewed. Keep writable paths out of host launches; instead, confine the process to only approved host resources.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this one as is. After the later commits the chat folder only supplies helper modules the approved script imports by name, and chat CLIs only resolve when the call names them. What remains is the packages folder for Python an approved call starts, appended after everything else, with no .pth processing. That folder is what the user installed in the chat for exactly these calls (for example an approved python analyze.py ~/data.xlsx whose script imports a chat-installed openpyxl), so scoping it to names in the command text would break that flow again. The remaining case needs a host tool that scans for plugins plus a planted entry point in an approved owner call.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 868a2dade4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if path is not None or name in self._skip:
return None
import importlib.machinery
return importlib.machinery.PathFinder.find_spec(name, [self._workdir])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict the finder to explicitly requested helpers

When an approved script imports a trusted library that probes an absent optional top-level dependency, this process-wide fallback supplies a same-named module planted in the chat directory by an earlier sandboxed call. The planted module then executes with the approved process's host access even though the approved script never imported that helper directly; placing the finder last only prevents shadowing dependencies that already exist. Limit this fallback to helper names explicitly imported by the approved script, rather than resolving every otherwise-missing top-level import.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 32a220f. The approved Python tool call now passes only the top-level module names its script imports (parsed with ast), and the finder resolves only those names from the chat folder. A library probing an optional import never reaches the folder. Checked by hand: a planted optional_dep.py loaded before this change and does not now, while an imported helper still loads. Terminal calls no longer get the finder at all; their python -c already has the chat folder as cwd, as before.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 32a220f2b8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

except (SyntaxError, ValueError):
return []
names = set()
for node in ast.walk(tree):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Scope helper authorization to imports executed by the script

The new ast.walk allowlist is fresh evidence that optional-import injection remains possible: when an approved script merely mentions import optional_dep inside an uncalled function or a false platform/TYPE_CHECKING branch, the name is still enabled process-wide. If a trusted library later probes that absent dependency, the finder executes a planted optional_dep.py from the chat workdir with the approved process's host access even though the script never executed that import. Scope workdir resolution to import requests actually initiated by the approved script rather than every syntactically mentioned name.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is. It needs the approved script to name the module itself, in a branch that never runs, and a library to then probe for that same missing name. The user reviewed a script that names the module, and a library probing for an unnamed module is already blocked by the allowlist.

Comment thread studio/backend/core/inference/tools.py Outdated
env["PYTHONNOUSERSITE"] = "1"
# Chat-installed CLIs resolve too, but only after every system executable.
scripts = os.path.join(packages, "Scripts" if os.name == "nt" else "bin")
env["PATH"] = os.pathsep.join(part for part in (env.get("PATH", ""), scripts) if part)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict chat CLI lookup to commands the approved call requests

In both approved Python and Terminal launches, appending the sandbox-writable scripts directory to PATH also exposes it to every trusted descendant process. If a trusted library or system executable probes an optional command that is absent from the system path—for example, a conversion library spawning ffmpeg—a binary planted earlier in .unsloth-packages/bin is selected and runs with host access even though the approved script or shell command never requested that chat CLI; placing the directory last prevents shadowing but not this missing-command injection. Limit this fallback to CLI names explicitly requested by the approved call rather than adding the whole directory process-wide.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 16de984. The chat bin folder is no longer added to PATH. Only the chat-installed CLIs whose names appear as words in the approved command or script are copied into the call's private directory, and that directory goes last on PATH. A tool probing for a command the call never names (the test builds the name at run time and uses command -v) misses the chat folder. The CLI the user ran still works.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 16de984971

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +311 to +313
_host_packages = os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES")
if _host_packages and _host_packages not in sys.path:
sys.path.append(_host_packages)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict approved imports from the session package directory

Appending the entire sandbox-writable .unsloth-packages directory makes every otherwise-missing module importable during an approved host call. If a trusted dependency probes an absent optional module, an earlier sandboxed call can plant that module in this directory and have it execute with host access even though the approved script never named it; placing the directory last prevents shadowing existing modules but not missing-module injection. Restrict session-package resolution to packages actually authorized by the approved script.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is: .unsloth-packages holds what pip installed in the chat for exactly these approved calls, and a module there cannot be told apart from a package the user installed; the Python tool already appended this folder on the merge base. Restricting it to names in the script would break scripts whose installed packages import their own dependencies.

Comment thread studio/backend/core/inference/tools.py Outdated
Comment on lines +10202 to +10207
words = set(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 (entry in words or stem in words) and os.path.isfile(source):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Parse executable positions before authorizing chat CLIs

Fresh evidence in this revision is that CLI authorization is derived from every word in the complete command or Python source, including comments, string literals, option values, and file names. If an approved script merely mentions ffmpeg in a comment or data value and a trusted dependency subsequently probes for ffmpeg, a planted chat executable is copied into the private PATH and runs with host access despite never being requested as a command. Identify actual executable invocations rather than treating arbitrary words as authorization.

Useful? React with 👍 / 👎.

Comment on lines +333 to +334
if path is not None or name not in self._names:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Support sibling imports from approved chat helpers

When an approved script imports a chat-local helper.py that in turn uses an absolute import of another chat-local module such as import constants, the dependency is absent from the main script's allowlist, so this finder rejects it and the helper fails with ModuleNotFoundError. This breaks common multi-file helpers that worked when the chat directory was on sys.path; resolve or recursively authorize local dependencies reached while loading an explicitly approved helper.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 901db10: when the finder serves a requested chat helper, that helper's own absolute imports are allowed too, so helper.py importing config.py works (test covers it).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 901db10889

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# 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)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Pass the original terminal command to CLI selection

For a non-owner account using UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS on a host without account confinement, _shell_argv stores the command in .studio_cmd_*.sh, leaving plan.argv with only the shell and generated filename. Scanning the joined argv here therefore never sees a chat CLI named by the approved command, so that CLI is not copied into the private PATH and the call fails with command-not-found. Pass the original terminal command to the selector instead.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is: it needs a non-owner account on a host without account confinement plus the UNSLOTH_STUDIO_ALLOW_UNCONFINED_TOOLS opt-in. Owners and confined accounts keep the command in argv, so named chat CLIs resolve there.

Comment thread studio/backend/core/inference/tools.py Outdated
for entry in entries:
stem = os.path.splitext(entry)[0] if os.name == "nt" else entry
source = os.path.join(scripts, entry)
if (entry in words or stem in words) and os.path.isfile(source):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match chat CLI names case-insensitively on Windows

On Windows, executable lookup is case-insensitive, but this membership check compares the command words and directory entries case-sensitively. If the chat package contains ruff.exe and the approved command invokes RUFF (or otherwise varies casing), the executable is not copied, while the original Scripts directory is intentionally absent from PATH, so the approved call fails with command-not-found. Normalize both the candidate names and command words for Windows before comparing them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 402f3d0: on Windows the command words and the Scripts entries are compared case-folded, with a test.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 402f3d0e6f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit d0c4c9f into main Oct 23, 2026
2 of 35 checks passed
@danielhanchen
danielhanchen deleted the studio-host-terminal-session-packages branch October 23, 2026 03:41
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 27, 2026
…ved host calls (unslothai#14948)

Follows up unslothai#14543.

### What was wrong

Approved host launches (the Python tool and Terminal) set
`_UNSLOTH_HOST_SESSION_PACKAGES`, and the sandbox `sitecustomize.py`
appended the whole chat `.unsloth-packages` folder to `sys.path`.
Appending it last stopped it from overriding the standard library or
installed packages, but its `*.dist-info` became visible to
`importlib.metadata`. Tools that load plugins from entry points then
imported code from that folder that the approved command never asked
for: an approved `python -m pytest -q test_ok.py` loaded a `pytest11`
plugin the chat had installed, and in the repro that plugin read a file
outside the chat folder.

### Fix

The folder is no longer put on `sys.path`. `sitecustomize.py` appends a
last-resort meta path finder, `_HostPackagesFinder`, that:
- serves top-level modules from the folder only after every other finder
has missed, so it never overrides anything the host has, and skips
`sitecustomize` / `usercustomize`;
- leaves submodules to the package's own `__path__`;
- answers `importlib.metadata` only for an exact distribution name with
no explicit `path` (so `version("pkg")` still works; a lookup scoped to
explicit paths is left to the stock path finder) and returns nothing for
name-less scans such as `distributions()` and `entry_points()`, which
plugin discovery relies on.

Explicit imports of chat-installed packages from an approved script or
from Terminal-started Python keep working as they did after unslothai#14543.
Visible change: tools that list installed packages by scanning (`pip
list` style, `pkgutil.iter_modules`) no longer see chat-installed
packages during an approved call, and `pkg_resources.get_distribution()`
no longer finds them (pkg_resources reads only `sys.path`;
`importlib.metadata.version()` still works). A Python started with `-S`
skips `sitecustomize` and could not import chat-installed packages
before this change either; that is unchanged. Submodules a chat installs
into a namespace package the host already provides resolve from the
chat's portion after the host's. Once one is served, that portion
directory is appended to the namespace's `__path__` (PEP 420, and
pkgutil-style or pkg_resources-style packages whose `__init__.py`
declares `__path__ = extend_path(__path__, __name__)` or
`declare_namespace(__name__)` at module level), so `importlib.resources`
and `pkgutil.iter_modules` on the namespace see it. Limit: a PEP 420
`__path__` is recomputed from `sys.path` whenever `sys.path` changes,
which drops the appended portion until the next submodule is served from
it.

### Tests

- New
`test_an_approved_pytest_call_does_not_autoload_chat_installed_plugins`
plants a `pytest11` entry point in the session package folder and runs
an approved Terminal pytest; it fails on main and passes here.
- New `test_an_approved_script_still_imports_chat_installed_packages`
checks that a package, its submodule and `importlib.metadata.version`
still resolve in an approved script, and that the entry point scan stays
empty.
- `test_tool_sandbox_hardening.py`, `test_tool_sandbox_wiring.py`,
`test_sandbox_sitecustomize.py`, `test_sandbox_tools.py`,
`test_sandbox_files_and_storage_roots.py`,
`test_full_access_tool_prompt.py`: 1478 passed, 2 skipped (and 1130
passed, 2 skipped for the four sandbox files after the namespace and
metadata-path fixes).
- Checked on Python 3.10, 3.11, 3.12 and 3.13: the folder no longer
shows up in `distributions()` or the `pytest11` entry points, and
explicit imports still work.

Not run: a full Studio approval flow against a live server, the macOS
and Windows sandbox wrappers (the new tests are POSIX only and ran on
Linux).

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant