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: load the user's own Pi extensions and packages in unsloth start pi (#10971)

oobabooga8fb25b75cbec
diff --git a/unsloth_cli/commands/start.py b/unsloth_cli/commands/start.py
index 30e32275827..041c7acc2f9 100644
--- a/unsloth_cli/commands/start.py
+++ b/unsloth_cli/commands/start.py
@@ -123,6 +123,10 @@ _CODEX_SUBAGENT_ROUTING_INSTRUCTIONS = (
"subagents for other delegation requests."
)
_PI_SUBAGENT_EXTENSION = Path(__file__).parent.parent / "pi_subagent.ts"
+_PI_USER_RESOURCE_DIRS = ("extensions", "skills", "prompts", "themes", "npm", "git")
+_PI_USER_RESOURCE_SETTINGS = ("packages", "extensions", "skills", "prompts", "themes")
+_PI_USER_VERBATIM_SETTINGS = ("npmCommand",)
+_PI_USER_RESOURCES_MANIFEST = ".unsloth-user-resources.json"
# OpenCode selects a model by "<providerID>/<modelID>". Use a dedicated id to avoid colliding with a user's providers; provider filters are set in the launch-time overlay.
_OPENCODE_PROVIDER = "unsloth-studio"
_PROVIDER_HEADER = f"[model_providers.{_CODEX_PROFILE}]"
@@ -2980,9 +2984,31 @@ def _codex_source_home(*, ignore_configured: bool = False) -> Path:
return Path.home() / ".codex"
+def _is_junction(path: Path) -> bool:
+ # Path.is_junction() was added in Python 3.12.
+ if hasattr(path, "is_junction"):
+ return path.is_junction()
+ try:
+ return (
+ getattr(os.lstat(path), "st_reparse_tag", None) == 0xA0000003
+ ) # IO_REPARSE_TAG_MOUNT_POINT
+ except OSError:
+ return False
+
+
+def _is_directory_link(path: Path) -> bool:
+ # lstat reads the link, so FILE_ATTRIBUTE_DIRECTORY answers even when dangling.
+ try:
+ return bool(getattr(os.lstat(path), "st_file_attributes", 0) & 0x10)
+ except OSError:
+ return False
+
+
def _remove_overlay_entry(path: Path) -> None:
- is_junction = getattr(path, "is_junction", None)
- if is_junction and is_junction():
+ if _is_junction(path):
+ path.rmdir()
+ elif os.name == "nt" and path.is_symlink() and _is_directory_link(path):
+ # DeleteFileW, which unlink maps to, refuses a directory entry; rmdir drops the link.
path.rmdir()
elif path.is_symlink() or path.is_file():
path.unlink()
@@ -4605,6 +4631,258 @@ def write_pi_config(base: str, key: str, model: dict, path: Path) -> None:
typer.echo(f"Updated {path}")
+def _link_user_dir(source: Path, target: Path) -> bool:
+ """Expose source at target. True once target resolves to source."""
+ # Refresh links, but preserve real session directories.
+ if target.is_symlink() or _is_junction(target):
+ _remove_overlay_entry(target)
+ if target.exists() or not source.is_dir():
+ return False
+ target.parent.mkdir(parents = True, exist_ok = True, mode = 0o700)
+ try:
+ target.symlink_to(source, target_is_directory = True)
+ except OSError:
+ if not _create_directory_junction(source, target):
+ typer.echo(f"Warning: couldn't link {source} into the Pi session.", err = True)
+ return False
+ return True
+
+
+def _pi_local_entry(
+ entry: str,
+ source: Path,
+ home: Path,
+ linked: frozenset,
+ agents_skills = None,
+) -> str:
+ """Re-anchor a user path from the original Pi agent directory."""
+ value = entry.strip()
+ if not value or value == "." or value.startswith("file:"):
+ # Nothing to anchor: "" and "." would name the whole agent directory.
+ return entry
+ if value == "~" or value.startswith(("~/", "~" + os.sep)):
+ target = os.path.join(home, value[2:])
+ else:
+ # Pi stores local packages relative to its agent directory.
+ target = os.path.join(source, value)
+ target = os.path.normpath(target)
+ if agents_skills is not None:
+ # Pi reads ~/.agents/skills through HOME, which moved, so a rule naming the
+ # user's copy must follow it or it stops matching.
+ user_root, session_root = agents_skills
+ try:
+ inside = os.path.relpath(target, user_root)
+ except ValueError: # on another Windows drive
+ inside = os.pardir
+ if inside == os.curdir:
+ return session_root
+ if inside != os.pardir and not inside.startswith(os.pardir + os.sep):
+ return os.path.join(session_root, inside)
+ try:
+ relative = os.path.relpath(target, source)
+ except ValueError: # on another Windows drive
+ return target
+ # Session-relative only where the link landed: a real session directory blocks
+ # the link, and the entry would then point into it instead of at the user's.
+ if relative.split(os.sep)[0] in linked:
+ return relative
+ return target
+
+
+def _pi_settings_entries(
+ key: str,
+ entries,
+ source: Path,
+ home: Path,
+ linked: frozenset,
+ agents_skills = None,
+) -> list:
+ if not isinstance(entries, list):
+ return []
+ result = []
+ for entry in entries:
+ if key == "packages":
+ spec = entry.get("source") if isinstance(entry, dict) else entry
+ # All other package sources are local paths.
+ if isinstance(spec, str) and not spec.strip().startswith(
+ ("npm:", "git:", "github:", "http:", "https:", "ssh:")
+ ):
+ spec = _pi_local_entry(spec, source, home, linked, agents_skills)
+ entry = {**entry, "source": spec} if isinstance(entry, dict) else spec
+ elif isinstance(entry, str):
+ prefix = entry[:1] if entry.startswith(("!", "+", "-")) else ""
+ pattern = entry[len(prefix) :]
+ if not prefix and "*" not in entry and "?" not in entry:
+ entry = _pi_local_entry(entry, source, home, linked, agents_skills)
+ elif not pattern.strip().startswith("~"): # Pi does not expand ~ in patterns
+ # Pi matches patterns against paths relative to the agent directory, which moved.
+ # Keep the original too: it still matches basenames and linked directories.
+ anchored = prefix + _pi_local_entry(
+ pattern,
+ source,
+ home,
+ linked,
+ agents_skills,
+ )
+ if anchored != entry:
+ result.append(entry)
+ entry = anchored
+ result.append(entry)
+ return result
+
+
+def _clear_pi_user_resources(agent_dir: Path, home: Path) -> None:
+ """Undo what an earlier launch linked and copied, leaving session state alone."""
+ targets = [agent_dir / name for name in _PI_USER_RESOURCE_DIRS]
+ targets.append(home / ".agents" / "skills")
+ for target in targets:
+ if target.is_symlink() or _is_junction(target):
+ _remove_overlay_entry(target)
+ manifest_path = agent_dir / _PI_USER_RESOURCES_MANIFEST
+ previous = _read_json_object(manifest_path)
+ if not previous:
+ return
+ settings_path = agent_dir / "settings.json"
+ settings = _read_json_object(settings_path)
+ if settings is None:
+ return
+ before = json.dumps(settings, sort_keys = True)
+ for key, copied in previous.items():
+ own = settings.get(key)
+ if key in _PI_USER_VERBATIM_SETTINGS:
+ # An argument vector, not entries: subtracting drops whatever the two share.
+ if own == copied:
+ settings.pop(key, None)
+ elif isinstance(copied, list) and isinstance(own, list):
+ rest = [item for item in own if item not in copied]
+ if rest:
+ settings[key] = rest
+ else:
+ settings.pop(key, None)
+ elif own == copied:
+ settings.pop(key, None)
+ if json.dumps(settings, sort_keys = True) != before:
+ _write_private_json(settings_path, settings)
+ manifest_path.unlink(missing_ok = True)
+
+
+def write_pi_user_resources(agent_dir: Path, home: Path) -> None:
+ """Expose selected user Pi resources inside an isolated session."""
+ if _wsl_windows_executable(["pi"]):
+ # Windows Pi cannot reliably follow WSL links into mounted drives, and a session
+ # an earlier Linux pi prepared still holds them, so drop those before returning.
+ _clear_pi_user_resources(agent_dir, home)
+ return
+ user_home = Path.home()
+ configured = os.environ.get("PI_CODING_AGENT_DIR")
+ configured = configured.strip() if configured else ""
+ # Pi resolves a relative override from the launch directory.
+ source = (
+ Path(os.path.abspath(os.path.expanduser(configured)))
+ if configured
+ else user_home / ".pi" / "agent"
+ )
+ if source.resolve(strict = False) == agent_dir.resolve(strict = False):
+ # Do not treat this session as its own resource source.
+ source = user_home / ".pi" / "agent"
+ if configured and not source.is_dir():
+ # Otherwise this looks exactly like the bug this function exists to fix.
+ typer.echo(
+ f"Warning: PI_CODING_AGENT_DIR points at {source}, which is not a directory; "
+ "no Pi extensions or packages will load in this session.",
+ err = True,
+ )
+ linked = frozenset(
+ name for name in _PI_USER_RESOURCE_DIRS if _link_user_dir(source / name, agent_dir / name)
+ )
+ # HOME is relocated, so link Pi's other global skill directory too.
+ user_skills = user_home / ".agents" / "skills"
+ session_skills = home / ".agents" / "skills"
+ agents_skills = (
+ (str(user_skills), str(session_skills))
+ if _link_user_dir(user_skills, session_skills)
+ else None
+ )
+
+ user_settings_path = source / "settings.json"
+ user_settings = _read_json_object(user_settings_path)
+ if user_settings is None:
+ typer.echo(
+ f"Warning: couldn't parse {user_settings_path}; "
+ "Pi packages listed there won't load in this session.",
+ err = True,
+ )
+ user_settings = {}
+ settings_path = agent_dir / "settings.json"
+ settings = _read_json_object(settings_path)
+ if settings is None:
+ typer.echo(
+ f"Warning: couldn't parse {settings_path}; your Pi packages won't load in this session.",
+ err = True,
+ )
+ return
+ manifest_path = agent_dir / _PI_USER_RESOURCES_MANIFEST
+ previous = _read_json_object(manifest_path)
+ if previous is None:
+ # Provenance is lost, so entries the user has since removed cannot be reconciled.
+ typer.echo(
+ f"Warning: couldn't parse {manifest_path}; Pi resources copied by an earlier "
+ "launch stay in this session even if you removed them since.",
+ err = True,
+ )
+ previous = {}
+ before = json.dumps(settings, sort_keys = True)
+ copied = {}
+ for key in _PI_USER_RESOURCE_SETTINGS:
+ entries = _pi_settings_entries(
+ key,
+ user_settings.get(key),
+ source,
+ user_home,
+ linked,
+ agents_skills,
+ )
+ # Refresh copied entries while preserving settings added inside the session.
+ stale = previous.get(key) if isinstance(previous.get(key), list) else []
+ own = settings.get(key)
+ if own is not None and not isinstance(own, list):
+ # Pi types these as arrays; leave a shape we do not understand alone.
+ typer.echo(
+ f"Warning: {settings_path} has a non-list {key!r}; "
+ "leaving it as is, so your Pi entries for it won't load in this session.",
+ err = True,
+ )
+ continue
+ own = [item for item in own or [] if item not in stale and item not in entries]
+ if entries or own:
+ # Pi de-dupes packages by identity keeping the FIRST, so session entries
+ # lead. Patterns apply in order instead, so those stay user-first.
+ settings[key] = own + entries if key == "packages" else entries + own
+ else:
+ settings.pop(key, None)
+ if entries:
+ copied[key] = entries
+ for key in _PI_USER_VERBATIM_SETTINGS:
+ # Pi runs every package lookup and install through npmCommand, so inheriting
+ # the package list without it falls back to an npm that cannot find them.
+ value = user_settings.get(key)
+ own = settings.get(key)
+ if own is not None and own != previous.get(key):
+ continue # changed inside the session, so the session owns it now
+ if isinstance(value, list) and value and all(isinstance(arg, str) for arg in value):
+ settings[key] = value
+ copied[key] = value
+ else:
+ settings.pop(key, None)
+ if json.dumps(settings, sort_keys = True) != before:
+ _write_private_json(settings_path, settings)
+ if copied != previous:
+ if copied:
+ _write_private_json(manifest_path, copied)
+ else:
+ manifest_path.unlink(missing_ok = True)
+
+
def write_pi_subagent_config(
base: str,
key: str,
@@ -5335,6 +5613,7 @@ def pi(
# 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")
+ 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"):
# Node resolves ~/.pi via USERPROFILE (then HOMEDRIVE + HOMEPATH) on Windows, not HOME. Set them whenever Pi may run as a Windows process: native Windows, or a /mnt Windows shim launched from WSL, where the WSLENV bridge then translates the path. Otherwise the Windows process falls back to the user's real %USERPROFILE%\\.pi. splitdrive yields no drive off a POSIX path, so HOMEDRIVE/HOMEPATH stay unset there.
diff --git a/unsloth_cli/tests/test_start.py b/unsloth_cli/tests/test_start.py
index 4f876bd9b94..f36b2f1b5bb 100644
--- a/unsloth_cli/tests/test_start.py
+++ b/unsloth_cli/tests/test_start.py
@@ -12,6 +12,7 @@ import json
import os
import re
import shlex
+import shutil
import signal
import sys
import threading
@@ -5546,7 +5547,21 @@ def test_write_pi_config_preserves_and_idempotent(tmp_path):
assert path.read_text() == before
-def test_connect_pi_no_launch(fake_studio, tmp_path):
+def _pi_user_agent_dir(tmp_path, monkeypatch) -> Path:
+ user_home = tmp_path / "user-home"
+ agent_dir = user_home / ".pi" / "agent"
+ agent_dir.mkdir(parents = True)
+ monkeypatch.setenv("HOME", str(user_home))
+ monkeypatch.setenv("USERPROFILE", str(user_home))
+ monkeypatch.delenv("PI_CODING_AGENT_DIR", raising = False)
+ return agent_dir
+
+
+def test_connect_pi_no_launch(fake_studio, tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "extensions").mkdir()
+ (user_agent_dir / "extensions" / "mine.ts").write_text("export default () => {};\n")
+ (user_agent_dir / "settings.json").write_text(json.dumps({"packages": ["npm:pi-mine"]}))
result = CliRunner().invoke(start.start_app, ["pi", "--no-launch"])
assert result.exit_code == 0, result.output
# Pi resolves its config dir from PI_CODING_AGENT_DIR first, so pin it at the session
@@ -5563,6 +5578,424 @@ def test_connect_pi_no_launch(fake_studio, tmp_path):
{"id": MODEL["id"], "contextWindow": MODEL["context_length"], "maxTokens": 8192}
]
assert not any(c[1].endswith("/api/inference/status") for c in fake_studio)
+ assert (home / ".pi" / "agent" / "extensions" / "mine.ts").is_file()
+ settings = json.loads((home / ".pi" / "agent" / "settings.json").read_text())
+ assert settings == {"packages": ["npm:pi-mine"]}
+ assert not (user_agent_dir / "models.json").exists()
+
+
[email protected](os.name == "nt", reason = "asserts POSIX symlinks and path forms")
+def test_write_pi_user_resources_links_resources_and_keeps_config_private(tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ user_home = user_agent_dir.parent.parent
+ for name in ("extensions", "skills", "npm", "git"):
+ (user_agent_dir / name).mkdir()
+ (user_home / ".agents" / "skills").mkdir(parents = True)
+ (user_agent_dir / "auth.json").write_text('{"google": "user-key"}\n')
+ (user_agent_dir / "models.json").write_text('{"providers": {"mine": {}}}\n')
+ (user_agent_dir / "sessions").mkdir()
+ (user_agent_dir / "settings.json").write_text(
+ json.dumps(
+ {
+ "defaultProvider": "google",
+ "theme": "light",
+ "packages": [
+ "git:github.com/me/pi-tools",
+ "../../src/local-extension",
+ {"source": "~/other-extension", "extensions": ["index.ts"]},
+ ],
+ "extensions": [
+ "extensions/extra.ts",
+ "-extensions/off.ts",
+ "root.ts",
+ "/abs/ext.ts",
+ "!local/old.ts",
+ "-~/literal.ts",
+ ],
+ "skills": ["skills/*", "../shared/*"],
+ }
+ )
+ )
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ start.write_pi_config(BASE, "sk-unsloth-abc", MODEL, agent_dir / "models.json")
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ for name in ("extensions", "skills", "npm", "git"):
+ assert (agent_dir / name).is_symlink()
+ assert (agent_dir / name).resolve() == (user_agent_dir / name).resolve()
+ assert not (agent_dir / "prompts").exists()
+ assert (session_home / ".agents" / "skills").resolve() == (
+ user_home / ".agents" / "skills"
+ ).resolve()
+ for private in ("auth.json", "sessions"):
+ assert not (agent_dir / private).exists()
+ assert "mine" not in json.loads((agent_dir / "models.json").read_text())["providers"]
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ assert settings == {
+ "packages": [
+ "git:github.com/me/pi-tools",
+ str(user_home / "src" / "local-extension"),
+ {"source": str(user_home / "other-extension"), "extensions": ["index.ts"]},
+ ],
+ "extensions": [
+ "extensions/extra.ts",
+ "-extensions/off.ts",
+ str(user_agent_dir / "root.ts"),
+ "/abs/ext.ts",
+ # Pi matches patterns relative to the agent directory, so add a user-anchored copy.
+ "!local/old.ts",
+ f"!{user_agent_dir / 'local' / 'old.ts'}",
+ "-~/literal.ts",
+ ],
+ "skills": ["skills/*", "../shared/*", str(user_home / ".pi" / "shared" / "*")],
+ }
+
+
+def test_write_pi_user_resources_refreshes_a_persisted_session(tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "extensions").mkdir()
+ user_settings = user_agent_dir / "settings.json"
+ user_settings.write_text(json.dumps({"packages": ["npm:old", "npm:kept"]}))
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+
+ start.write_pi_user_resources(agent_dir, session_home)
+ # Add session-only state, then change the user config.
+ settings_path = agent_dir / "settings.json"
+ settings = json.loads(settings_path.read_text())
+ settings["packages"].append("npm:session-only")
+ settings["theme"] = "dark"
+ settings_path.write_text(json.dumps(settings))
+ user_settings.write_text(json.dumps({"packages": ["npm:kept", "npm:new"]}))
+ (user_agent_dir / "extensions").rmdir()
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ # Pi keeps the first entry per package identity, so session-owned packages lead.
+ assert json.loads(settings_path.read_text()) == {
+ "packages": ["npm:session-only", "npm:kept", "npm:new"],
+ "theme": "dark",
+ }
+ assert not (agent_dir / "extensions").exists() and not (agent_dir / "extensions").is_symlink()
+
+ user_settings.unlink()
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert json.loads(settings_path.read_text()) == {
+ "packages": ["npm:session-only"],
+ "theme": "dark",
+ }
+ assert not (agent_dir / start._PI_USER_RESOURCES_MANIFEST).exists()
+
+
+def test_write_pi_user_resources_leaves_session_dirs_and_user_files_alone(tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "npm" / "node_modules" / "pi-mine").mkdir(parents = True)
+ (user_agent_dir / "extensions").mkdir()
+ (user_agent_dir / "extensions" / "mine.ts").write_text("mine\n")
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ (agent_dir / "npm").mkdir(parents = True)
+ (agent_dir / "npm" / "session.txt").write_text("session\n")
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert not (agent_dir / "npm").is_symlink()
+ assert (agent_dir / "npm" / "session.txt").read_text() == "session\n"
+ assert (agent_dir / "extensions" / "mine.ts").read_text() == "mine\n"
+ # Deleting the session must not delete linked user files.
+ shutil.rmtree(session_home)
+ assert (user_agent_dir / "extensions" / "mine.ts").read_text() == "mine\n"
+ assert (user_agent_dir / "npm" / "node_modules" / "pi-mine").is_dir()
+
+
+def test_write_pi_user_resources_uses_inherited_agent_dir(tmp_path, monkeypatch):
+ _pi_user_agent_dir(tmp_path, monkeypatch)
+ configured = tmp_path / "custom-pi"
+ (configured / "extensions").mkdir(parents = True)
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ monkeypatch.setenv("PI_CODING_AGENT_DIR", str(configured))
+
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert (agent_dir / "extensions").resolve() == (configured / "extensions").resolve()
+
+ # Do not reuse the session as its own source.
+ monkeypatch.setenv("PI_CODING_AGENT_DIR", str(agent_dir))
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert not (agent_dir / "extensions").exists()
+
+
+def test_write_pi_user_resources_resolves_a_relative_agent_dir_from_the_launch_dir(
+ tmp_path, monkeypatch
+):
+ _pi_user_agent_dir(tmp_path, monkeypatch)
+ configured = tmp_path / "launch" / "custom-pi"
+ (configured / "extensions").mkdir(parents = True)
+ (configured / "settings.json").write_text(json.dumps({"packages": ["../src/local-ext"]}))
+ monkeypatch.chdir(tmp_path / "launch")
+ monkeypatch.setenv("PI_CODING_AGENT_DIR", "custom-pi")
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert (agent_dir / "extensions").resolve() == (configured / "extensions").resolve()
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ assert settings == {"packages": [str(tmp_path / "launch" / "src" / "local-ext")]}
+
+
+def test_is_junction_reads_the_reparse_tag_before_python_3_12(tmp_path, monkeypatch):
+ # Python 3.13 also defines is_junction on a pathlib base class.
+ for cls in type(tmp_path).__mro__:
+ if "is_junction" in vars(cls):
+ monkeypatch.delattr(cls, "is_junction")
+ tags = {"junction": 0xA0000003, "symlink": 0xA000000C}
+
+ def lstat(path):
+ name = Path(path).name
+ if name not in tags:
+ raise FileNotFoundError(path)
+ return SimpleNamespace(st_reparse_tag = tags[name])
+
+ monkeypatch.setattr(start.os, "lstat", lstat)
+ assert start._is_junction(tmp_path / "junction")
+ assert not start._is_junction(tmp_path / "symlink")
+ assert not start._is_junction(tmp_path / "missing")
+
+
+def test_link_user_dir_replaces_a_junction_from_an_earlier_run(tmp_path, monkeypatch):
+ target = tmp_path / "session" / "extensions"
+ target.mkdir(parents = True) # stands in for a junction to a previous source
+ source = tmp_path / "user" / "extensions"
+ source.mkdir(parents = True)
+ monkeypatch.setattr(start, "_is_junction", lambda path: path == target and path.is_dir())
+
+ start._link_user_dir(source, target)
+
+ assert target.is_symlink()
+ assert target.resolve() == source.resolve()
+
+
+def test_write_pi_user_resources_skips_a_windows_pi_under_wsl(tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "extensions").mkdir()
+ (user_agent_dir / "settings.json").write_text(json.dumps({"packages": ["npm:pi-mine"]}))
+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda _: "/mnt/c/npm/pi")
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert not agent_dir.exists()
+
+
[email protected](os.name == "nt", reason = "asserts POSIX symlinks and path forms")
+def test_write_pi_user_resources_clears_a_session_a_linux_pi_prepared(tmp_path, monkeypatch):
+ # Switching a persisted session from a Linux pi to a Windows one must not hand
+ # Windows Pi the WSL-backed links the skip exists to withhold.
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "extensions").mkdir()
+ (user_agent_dir / "settings.json").write_text(
+ json.dumps({"packages": ["npm:user-pkg"], "extensions": ["extensions/mine.ts"]})
+ )
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda _: None)
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert (agent_dir / "extensions").is_symlink()
+ # Something the session set for itself, which must survive.
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ settings["packages"].append("npm:session-only")
+ (agent_dir / "settings.json").write_text(json.dumps(settings))
+
+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda _: "/mnt/c/npm/pi.cmd")
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert not (agent_dir / "extensions").exists()
+ assert json.loads((agent_dir / "settings.json").read_text()) == {
+ "packages": ["npm:session-only"],
+ }
+ assert not (agent_dir / start._PI_USER_RESOURCES_MANIFEST).exists()
+ # The user's own directory is untouched either way.
+ assert (user_agent_dir / "extensions").is_dir()
+
+
[email protected]("session_command", [None, ["npm", "--silent"]])
+def test_write_pi_user_resources_clears_npm_command_whole(tmp_path, monkeypatch, session_command):
+ # npmCommand is an argument vector: subtracting it entry by entry would leave a
+ # command missing whatever the copied and session values happen to share.
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "settings.json").write_text(
+ json.dumps({"npmCommand": ["npm", "--registry=x"]})
+ )
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda _: None)
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert json.loads((agent_dir / "settings.json").read_text())["npmCommand"] == [
+ "npm",
+ "--registry=x",
+ ]
+ if session_command is not None:
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ settings["npmCommand"] = session_command
+ (agent_dir / "settings.json").write_text(json.dumps(settings))
+
+ monkeypatch.setattr(start, "_wsl_windows_executable", lambda _: "/mnt/c/npm/pi.cmd")
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ # The copied command goes; one the session chose survives intact.
+ assert settings.get("npmCommand") == session_command
+
+
[email protected](os.name == "nt", reason = "asserts POSIX symlinks and path forms")
+def test_write_pi_user_resources_reanchors_when_a_real_session_dir_blocks_the_link(
+ tmp_path, monkeypatch
+):
+ # Pi creates <agent dir>/npm the first time a package is installed, so a
+ # persisted session can already own that directory. The link is then skipped
+ # and a session-relative entry would point into it instead of at the user's.
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "npm").mkdir()
+ (user_agent_dir / "extensions").mkdir()
+ (user_agent_dir / "settings.json").write_text(
+ json.dumps({"packages": ["npm/pkg"], "extensions": ["extensions/mine.ts"]})
+ )
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ (agent_dir / "npm").mkdir(parents = True)
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ assert not (agent_dir / "npm").is_symlink() # the session's own directory survives
+ assert settings["packages"] == [str(user_agent_dir / "npm" / "pkg")]
+ # extensions was linked, so entries under it stay relative and resolve through it.
+ assert settings["extensions"] == ["extensions/mine.ts"]
+
+
[email protected](os.name == "nt", reason = "asserts POSIX symlinks and path forms")
+def test_write_pi_user_resources_keeps_a_disabled_global_skill_disabled(tmp_path, monkeypatch):
+ # ~/.agents/skills is reached through HOME, which moved, so a rule naming the
+ # user's copy has to follow it or Pi re-enables the skill inside the session.
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ user_home = user_agent_dir.parent.parent
+ disabled = user_home / ".agents" / "skills" / "off" / "SKILL.md"
+ disabled.parent.mkdir(parents = True)
+ disabled.write_text("disabled\n")
+ (user_agent_dir / "settings.json").write_text(json.dumps({"skills": [f"-{disabled}"]}))
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ session_skill = session_home / ".agents" / "skills" / "off" / "SKILL.md"
+ assert session_skill.exists()
+ settings = json.loads((agent_dir / "settings.json").read_text())
+ # The original rule is kept and an alias for the session path is added beside it.
+ assert settings["skills"] == [f"-{disabled}", f"-{session_skill}"]
+
+
+def test_write_pi_user_resources_copies_the_npm_command(tmp_path, monkeypatch):
+ # Pi runs every package lookup and install through npmCommand, so a session
+ # that inherits the package list without it falls back to plain npm.
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ command = ["mise", "exec", "node@20", "--", "npm"]
+ (user_agent_dir / "settings.json").write_text(
+ json.dumps({"packages": ["npm:pi-mine"], "npmCommand": command})
+ )
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert json.loads((agent_dir / "settings.json").read_text())["npmCommand"] == command
+ # A command set inside the session is not overwritten on the next launch.
+ settings_path = agent_dir / "settings.json"
+ settings = json.loads(settings_path.read_text())
+ settings["npmCommand"] = ["pnpm"]
+ settings_path.write_text(json.dumps(settings))
+ start.write_pi_user_resources(agent_dir, session_home)
+ assert json.loads(settings_path.read_text())["npmCommand"] == ["pnpm"]
+
+
+def test_write_pi_user_resources_warns_on_an_unusable_agent_dir_override(
+ tmp_path, monkeypatch, capsys
+):
+ # Otherwise this looks exactly like the bug write_pi_user_resources exists to fix.
+ _pi_user_agent_dir(tmp_path, monkeypatch)
+ missing = tmp_path / "not-a-directory"
+ monkeypatch.setenv("PI_CODING_AGENT_DIR", f" {missing} ")
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ agent_dir.mkdir(parents = True)
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ assert "PI_CODING_AGENT_DIR" in capsys.readouterr().err
+
+
+def test_write_pi_user_resources_keeps_a_non_list_setting(tmp_path, monkeypatch):
+ user_agent_dir = _pi_user_agent_dir(tmp_path, monkeypatch)
+ (user_agent_dir / "settings.json").write_text(json.dumps({"themes": ["npm:user-theme"]}))
+ session_home = tmp_path / "session"
+ agent_dir = session_home / ".pi" / "agent"
+ agent_dir.mkdir(parents = True)
+ (agent_dir / "settings.json").write_text(json.dumps({"themes": {"name": "dark"}}))
+
+ start.write_pi_user_resources(agent_dir, session_home)
+
+ # Not a shape we understand, so it is left alone rather than deleted.
+ assert json.loads((agent_dir / "settings.json").read_text())["themes"] == {"name": "dark"}
+
+
[email protected]("entry", ["", " ", "."])
+def test_pi_local_entry_leaves_degenerate_entries_alone(tmp_path, entry):
+ # Anchoring these would name the user's whole agent directory.
+ assert start._pi_local_entry(entry, tmp_path, tmp_path, frozenset()) == entry
+
+
[email protected]("dangling", [False, True])
+def test_remove_overlay_entry_rmdirs_a_windows_directory_symlink(tmp_path, monkeypatch, dangling):
+ # unlink maps to DeleteFileW, which refuses a directory symlink with WinError 5,
+ # and a dangling link is still one: is_dir() would follow the missing target.
+ source = tmp_path / "source"
+ source.mkdir()
+ (source / "keep.txt").write_text("keep\n")
+ target = tmp_path / "link"
+ target.symlink_to(source, target_is_directory = True)
+ if dangling:
+ shutil.rmtree(source)
+ source.mkdir() # restore the sentinel dir so the assertion below still reads
+ (source / "keep.txt").write_text("keep\n")
+ target.unlink()
+ target.symlink_to(tmp_path / "gone", target_is_directory = True)
+ # POSIX lstat has no st_file_attributes; stand in for the Windows link attributes.
+ real_lstat = os.lstat
+ monkeypatch.setattr(
+ start.os,
+ "lstat",
+ lambda p: SimpleNamespace(
+ st_file_attributes = 0x10,
+ st_reparse_tag = 0,
+ st_mode = real_lstat(p).st_mode,
+ ),
+ )
+ # rmdir on a link is POSIX-invalid, so record the routing instead of running it.
+ monkeypatch.setattr(start.os, "name", "nt")
+ calls = []
+ monkeypatch.setattr(start.Path, "unlink", lambda self, **kw: calls.append("unlink"))
+ monkeypatch.setattr(start.Path, "rmdir", lambda self: calls.append("rmdir"))
+
+ start._remove_overlay_entry(target)
+
+ assert calls == ["rmdir"]
+ assert (source / "keep.txt").read_text() == "keep\n"
@pytest.mark.parametrize("yolo", [False, True])
@@ -5607,6 +6040,9 @@ def test_connect_pi_as_subagent_preserves_cloud_parent(fake_studio, tmp_path, yo
def test_connect_pi_no_launch_windows_relocates_userprofile(fake_studio, tmp_path, monkeypatch):
# On native Windows Node resolves ~/.pi via USERPROFILE, not HOME, so the session
# must point USERPROFILE at the relocated home or Pi reads the user's real ~/.pi.
+ user_home = _pi_user_agent_dir(tmp_path, monkeypatch).parent.parent
+ # Avoid pathlib selecting WindowsPath on this POSIX runner.
+ monkeypatch.setattr(start.Path, "home", lambda: user_home)
monkeypatch.setattr(start.os, "name", "nt")
result = CliRunner().invoke(start.start_app, ["pi", "--no-launch"])
assert result.exit_code == 0, result.output