Python
Sandbox: the developer-tool folders a sandbox may read, with switches in Settings
Rohit C Prasadb5571573b6b2
diff --git a/coworker/agent.py b/coworker/agent.pyindex 40fd651f..52a7be72 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -348,6 +348,7 @@ def build_engine(agent=agent.name,credentials=config.sandbox_credentials,network_profile=config.sandbox_network_profile,+ toolchains=config.sandbox_toolchains,)if ws is not Noneelse Nonediff --git a/coworker/config.py b/coworker/config.pyindex 26c05ff8..d3e2b885 100644--- a/coworker/config.py+++ b/coworker/config.py@@ -127,6 +127,10 @@ class Config:# Which hosts a sandbox may reach: a profile name from coworker/sandbox/network_profiles.py# ("strict" when unset). Machine-level, like the provider.sandbox_network_profile: Optional[str] = None+ # Developer tool folders under the home folder a sandbox may read (design doc, Windows+ # 3d.4): `[[sandbox_toolchains]]` tables with name, path, enabled, editing or adding to+ # the shipped list in coworker/sandbox/toolchains.py by name. Machine-level.+ sandbox_toolchains: list[dict[str, Any]] = field(default_factory=list)_FIELDS = {@@ -139,6 +143,7 @@ _FIELDS = {"sandbox_provider","sandbox_credentials","sandbox_network_profile",+ "sandbox_toolchains","compaction_cap_tokens","compaction_summary_max_tokens","allowed_commands",@@ -165,6 +170,7 @@ _GLOBAL_ONLY_FIELDS = {"sandbox_provider","sandbox_credentials","sandbox_network_profile",+ "sandbox_toolchains","allowed_commands","auto_allow","allowed_domains",diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.pyindex 15ff9bed..5bc379bb 100644--- a/coworker/sandbox/providers/seatbelt.py+++ b/coworker/sandbox/providers/seatbelt.py@@ -87,6 +87,7 @@ class SeatbeltProvider:roots: Sequence[dict[str, Any]],cwd: str | Path,profile: str = network_profiles.DEFAULT_PROFILE,+ tool_dirs: Optional[Sequence[str]] = None,network: bool = True,runner_path: Optional[Path] = None,relay_silence_seconds: Optional[float] = None,@@ -98,6 +99,7 @@ class SeatbeltProvider:self.copied: Optional[creds.CopiedCredentials] = Noneself.cwd = seatbelt_profile.real(cwd)self.profile = network_profiles.check(profile)+ self.tool_dirs = list(tool_dirs) if tool_dirs is not None else None # None: the shipped listself.network = networkself._runner = Path(runner_path) if runner_path is not None else build_runner_zipapp()self._relay_silence = relay_silence_seconds@@ -133,6 +135,7 @@ class SeatbeltProvider:read_only=[str(self._runner), *read_paths(), str(toolchain.bin_dir())],proxy_port=self._proxy.port if self._proxy is not None else None,open_network=self.network and network_profiles.is_open(self.profile),+ tool_dirs=self.tool_dirs,)def _environment(self) -> dict[str, str]:diff --git a/coworker/sandbox/providers/seatbelt_profile.py b/coworker/sandbox/providers/seatbelt_profile.pyindex 6af75cee..e6dfb23e 100644--- a/coworker/sandbox/providers/seatbelt_profile.py+++ b/coworker/sandbox/providers/seatbelt_profile.py@@ -21,6 +21,8 @@ import osfrom pathlib import Pathfrom typing import Any, Optional, Sequence+from .. import toolchains+# Programs, libraries and settings. No entry here is under a home folder._SYSTEM_READ = ["/usr",@@ -39,24 +41,9 @@ _SYSTEM_READ = [# Folders that must be walkable for path lookups to work, without listing what is in them._LITERAL_READ = ["/", "/private", "/private/tmp", "/private/var", "/private/var/folders", "/Users", "/Volumes"]-# Developer toolchains under the home folder: readable, never writable.-TOOLCHAINS = [- ".nvm",- ".volta",- ".bun",- ".deno",- ".pyenv",- ".rbenv",- ".asdf",- ".sdkman",- ".cargo",- ".rustup",- ".local/bin",- ".local/share/uv",- ".local/share/mise",- ".local/pipx",- "go",-]+# Developer toolchains under the home folder: readable, never writable. The list lives in+# toolchains.py (with the Windows one) and the user edits it in Settings ▸ Sandbox.+TOOLCHAINS = [e["path"][2:] for e in toolchains.defaults("darwin")]# The user's git settings. Files, not folders of secrets: credentials live in the keychain.GIT_SETTINGS = [".gitconfig", ".gitignore", ".gitignore_global", ".config/git"]@@ -99,10 +86,12 @@ def _literals(paths: Sequence[str]) -> str:return " ".join(f"(literal {_quote(p)})" for p in paths)-def home_read_only(home: Optional[str] = None) -> list[str]:- """The toolchain folders and git settings that exist under this home folder."""+def home_read_only(home: Optional[str] = None, tool_dirs: Optional[Sequence[str]] = None) -> list[str]:+ """The toolchain folders (the machine's list, or the shipped one) and git settings that+ exist under this home folder."""base = Path(real(home or "~"))- return [real(base / name) for name in (*TOOLCHAINS, *GIT_SETTINGS) if (base / name).exists()]+ tools = [real(p) for p in tool_dirs] if tool_dirs is not None else [real(base / name) for name in TOOLCHAINS if (base / name).exists()]+ return tools + [real(base / name) for name in GIT_SETTINGS if (base / name).exists()]def render(@@ -113,6 +102,7 @@ def render(proxy_port: Optional[int] = None,home: Optional[str] = None,open_network: bool = False,+ tool_dirs: Optional[Sequence[str]] = None,) -> str:"""`roots`: [{"path": absolute path, "writable": bool}]. `runtime_dir`: this sandbox'sown folder (socket and temporary files). `read_only`: more paths to read, e.g. the@@ -120,7 +110,7 @@ def render(and any local port, no proxy; the files stay confined."""writable = [real(r["path"]) for r in roots if r.get("writable")]readable = [real(r["path"]) for r in roots if not r.get("writable")]- readable += [real(p) for p in read_only] + home_read_only(home)+ readable += [real(p) for p in read_only] + home_read_only(home, tool_dirs)runtime = real(runtime_dir)lines = ["(version 1)",diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex bbd7a291..5a4a7774 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -102,13 +102,17 @@ class WindowsProvider:relay_silence_seconds: Optional[float] = None,credentials: Sequence[creds.Grant] = (),force_mode: Optional[str] = None,+ tool_dirs: Sequence[str] = (),) -> None:"""`credentials`: the grants (credentials.granted) to copy into the sandbox.- `force_mode`: tests only; `partial` on a machine where setup has run."""+ `tool_dirs`: developer tool folders under the profile the account may read (the+ full mode; the same-user mode reads them anyway). `force_mode`: tests only;+ `partial` on a machine where setup has run."""from .. import winsecself.roots = _clean_roots(roots)self.grants = list(credentials)+ self.tool_dirs = [os.path.realpath(p) for p in tool_dirs]self.copied: Optional[creds.CopiedCredentials] = Noneself.cwd = os.path.realpath(str(cwd))self.profile = network_profiles.check(profile)@@ -185,6 +189,10 @@ class WindowsProvider:for root in self.roots:self._grant(root["path"], "write" if root["writable"] else "read")self._grant(self._dir, "write")+ if self.mode == FULL:+ for folder in self.tool_dirs: # readable to the account, never writable+ if os.path.isdir(folder):+ self._grant(folder, "read")self._desktop = winsec.Desktop(self.session_sid)log = os.path.join(self._dir, "daemon.log")if self.mode == FULL:@@ -193,9 +201,15 @@ class WindowsProvider:# The runner file lives in the user's state folder, which the account cannot see.self._runner_inside = Path(self._dir) / self._runner.nameshutil.copy2(self._runner, self._runner_inside)- env_args = [arg for k, v in self._environment(full=True).items() for arg in ("--env", f"{k}={v}")]+ # The environment goes through a file in the private folder (the account reads+ # it): CreateProcessWithLogonW allows 1024 characters of command line, and PATH+ # alone can be longer than that.+ import json++ env_file = os.path.join(self._dir, "env.json")+ Path(env_file).write_text(json.dumps(self._environment(full=True)), encoding="utf-8")serve = serve_arguments(self.socket_path, self._dir, also_sids=[sid])- argv = [*runner_command(self._runner_inside), "serve", *serve, *env_args, "--cwd", self.cwd, "--exit-with-parent"]+ argv = [*runner_command(self._runner_inside), "serve", *serve, "--env-file", env_file, "--cwd", self.cwd, "--exit-with-parent"]self._daemon = winsec.spawn_as_account(argv, account=name, password=password, desktop=self._desktop, cwd=self.cwd, stderr_path=log)else:self._runner_inside = self._runner@@ -226,6 +240,9 @@ class WindowsProvider:into the private folder. Full mode: only what the account's own environment lacks(the proxy), because the account has a profile, temp and caches of its own."""env: dict[str, str] = {} if full else clean_environment()+ if full:+ # The account's own PATH knows nothing of the person's tools; the person's does.+ env["PATH"] = os.environ.get("PATH", "")if not full:temp = os.path.join(self._dir, "tmp")os.makedirs(temp, exist_ok=True)@@ -366,6 +383,8 @@ class WindowsProvider:one is closed at once."""self.roots = _clean_roots(roots)wanted = [(r["path"], "write" if r["writable"] else "read") for r in self.roots] + [(self._dir, "write")]+ if self.mode == FULL:+ wanted += [(folder, "read") for folder in self.tool_dirs if os.path.isdir(folder)]for entry in list(self._granted):if entry not in wanted:self._revoke(*entry)diff --git a/coworker/sandbox/runner/__main__.py b/coworker/sandbox/runner/__main__.pyindex 8f617622..1d5346be 100644--- a/coworker/sandbox/runner/__main__.py+++ b/coworker/sandbox/runner/__main__.py@@ -25,6 +25,7 @@ def main(argv: list[str] | None = None) -> int:serve.add_argument("--dir", default=None, help="this runner's own folder, removed at shutdown (default: the socket's folder)")serve.add_argument("--allow-sid", action="append", default=[], help="Windows: an account that may connect to the pipe (repeatable)")serve.add_argument("--env", action="append", default=[], metavar="NAME=VALUE", help="set a variable for the shells (repeatable; for a provider that cannot pass an environment)")+ serve.add_argument("--env-file", default=None, help="a JSON object of variables for the shells (a command line that must stay short: Windows' logon call allows 1024 characters)")attach = sub.add_parser("attach", help="connect this process's stdin/stdout to the daemon")attach.add_argument("--socket", required=True)attach.add_argument("--silence-seconds", type=float, default=None, help="leave after this much client silence (0 = never)")@@ -39,6 +40,12 @@ def main(argv: list[str] | None = None) -> int:return run_connect(args.proxy_host, args.proxy_port, args.host, args.port)if args.command == "serve":+ if args.env_file:+ import json++ with open(args.env_file, encoding="utf-8") as fh:+ for name, value in json.load(fh).items():+ os.environ[str(name)] = str(value)for item in args.env:name, sep, value = item.partition("=")if sep and name:diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex c46f3563..01dd524a 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -9,7 +9,7 @@ import sysfrom typing import Any, Optionalfrom .. import config as app_config-from . import credentials, network_profiles+from . import credentials, network_profiles, toolchainsfrom .workspace import DIRECT, OPENSHELL, SEATBELT, WINDOWS@@ -74,6 +74,7 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:{"name": name, "hosts": network_profiles.hosts(name)} for name in network_profiles.PROFILES],"credentials": _for_display(credentials.entries(cfg.sandbox_credentials)),+ "toolchains": toolchains.for_display(cfg.sandbox_toolchains),"config_path": str(app_config.global_config_path()),}@@ -147,6 +148,33 @@ def update(body: dict[str, Any]) -> dict[str, Any]:if len(diff) > 1:slim.append(diff)app_config.set_global_tables("sandbox_credentials", slim)+ if "toolchains" in body:+ rows = body.get("toolchains")+ if not isinstance(rows, list):+ return {"ok": False, "error": "toolchains must be a list"}+ cleaned = []+ for raw in rows:+ if not isinstance(raw, dict) or not str(raw.get("name") or "").strip():+ return {"ok": False, "error": "every toolchain entry needs a name"}+ path = str(raw.get("path") or "").strip()+ if path and not (path.startswith("~/") or path.startswith("/") or path[1:3] == ":\\" or path[1:3] == ":/"):+ return {"ok": False, "error": f"the path for '{raw['name']}' must start with ~/ or be absolute"}+ row = {"name": str(raw["name"]).strip(), "enabled": bool(raw.get("enabled"))}+ for key in ("title", "path"):+ if raw.get(key) is not None:+ row[key] = str(raw[key])+ cleaned.append(row)+ shipped = {e["name"]: e for e in toolchains.defaults()}+ slim = []+ for row in cleaned:+ base = shipped.get(row["name"])+ if base is None:+ slim.append(row)+ continue+ diff = {k: v for k, v in row.items() if k == "name" or base.get(k) != v}+ if len(diff) > 1:+ slim.append(diff)+ app_config.set_global_tables("sandbox_toolchains", slim)return {"ok": True, **snapshot()}diff --git a/coworker/sandbox/toolchains.py b/coworker/sandbox/toolchains.pynew file mode 100644index 00000000..a5b434b9--- /dev/null+++ b/coworker/sandbox/toolchains.py@@ -0,0 +1,105 @@+"""Developer tools under the home folder that a sandbox may READ (design doc, Windows 3d.4;+macOS section 11 step 4).++A sandbox hides the home folder, and with it the tools people install per user: Node+versions under `.nvm`, Python versions under `.pyenv`, Cargo, Scoop. Without these the+agent has no `node`. So a fixed list of tool folders is readable, never writable, and the+user can switch each off or add one, machine-level, in Settings ▸ Sandbox+(`[[sandbox_toolchains]]` in the machine's config.toml; a project cannot change it).++Per platform. The Mac list is what the Seatbelt profile always granted; the Windows list+is the ruling of 2026-09-25. OpenShell mounts no home folder, so it has no list.+"""++from __future__ import annotations++import os+import sys+from typing import Any, Optional, Sequence++# name, title, path under the home folder (forward slashes on every platform)+_MAC: list[tuple[str, str, str]] = [+ ("nvm", "nvm (Node versions)", "~/.nvm"),+ ("volta", "Volta", "~/.volta"),+ ("bun", "Bun", "~/.bun"),+ ("deno", "Deno", "~/.deno"),+ ("pyenv", "pyenv (Python versions)", "~/.pyenv"),+ ("rbenv", "rbenv", "~/.rbenv"),+ ("asdf", "asdf", "~/.asdf"),+ ("sdkman", "SDKMAN", "~/.sdkman"),+ ("cargo", "Cargo", "~/.cargo"),+ ("rustup", "rustup", "~/.rustup"),+ ("local-bin", "~/.local/bin", "~/.local/bin"),+ ("uv", "uv", "~/.local/share/uv"),+ ("mise", "mise", "~/.local/share/mise"),+ ("pipx", "pipx", "~/.local/pipx"),+ ("go", "Go", "~/go"),+]+_WINDOWS: list[tuple[str, str, str]] = [+ ("nvm", "nvm for Windows (Node versions)", "~/AppData/Roaming/nvm"),+ ("npm", "npm global packages", "~/AppData/Roaming/npm"),+ ("pyenv", "pyenv-win (Python versions)", "~/.pyenv"),+ ("python", "Python (per-user install)", "~/AppData/Local/Programs/Python"),+ ("scoop", "Scoop", "~/scoop"),+ ("cargo", "Cargo", "~/.cargo"),+ ("rustup", "rustup", "~/.rustup"),+ ("go", "Go", "~/go"),+ ("pipx", "pipx", "~/AppData/Local/pipx"),+ ("uv", "uv", "~/AppData/Local/uv"),+]+++def defaults(platform: str = sys.platform) -> list[dict[str, Any]]:+ """The shipped list for a platform, every entry switched on."""+ rows = _WINDOWS if platform == "win32" else _MAC if platform == "darwin" else []+ return [{"name": n, "title": t, "path": p, "enabled": True} for n, t, p in rows]+++def entries(configured: Optional[Sequence[dict[str, Any]]], platform: str = sys.platform) -> list[dict[str, Any]]:+ """The machine's list: the shipped entries with the user's edits and additions applied+ by name."""+ by_name = {e["name"]: dict(e) for e in defaults(platform)}+ for raw in configured or []:+ if not isinstance(raw, dict) or not str(raw.get("name") or "").strip():+ continue+ name = str(raw["name"]).strip()+ base = by_name.get(name, {"name": name, "title": name, "path": "", "enabled": True})+ merged = {**base, **{k: v for k, v in raw.items() if v is not None}}+ merged["enabled"] = bool(merged.get("enabled"))+ by_name[name] = merged+ return list(by_name.values())+++def _real(path: str, home: str) -> str:+ text = str(path).replace("\\", "/")+ if text == "~" or text.startswith("~/"):+ text = os.path.join(home, *text[2:].split("/")) if len(text) > 1 else home+ return os.path.realpath(os.path.expanduser(text))+++def granted(+ configured: Optional[Sequence[dict[str, Any]]], *, home: Optional[str] = None, platform: str = sys.platform+) -> list[str]:+ """Real paths of the entries that are switched on AND exist under this home folder.+ Never the home folder itself, never something outside it."""+ home = os.path.realpath(home or os.path.expanduser("~"))+ out: list[str] = []+ for e in entries(configured, platform):+ if not e.get("enabled") or not e.get("path"):+ continue+ real = _real(str(e["path"]), home)+ if real == home or not real.startswith(home + os.sep) or not os.path.exists(real):+ continue+ if real not in out:+ out.append(real)+ return out+++def for_display(configured: Optional[Sequence[dict[str, Any]]], *, home: Optional[str] = None, platform: str = sys.platform) -> list[dict[str, Any]]:+ """The entries with `exists` (on this machine) and `shipped` (in the default list)."""+ home = os.path.realpath(home or os.path.expanduser("~"))+ shipped = {e["name"] for e in defaults(platform)}+ return [+ {**e, "exists": bool(e.get("path")) and os.path.exists(_real(str(e["path"]), home)), "shipped": e["name"] in shipped}+ for e in entries(configured, platform)+ ]diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex ad602ef0..64cb8377 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -208,10 +208,13 @@ def open_workspace(agent: str = "",credentials: Optional[list] = None,network_profile: Optional[str] = None,+ toolchains: Optional[list] = None,) -> Workspace:"""The session's workspace for the configured provider. `credentials`: the machine's`sandbox_credentials` setting; the enabled entries are copied into the sandbox(design doc, section 11b). Ignored in `direct` mode, where nothing is hidden anyway. `direct` unless told otherwise.+ `toolchains`: the machine's `sandbox_toolchains` setting; the switched-on folders that+ exist are readable inside (Seatbelt, Windows full mode).`roots`: the session's RootDir list (primary first); without it the workspace folder isthe only, writable, root. `session_id` and `agent` say who the sandbox is for; they gointo the registry and onto the sandbox as a label."""@@ -230,12 +233,15 @@ def open_workspace(from .network_profiles import check, default_profileprofile = check((network_profile or "").strip().lower() or default_profile())+ from . import toolchains as toolchain_list++ tool_dirs = toolchain_list.granted(toolchains)if name == SEATBELT:from .providers.seatbelt import SeatbeltProviderfrom .registry import SandboxRegistryreturn RunnerWorkspace(- SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile),+ SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs),cwd=cwd,registry=SandboxRegistry(),session_id=session_id,@@ -260,7 +266,7 @@ def open_workspace(from .registry import SandboxRegistryreturn RunnerWorkspace(- WindowsProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile),+ WindowsProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs),cwd=cwd,registry=SandboxRegistry(),session_id=session_id,diff --git a/docs/config.example.toml b/docs/config.example.tomlindex 056e89ac..4a4f1e73 100644--- a/docs/config.example.toml+++ b/docs/config.example.toml@@ -45,3 +45,12 @@ port = 8765# [[sandbox_credentials]]# name = "ssh"# enabled = true+# Developer tool folders under your home folder a sandbox may read (never write). The+# shipped list per platform is in Settings ▸ Sandbox; an entry here switches one off or+# adds one by name.+# [[sandbox_toolchains]]+# name = "nvm"+# enabled = false+# [[sandbox_toolchains]]+# name = "mytools"+# path = "~/tools"diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.mdindex 51e5eae1..b02d6ff0 100644--- a/docs/macos-sandbox.md+++ b/docs/macos-sandbox.md@@ -49,10 +49,11 @@ Read only:- the session's read-only folders;- the system: `/usr`, `/bin`, `/System`, `/Library`, `/opt`, `/Applications`, `/private/etc`;- OpenWorker's managed tools folder, the tool runner and its Python;-- under your home folder, only a fixed list of developer toolchains — `.nvm`, `.volta`,- `.bun`, `.deno`, `.pyenv`, `.rbenv`, `.asdf`, `.sdkman`, `.cargo`, `.rustup`,- `.local/bin`, `.local/share/uv`, `.local/share/mise`, `.local/pipx`, `go` — plus git's- settings (`.gitconfig`, `.config/git`).+- under your home folder, only the developer toolchains on the list in Settings ▸+ Sandbox — shipped: `.nvm`, `.volta`, `.bun`, `.deno`, `.pyenv`, `.rbenv`, `.asdf`,+ `.sdkman`, `.cargo`, `.rustup`, `.local/bin`, `.local/share/uv`, `.local/share/mise`,+ `.local/pipx`, `go`; each with a switch, and you can add a folder — plus git's settings+ (`.gitconfig`, `.config/git`).Network: `localhost` on the proxy's port, nothing else. `curl`, `git`, `pip` and `npm`follow the proxy variables; a program that ignores them has no network at all.diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.mdindex dda067e1..bc2f681f 100644--- a/docs/windows-sandbox.md+++ b/docs/windows-sandbox.md@@ -151,13 +151,17 @@ Read only:account read those by default, and so can the sandbox. Keep what the agent must not seeunder your profile.+Read only, from your profile, so the agent can run your tools:++- developer tools installed per user, from a list you control in Settings ▸ Sandbox:+ nvm for Windows and npm's global folder (`AppData\Roaming`), pyenv-win, per-user+ Python installs, Scoop, Cargo, rustup, Go, pipx and uv. Each has a switch; you can add+ a folder. The session also inherits your `PATH`, so those tools resolve. Nothing under+ them is writable.+Not readable:-- your profile, `C:\Users\<you>`, and every other account's profile. This includes- developer tools installed per user (nvm for Windows, pyenv-win, Scoop, npm's global- folder, Cargo). A read-only list of those, with switches in Settings, is the next- change; until then, install the tools the agent needs machine-wide, or grant the folder- to the session.+- the rest of your profile, `C:\Users\<you>`, and every other account's profile.## Sharing a credential on purpose@@ -211,6 +215,6 @@ expire on their own limit what that is worth.|---|---|---|---|| Mechanism | a second local account, permissions, firewall and kernel filters | the Seatbelt profile built into macOS | a Linux container with Landlock and seccomp || Install | one administrator prompt | nothing | OpenShell and Docker |-| Files | session folders; profile invisible; outside-profile folders readable | session folders; home invisible | session folders; nothing else |+| Files | session folders; profile invisible except the tool list; outside-profile folders readable | session folders; home invisible except the tool list | session folders; nothing else || Network | open (default), or the allow list through the proxy | the allow list through the proxy, or open | the allow list in the policy, or open || Default | open | strict | strict |diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 5209a656..7b0f8e1f 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2097,6 +2097,14 @@ export interface SandboxCredentialEntry {does?: string;enabled: boolean;}+export interface SandboxToolchainEntry {+ name: string;+ title?: string;+ path: string;+ enabled: boolean;+ exists?: boolean; // on this machine+ shipped?: boolean; // in the default list (cannot be removed, only switched off)+}export interface SandboxSettings {platform: string;provider: string; // "" = the default rule@@ -2106,6 +2114,7 @@ export interface SandboxSettings {network_profile: string;network_profiles: { name: string; hosts: string[] }[];credentials: SandboxCredentialEntry[];+ toolchains: SandboxToolchainEntry[];config_path: string;}@@ -2115,7 +2124,7 @@ export async function getSandboxSettings(machineId?: string | null): Promise<San}export async function setSandboxSettings(- patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials">>,+ patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials" | "toolchains">>,machineId?: string | null,): Promise<{ ok: boolean; error?: string } & Partial<SandboxSettings>> {const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox`, {diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsxindex a6630ed9..82e8dfbc 100644--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx@@ -22,6 +22,10 @@ const snapshot = {{ name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: false },{ name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },],+ toolchains: [+ { name: "nvm", title: "nvm (Node versions)", path: "~/.nvm", enabled: true, exists: true, shipped: true },+ { name: "mytools", title: "My tools", path: "~/tools", enabled: true, exists: false, shipped: false },+ ],config_path: "/Users/sam/.config/coworker/config.toml",};@@ -104,4 +108,31 @@ describe("Settings ▸ Sandbox", () => {expect(last.credentials.map((c: any) => c.name)).toEqual(["gh", "npm-token"]);});});++ it("switches a toolchain folder off and adds one, without the display-only fields", async () => {+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-section");+ expect(screen.getByText(/not on this machine/)).toBeTruthy();+ fireEvent.click(screen.getByLabelText("nvm (Node versions)"));+ await waitFor(() =>+ expect(setSandboxSettings).toHaveBeenLastCalledWith({+ toolchains: [+ { name: "nvm", title: "nvm (Node versions)", path: "~/.nvm", enabled: false },+ { name: "mytools", title: "My tools", path: "~/tools", enabled: true },+ ],+ }),+ );+ fireEvent.click(screen.getByTestId("sandbox-toolchain-add"));+ const editor = screen.getByTestId("sandbox-toolchain-editor");+ const inputs = editor.querySelectorAll("input");+ fireEvent.change(inputs[0], { target: { value: "Zig" } });+ fireEvent.change(inputs[1], { target: { value: "~/.zig" } });+ fireEvent.click(screen.getAllByText("Done")[0]);+ await waitFor(() => {+ const calls = setSandboxSettings.mock.calls;+ const last = calls[calls.length - 1]?.[0];+ expect(last.toolchains.map((c: any) => c.name)).toEqual(["nvm", "mytools", "zig"]);+ expect(last.toolchains[2]).toEqual({ name: "zig", title: "Zig", path: "~/.zig", enabled: true });+ });+ });});diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex a594385d..dc037bfc 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -36,6 +36,7 @@ import {type ModelSettings,type PdfSettings,type SandboxCredentialEntry,+ type SandboxToolchainEntry,type SandboxSettings,type WorkspaceCommandTrust,} from "../api";@@ -729,6 +730,9 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {const [cfg, setCfg] = useState<SandboxSettings | null>(null);const [error, setError] = useState<string>("");const [editing, setEditing] = useState<string | null>(null); // credential name being edited, "" = new+ const [addingTool, setAddingTool] = useState(false); // the "Add a folder" editor of the toolchain list+ const [toolTitle, setToolTitle] = useState("");+ const [toolPath, setToolPath] = useState("~/");useEffect(() => {getSandboxSettings(mid).then(setCfg).catch(() => setCfg(null));@@ -758,6 +762,7 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {return v === k ? fallback || "" : v;};const updateCredentials = (rows: SandboxCredentialEntry[]) => save({ credentials: rows });+ const updateToolchains = (rows: SandboxToolchainEntry[]) => save({ toolchains: rows.map(({ exists: _e, shipped: _s, ...row }) => row) });return (<section data-testid="sandbox-section">@@ -876,6 +881,68 @@ function SandboxSection({ machine }: { machine?: Machine | null }) {}}/>) : null}++ {cfg.platform !== "linux" && cfg.toolchains ? (+ <>+ <div className="flex items-center mb-2 mt-6">+ <div className={FIELD_LABEL}>{t("settingsx.sandbox.toolchains")}</div>+ <button className="ml-auto text-ui text-accent" onClick={() => setAddingTool(true)} data-testid="sandbox-toolchain-add">+ {t("settingsx.sandbox.add_toolchain")}+ </button>+ </div>+ <div className={CARD + " divide-y divide-line"}>+ {cfg.toolchains.map((tc) => (+ <div key={tc.name} className="flex items-start gap-3 px-4 py-2.5" data-testid={`sandbox-toolchain-${tc.name}`}>+ <input+ type="checkbox"+ className="mt-1"+ checked={tc.enabled}+ onChange={(e) => updateToolchains(cfg.toolchains.map((x) => (x.name === tc.name ? { ...x, enabled: e.target.checked } : x)))}+ aria-label={tc.title || tc.name}+ />+ <span className="flex-1 min-w-0">+ <span className={"block text-ui " + (tc.exists === false ? "text-muted" : "text-ink")}>+ {tc.title || tc.name} <code className="text-meta text-muted font-mono">{tc.path}</code>+ {tc.exists === false ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.toolchain_missing")}</span> : null}+ </span>+ </span>+ {!tc.shipped ? (+ <button className="text-meta text-muted hover:text-ink shrink-0" onClick={() => updateToolchains(cfg.toolchains.filter((x) => x.name !== tc.name))}>+ {t("settingsx.sandbox.remove")}+ </button>+ ) : null}+ </div>+ ))}+ </div>+ <div className={FIELD_HELP}>{t("settingsx.sandbox.toolchains_help")}</div>+ {addingTool ? (+ <div className={CARD + " p-4 mt-3"} data-testid="sandbox-toolchain-editor">+ <div className="grid grid-cols-[150px_1fr] gap-x-3 gap-y-2 items-center">+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_title")}</label>+ <input className={INPUT} value={toolTitle} onChange={(e) => setToolTitle(e.target.value)} />+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_toolchain_path")}</label>+ <input className={INPUT + " font-mono"} value={toolPath} onChange={(e) => setToolPath(e.target.value)} />+ </div>+ <div className="flex justify-end gap-2 mt-3">+ <button className={BTN_BORDERED} onClick={() => setAddingTool(false)}>{t("settingsx.sandbox.cancel")}</button>+ <button+ className={BTN_ACCENT}+ disabled={!(toolPath.startsWith("~/") || toolPath.startsWith("/")) || toolPath.length < 3}+ onClick={() => {+ const slug = (toolTitle || toolPath).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");+ setAddingTool(false);+ setToolTitle("");+ setToolPath("~/");+ updateToolchains([...cfg.toolchains, { name: slug, title: toolTitle || undefined, path: toolPath, enabled: true }]);+ }}+ >+ {t("settingsx.sandbox.done")}+ </button>+ </div>+ </div>+ ) : null}+ </>+ ) : null}</section>);}diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex 302384ce..e3e34cb4 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2305,6 +2305,11 @@"field_hosts": "Hosts it needs (host:port, one per line)","field_does": "Lets the agent","credentials_help": "Switched-on entries are copied into every sandbox on this machine for the session, and deleted with it. Your real files are never touched.",+ "toolchains": "Developer tools the sandbox may read",+ "toolchains_help": "Tools installed under your home folder are hidden with the rest of it. These folders are readable, never writable, so the agent can run them. Switch one off, or add a folder.",+ "toolchain_missing": "not on this machine",+ "add_toolchain": "Add a folder…",+ "field_toolchain_path": "Folder (under your home folder)","keychain_note": "Logins kept in the macOS Keychain (git over HTTPS) are not files and cannot be shared. Use an SSH remote, or the GitHub connector.","does_ssh": "Push and pull over SSH, and log in to servers, as you.","does_gh": "Use gh as you: pull requests, issues, releases.",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex c1d758ce..728d6c8d 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2265,6 +2265,11 @@"field_hosts": "所需主机(host:port,每行一个)","field_does": "让同事可以","credentials_help": "已开启的条目会在会话期间复制到这台机器上的每个沙箱中,并随沙箱一起删除。你的真实文件不会被改动。",+ "toolchains": "沙箱可读取的开发工具",+ "toolchains_help": "安装在你主目录下的工具会随主目录一起被隐藏。这些文件夹只读、不可写,以便同事运行它们。可关闭某一项,或添加文件夹。",+ "toolchain_missing": "这台机器上没有",+ "add_toolchain": "添加文件夹…",+ "field_toolchain_path": "文件夹(在你的主目录下)","keychain_note": "保存在 macOS 钥匙串中的登录信息(HTTPS 方式的 git)不是文件,无法共享。请使用 SSH 远程地址,或 GitHub 连接器。","does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。","does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",diff --git a/tests/test_sandbox_seatbelt.py b/tests/test_sandbox_seatbelt.pyindex 7d0e1271..2daa8f94 100644--- a/tests/test_sandbox_seatbelt.py+++ b/tests/test_sandbox_seatbelt.py@@ -166,6 +166,18 @@ def test_the_open_profile_has_no_list_and_is_the_default_on_windows_only(tmp_patassert "(allow network*)" in text and "localhost:" not in text and "(deny default)" in text+@posix_paths+def test_profile_reads_the_machines_toolchain_list_when_given(tmp_path):+ home = tmp_path / "home"+ (home / "tools").mkdir(parents=True)+ (home / ".nvm").mkdir()+ project = tmp_path / "project"+ project.mkdir()+ text = seatbelt_profile.render([{"path": str(project), "writable": True}], runtime_dir=str(tmp_path / "rt"), home=str(home), tool_dirs=[str(home / "tools")])+ assert seatbelt_profile.real(str(home / "tools")) in text+ assert seatbelt_profile.real(str(home / ".nvm")) not in text # the list given replaces the shipped one++# -- selection ------------------------------------------------------------------------def test_an_explicit_seatbelt_setting_refuses_when_it_cannot_be_used(monkeypatch):def broken() -> None:diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.pyindex c11b3655..09af016a 100644--- a/tests/test_sandbox_settings.py+++ b/tests/test_sandbox_settings.py@@ -31,6 +31,29 @@ def test_snapshot_reports_the_default_rule_and_the_shipped_entries(config_file):assert [n["name"] for n in snap["network_profiles"]] == ["strict", "standard", "open"]assert [(e["name"], e["enabled"]) for e in snap["credentials"]] == [("ssh", False), ("gh", False), ("aws", False), ("kube", False)]assert snap["config_path"] == str(config_file)+ from coworker.sandbox import toolchains++ assert [e["name"] for e in snap["toolchains"]] == [e["name"] for e in toolchains.defaults()]+ assert all(e["shipped"] and e["enabled"] and "exists" in e for e in snap["toolchains"])+++def test_toolchain_switches_and_additions_are_written_slim(config_file):+ from coworker.sandbox import toolchains++ rows = [dict(e) for e in toolchains.defaults()]+ if rows:+ rows[0]["enabled"] = False+ rows.append({"name": "mytools", "title": "My tools", "path": "~/tools", "enabled": True})+ out = settings.update({"toolchains": rows})+ assert out["ok"], out+ text = config_file.read_text()+ assert text.count("[[sandbox_toolchains]]") == (2 if rows[:-1] else 1) # one switch, one addition; nothing else+ assert 'name = "mytools"' in text and 'path = "~/tools"' in text+ by = {e["name"]: e for e in settings.snapshot()["toolchains"]}+ assert by["mytools"]["enabled"] and not by["mytools"]["shipped"]+ if rows[:-1]:+ assert by[rows[0]["name"]]["enabled"] is False+ assert settings.update({"toolchains": [{"name": "x", "path": "relative/path"}]})["ok"] is Falsedef test_update_writes_only_what_differs_from_the_shipped_entries(config_file):diff --git a/tests/test_sandbox_toolchains.py b/tests/test_sandbox_toolchains.pynew file mode 100644index 00000000..9cfea76f--- /dev/null+++ b/tests/test_sandbox_toolchains.py@@ -0,0 +1,44 @@+"""The developer-tool folders a sandbox may read (coworker/sandbox/toolchains.py): a shipped+list per platform, the user's switches and additions by name, only what exists under the+home folder."""++from __future__ import annotations++import os++from coworker.sandbox import toolchains+++def test_the_shipped_lists_are_per_platform_and_switched_on():+ mac = toolchains.defaults("darwin")+ win = toolchains.defaults("win32")+ assert {e["name"] for e in mac} >= {"nvm", "pyenv", "cargo", "go", "uv"}+ assert {e["name"] for e in win} >= {"nvm", "npm", "pyenv", "scoop", "cargo"}+ assert all(e["enabled"] and e["path"].startswith("~/") for e in mac + win)+ assert toolchains.defaults("linux") == [] # OpenShell mounts no home folder+++def test_the_user_edits_and_adds_by_name():+ rows = toolchains.entries([{"name": "nvm", "enabled": False}, {"name": "mytools", "path": "~/tools", "title": "My tools"}], "darwin")+ by = {e["name"]: e for e in rows}+ assert by["nvm"]["enabled"] is False and by["nvm"]["path"] == "~/.nvm" # the path stays shipped+ assert by["mytools"] == {"name": "mytools", "title": "My tools", "path": "~/tools", "enabled": True}+++def test_granted_is_only_what_is_on_and_exists_under_home(tmp_path):+ home = tmp_path / "home"+ (home / ".nvm").mkdir(parents=True)+ (home / "tools").mkdir()+ (tmp_path / "outside").mkdir()+ configured = [+ {"name": "pyenv", "enabled": True}, # on, but missing here+ {"name": "cargo", "enabled": False},+ {"name": "mytools", "path": "~/tools"},+ {"name": "escape", "path": str(tmp_path / "outside")}, # outside the home folder: never+ {"name": "home", "path": "~"}, # the home folder itself: never+ ]+ got = toolchains.granted(configured, home=str(home), platform="darwin")+ assert got == [os.path.realpath(home / ".nvm"), os.path.realpath(home / "tools")]+ shown = {e["name"]: e for e in toolchains.for_display(configured, home=str(home), platform="darwin")}+ assert shown["nvm"]["exists"] and shown["nvm"]["shipped"]+ assert not shown["pyenv"]["exists"] and shown["mytools"]["exists"] and not shown["mytools"]["shipped"]diff --git a/tests/test_sandbox_windows.py b/tests/test_sandbox_windows.pyindex c094571b..118077bf 100644--- a/tests/test_sandbox_windows.py+++ b/tests/test_sandbox_windows.py@@ -309,6 +309,33 @@ def test_full_mode_blocks_the_network_except_the_proxy(tmp_path):ws.close()+@full+def test_full_mode_reads_the_toolchain_folders_it_is_given(tmp_path):+ """A folder under the person's profile (invisible to the account) becomes readable,+ never writable, when it is on the machine's toolchain list."""+ from coworker.sandbox.providers.windows import WindowsProvider++ tools = tmp_path / "AppData" / "Roaming" / "npm" # tmp_path is under the Administrator's profile+ tools.mkdir(parents=True)+ (tools / "tool.cmd").write_text("@echo tool ran\r\n")+ project = tmp_path / "project"+ project.mkdir()+ zipapp = build_runner_zipapp(tmp_path / "dist")+ provider = WindowsProvider(roots=[{"path": str(project), "writable": True}], cwd=project, runner_path=zipapp, network=False, force_mode="full", tool_dirs=[str(tools)])+ ws = RunnerWorkspace(provider, cwd=project)+ ws.executor.default_timeout = 60+ try:+ assert "tool ran" in ws.executor.run(f"& '{tools / 'tool.cmd'}'")["output"]+ assert ws.executor.run(f"Set-Content -Path '{tools / 'no.txt'}' -Value x")["exit_code"] != 0 # read only+ assert ws.executor.run(f"Get-ChildItem '{tmp_path}'")["exit_code"] != 0 # the folder beside it stays hidden+ assert "Administrator" in ws.executor.run("$env:PATH")["output"] # the person's PATH came along+ finally:+ ws.close()+ from coworker.sandbox import winsec++ assert not winsec.entries_for(str(tools), provider.session_sid)++@fulldef test_the_open_profile_runs_as_the_open_account_with_the_network_open(tmp_path):ws, provider, project = _open(tmp_path, mode="full", network=True, profile="open")