Python
Workspace tools run inside the tool runner when a session uses one
Devika Vermaced3390c074a
diff --git a/coworker/agent.py b/coworker/agent.pyindex 70b46963..2260141f 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -342,7 +342,7 @@ def build_engine(executor = sandbox_workspace.executor if sandbox_workspace is not None else Nonetodo = TodoList()context = AgentContext(- workspace=ws, executor=executor, todo=todo, roots=root_list or None+ workspace=ws, executor=executor, todo=todo, roots=root_list or None, sandbox=sandbox_workspace)registry = ToolRegistry()diff --git a/coworker/agents/base.py b/coworker/agents/base.pyindex 3caf7d7e..56feee30 100644--- a/coworker/agents/base.py+++ b/coworker/agents/base.py@@ -23,6 +23,10 @@ class AgentContext:# When None, tools fall back to the single `workspace` root. Held by reference so runtime# add/remove of folders is seen by the file tools built from it.roots: Optional[list] = None+ # The session's sandbox workspace (coworker.sandbox.workspace). In `direct` mode, or when+ # None, the workspace tools run in this process as they always have; with a tool runner+ # behind it, their execution goes there.+ sandbox: Optional[Any] = None@dataclassdiff --git a/coworker/catalog.py b/coworker/catalog.pyindex c910f37b..8d246312 100644--- a/coworker/catalog.py+++ b/coworker/catalog.py@@ -21,6 +21,7 @@ import aisuite as aifrom .agents.base import AgentContextfrom .risk import RiskClass+from .sandbox.proxy import proxy_toolsfrom .tools.files import file_toolsfrom .tools.git import git_toolsfrom .tools.search import search_tools@@ -97,6 +98,16 @@ def _describe_edit_tools(tools: list) -> list:return tools+def _placed(context: AgentContext, tools: list) -> list:+ """Where the workspace tools run. In `direct` mode (and whenever the session has no tool+ runner) they are returned untouched. With a runner, each is replaced by a proxy that has+ the same definition and sends only the execution into the sandbox."""+ sandbox = context.sandbox+ if sandbox is None or getattr(sandbox, "client", None) is None:+ return tools+ return proxy_tools(tools, sandbox, root=str(context.workspace), roots=context.roots)++def _code_files(context: AgentContext) -> list:"""Repo-oriented files: line-numbered/windowed `read_file`. Our `grep` and windowed`read_file` replace aisuite's slower `search_files` / `read_file`/`read_file_lines`.@@ -115,7 +126,7 @@ def _code_files(context: AgentContext) -> list:if getattr(t, "__name__", "") not in replaced])- return [*files, *file_tools(ws, roots=context.roots)]+ return _placed(context, [*files, *file_tools(ws, roots=context.roots)])def _files(context: AgentContext) -> list:@@ -136,16 +147,16 @@ def _files(context: AgentContext) -> list:if getattr(t, "__name__", "") not in replaced])- return [*files, *file_tools(ws, roots=context.roots)]+ return _placed(context, [*files, *file_tools(ws, roots=context.roots)])def _git(context: AgentContext) -> list:ws = str(context.workspace)- return [*ai.toolkits.git(root=ws), *git_tools(ws)] # git_status, git_diff, git_log+ return _placed(context, [*ai.toolkits.git(root=ws), *git_tools(ws)]) # git_status, git_diff, git_logdef _search(context: AgentContext) -> list:- return search_tools(str(context.workspace)) # grep (ripgrep, .gitignore-aware)+ return _placed(context, search_tools(str(context.workspace))) # grep (ripgrep, .gitignore-aware)def _shell(context: AgentContext) -> list:diff --git a/coworker/sandbox/bundle.py b/coworker/sandbox/bundle.pyindex 1151d962..3e006a61 100644--- a/coworker/sandbox/bundle.py+++ b/coworker/sandbox/bundle.py@@ -20,11 +20,40 @@ _PACKAGE = "owrunner" # the name the runner package has inside the zipapp_MAIN = f"from {_PACKAGE}.__main__ import main\nraise SystemExit(main())\n"+# aisuite's file and git toolkits are plain standard-library code except for one import of+# the `tool` decorator, which only their factory functions use. The runner calls the+# toolkit classes directly, so a do-nothing stand-in is enough inside the packed file.+_AISUITE_TOOLKITS = ("files", "git")+_AGENTS_STANDIN = '''"""Stand-in for `aisuite.agents` inside the packed runner (see bundle.py)."""+++class ToolMetadata:+ def __init__(self, **kwargs):+ self.__dict__.update(kwargs)+++def tool(fn=None, **_kwargs):+ return fn if fn is not None else (lambda f: f)+'''++def _sources() -> list[Path]:root = Path(__file__).parent / "runner"return sorted(p for p in root.glob("*.py"))+def _toolkit_sources() -> list[Path]:+ import importlib.util++ found = []+ for name in _AISUITE_TOOLKITS:+ spec = importlib.util.find_spec(f"aisuite.toolkits.{name}")+ if spec is None or not spec.origin or not spec.origin.endswith(".py"):+ raise RuntimeError(f"cannot find the source of aisuite.toolkits.{name} to pack into the tool runner")+ found.append(Path(spec.origin))+ return found++def runner_dir() -> Path:return state_dir() / "sandbox"@@ -33,8 +62,9 @@ def build_runner_zipapp(dest_dir: Optional[Path] = None) -> Path:"""Build (or reuse) the runner zipapp and return its path. The name carries a hash ofthe sources, so an upgraded or edited runner never reuses a stale file."""sources = _sources()- digest = hashlib.sha256()- for src in sources:+ toolkits = _toolkit_sources()+ digest = hashlib.sha256(_AGENTS_STANDIN.encode())+ for src in (*sources, *toolkits):digest.update(src.name.encode())digest.update(src.read_bytes())dest_dir = Path(dest_dir) if dest_dir is not None else runner_dir()@@ -47,6 +77,11 @@ def build_runner_zipapp(dest_dir: Optional[Path] = None) -> Path:zf.writestr("__main__.py", _MAIN)for src in sources:zf.write(src, f"{_PACKAGE}/{src.name}")+ # `from ..agents import ...` inside the toolkits resolves to this stand-in.+ zf.writestr(f"{_PACKAGE}/agents.py", _AGENTS_STANDIN)+ zf.writestr(f"{_PACKAGE}/aisuite_toolkits/__init__.py", "")+ for src in toolkits:+ zf.write(src, f"{_PACKAGE}/aisuite_toolkits/{src.name}")os.chmod(tmp, 0o644)os.replace(tmp, target)return targetdiff --git a/coworker/sandbox/providers/runner_local.py b/coworker/sandbox/providers/runner_local.pyindex fa828b33..224af972 100644--- a/coworker/sandbox/providers/runner_local.py+++ b/coworker/sandbox/providers/runner_local.py@@ -38,7 +38,7 @@ class RunnerLocalProvider:def create(self) -> None:self._daemon = subprocess.Popen(- [sys.executable, str(self._runner), "serve", "--socket", self.socket_path, "--cwd", self.cwd, "--exit-with-parent"],+ [sys.executable, "-S", str(self._runner), "serve", "--socket", self.socket_path, "--cwd", self.cwd, "--exit-with-parent"],stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,@@ -53,7 +53,7 @@ class RunnerLocalProvider:time.sleep(0.02)def open_runner(self) -> Transport:- argv = [sys.executable, str(self._runner), "attach", "--socket", self.socket_path]+ argv = [sys.executable, "-S", str(self._runner), "attach", "--socket", self.socket_path]if self._relay_silence is not None:argv += ["--silence-seconds", str(self._relay_silence)]return PipeTransport(diff --git a/coworker/sandbox/proxy.py b/coworker/sandbox/proxy.pynew file mode 100644index 00000000..a8c27b0d--- /dev/null+++ b/coworker/sandbox/proxy.py@@ -0,0 +1,63 @@+"""Send a workspace tool's execution to the tool runner, leaving its definition alone.++A proxy has the same name, signature, description, schema and approval metadata as the tool+it stands for, so the registry, the permission engine and the model cannot tell the+difference. Only the call itself goes to the runner, where the same code runs on the other+side of the sandbox wall.+"""++from __future__ import annotations++import builtins+import functools+import inspect+from typing import Any, Callable, Optional++from .runner import protocol as P+from .runner.toolcalls import TOOLS++_TOOL_TIMEOUT = 180.0+++def _reraise(exc: P.RunnerError) -> None:+ """The tool raised inside the runner: raise the same kind of error with the same text."""+ kind = getattr(builtins, str(exc.data.get("type", "")), None)+ if not (isinstance(kind, type) and issubclass(kind, Exception)):+ kind = RuntimeError+ message = exc.message+ if kind is KeyError and len(message) >= 2 and message[0] == message[-1] == "'":+ message = message[1:-1] # str(KeyError("x")) is "'x'"+ raise kind(message) from None+++def proxy_tool(tool: Callable[..., Any], workspace: Any, *, root: str, roots: Optional[list] = None) -> Callable[..., Any]:+ name = getattr(tool, "__name__", "")+ signature = inspect.signature(tool)++ @functools.wraps(tool)+ def call(*args: Any, **kwargs: Any) -> Any:+ bound = signature.bind(*args, **kwargs)+ # The session's roots list is live (folders are granted while a session runs), so+ # it is read on every call, as the in-process tools do.+ live = [{"path": str(r.path), "writable": bool(r.writable)} for r in (roots or [])]+ try:+ result = workspace.client.call(+ "tool.call",+ {"name": name, "args": dict(bound.arguments), "workspace": root, "roots": live or None},+ timeout=_TOOL_TIMEOUT,+ )+ except P.RunnerError as exc:+ if exc.code == P.TOOL_RAISED:+ _reraise(exc)+ raise RuntimeError(f"{name} could not run in the sandbox: {exc.message}") from None+ return result.get("value")++ return call+++def proxy_tools(tools: list, workspace: Any, *, root: str, roots: Optional[list] = None) -> list:+ """Proxies for the tools the runner can execute; any other tool is returned as it is."""+ return [+ proxy_tool(t, workspace, root=root, roots=roots) if getattr(t, "__name__", "") in TOOLS else t+ for t in tools+ ]diff --git a/coworker/sandbox/runner/daemon.py b/coworker/sandbox/runner/daemon.pyindex a0a9be08..d161a3bc 100644--- a/coworker/sandbox/runner/daemon.py+++ b/coworker/sandbox/runner/daemon.py@@ -32,7 +32,7 @@ import uuidfrom pathlib import Pathfrom typing import Any, Callable, Optional-from . import fsops, protocol as P+from . import fsops, protocol as P, toolcallsfrom .executor import LocalExecutorRUNNER_VERSION = "0.1.0"@@ -122,8 +122,8 @@ class Daemon:def _reply(self, req_id: str, value: dict[str, Any]) -> None:self._emit(P.result(req_id, value), record=True)- def _fail(self, req_id: Optional[str], code: int, message: str) -> None:- self._emit(P.error(req_id, code, message), record=req_id is not None)+ def _fail(self, req_id: Optional[str], code: int, message: str, data: Optional[dict] = None) -> None:+ self._emit(P.error(req_id, code, message, data), record=req_id is not None)def _notify(self, method: str, params: dict[str, Any]) -> None:self._emit(P.notification(method, params), record=False)@@ -277,6 +277,16 @@ class Daemon:}if method == "proc.run":return self._proc_run(params)+ if method == "tool.call":+ # One of OpenWorker's own workspace tools, run here with the same code the+ # in-process tool runs. The value goes back as it is (a dict, a list, a string).+ value = toolcalls.call(+ str(params.get("name") or ""),+ dict(params.get("args") or {}),+ workspace=str(params.get("workspace") or self.default_cwd),+ roots=params.get("roots") or None,+ )+ return {"value": value}if method.startswith("fs."):path = self._resolve(params)try:@@ -306,6 +316,8 @@ class Daemon:self._reply(req_id, self._dispatch(req_id, method, params))except P.RunnerError as exc:self._fail(req_id, exc.code, exc.message)+ except toolcalls.ToolRaised as exc:+ self._fail(req_id, P.TOOL_RAISED, str(exc), {"type": exc.type_name})except (ValueError, TypeError) as exc:self._fail(req_id, P.INVALID_PARAMS, str(exc))except Exception as exc: # never let one request take the daemon downdiff --git a/coworker/sandbox/runner/protocol.py b/coworker/sandbox/runner/protocol.pyindex 10de8a06..8b4e214f 100644--- a/coworker/sandbox/runner/protocol.py+++ b/coworker/sandbox/runner/protocol.py@@ -39,6 +39,7 @@ UNKNOWN_TASK = 3FS_ERROR = 4VERSION_MISMATCH = 5RUNNER_RESTARTED = 6 # raised by the client, never sent by the runner+TOOL_RAISED = 7 # a workspace tool raised; data carries the error's type namedef encode(obj: dict[str, Any]) -> bytes:diff --git a/coworker/sandbox/runner/toolcalls.py b/coworker/sandbox/runner/toolcalls.pynew file mode 100644index 00000000..299a1789--- /dev/null+++ b/coworker/sandbox/runner/toolcalls.py@@ -0,0 +1,81 @@+"""Run one of OpenWorker's workspace tools inside the runner. Standard library only.++The tool DEFINITIONS (names, schemas, approval metadata) stay in the OpenWorker process.+When a session uses a sandbox, only the execution moves here: the server sends the tool's+name and arguments, this module runs the same code the in-process tool runs, and the result+goes back unchanged. So a session looks the same to the model in both modes.++The file-editing and git-status tools are aisuite's toolkit classes. They are plain+standard-library code, so the bundler packs the server's own copy of them into the runner+file (`aisuite_toolkits/`); run from a checkout, the installed aisuite is used instead.+"""++from __future__ import annotations++from typing import Any, Optional++from . import tools_git, tools_grep, tools_read++try: # inside the packed runner+ from .aisuite_toolkits.files import FileToolkit+ from .aisuite_toolkits.git import GitToolkit+except ImportError: # from a checkout (tests, development)+ from aisuite.toolkits.files import FileToolkit # type: ignore[no-redef]+ from aisuite.toolkits.git import GitToolkit # type: ignore[no-redef]++# The values `aisuite.toolkits.files()` / `.git()` use when OpenWorker builds these tools.+_MAX_READ_BYTES = 200_000+_MAX_SEARCH_BYTES = 1_000_000+_GIT_MAX_OUTPUT_CHARS = 20000++FILE_TOOLKIT_TOOLS = (+ "list_files",+ "read_file_lines",+ "search_files",+ "write_file",+ "apply_unified_diff",+ "apply_patch",+ "replace_in_file",+)+GIT_TOOLKIT_TOOLS = {"git_status": "status", "git_diff": "diff"}+OWN_TOOLS = ("read_file", "grep", "git_log")+TOOLS = (*FILE_TOOLKIT_TOOLS, *GIT_TOOLKIT_TOOLS, *OWN_TOOLS)+++class ToolRaised(Exception):+ """The tool raised; the server re-raises the same kind of error with the same text."""++ def __init__(self, exc: BaseException) -> None:+ super().__init__(str(exc))+ self.type_name = type(exc).__name__+++def call(+ name: str,+ args: dict[str, Any],+ *,+ workspace: str,+ roots: Optional[list[dict[str, Any]]] = None,+) -> Any:+ """`roots`: the session's folders as [{"path": ..., "writable": bool}], primary first.+ Without it the tools are scoped to `workspace` alone, writable (single-root sessions)."""+ try:+ if name == "read_file":+ extra = [str(r["path"]) for r in (roots or [])]+ return tools_read.read_file(workspace, roots=extra, **args)+ if name == "grep":+ return tools_grep.grep(workspace, **args)+ if name == "git_log":+ return tools_git.git_log(workspace, **args)+ if name in GIT_TOOLKIT_TOOLS:+ kit = GitToolkit(root=workspace, max_output_chars=_GIT_MAX_OUTPUT_CHARS)+ return getattr(kit, GIT_TOOLKIT_TOOLS[name])(**args)+ if name in FILE_TOOLKIT_TOOLS:+ scope = {"roots": roots} if roots else {"root": workspace, "allow_write": True}+ kit = FileToolkit(+ max_read_bytes=_MAX_READ_BYTES, max_search_bytes=_MAX_SEARCH_BYTES, ignore=None, **scope+ )+ return getattr(kit, name)(**args)+ except Exception as exc:+ raise ToolRaised(exc) from exc+ raise ToolRaised(KeyError(f"not a workspace tool: {name}"))diff --git a/tests/test_sandbox_runner.py b/tests/test_sandbox_runner.pyindex 05ffe2dd..ffa98525 100644--- a/tests/test_sandbox_runner.py+++ b/tests/test_sandbox_runner.py@@ -57,6 +57,8 @@ def test_runner_uses_only_the_standard_library():else:continue # relative imports stay inside the packagefor name in names:+ if source.name == "toolcalls.py" and name.startswith("aisuite.toolkits."):+ continue # only when run from a checkout; the packed file carries its own copyassert name.split(".")[0] in allowed, f"{source.name} imports {name}"diff --git a/tests/test_sandbox_tools.py b/tests/test_sandbox_tools.pynew file mode 100644index 00000000..452a7ab5--- /dev/null+++ b/tests/test_sandbox_tools.py@@ -0,0 +1,196 @@+"""Workspace tools in a sandbox: same definitions, same results, execution in the runner.++Every operation here runs twice on twin folders: once with the in-process tools (direct+mode) and once with the proxies that send execution to a tool runner. The answers, the+errors and the files left on disk must match, and what the model is shown about each tool+(name, schema, approval metadata) must be identical.+"""++from __future__ import annotations++import subprocess+import sys+import zipfile+from pathlib import Path++import pytest++pytestmark = pytest.mark.skipif(sys.platform == "win32", reason="the tool runner needs Unix sockets")++from coworker.agents.base import AgentContext # noqa: E402 (before catalog: import order)+from coworker import catalog # noqa: E402, I001+from coworker.roots import RootDir # noqa: E402+from coworker.sandbox.bundle import build_runner_zipapp # noqa: E402+from coworker.sandbox.providers.runner_local import RunnerLocalProvider # noqa: E402+from coworker.sandbox.workspace import RunnerWorkspace # noqa: E402+from coworker.tools import ToolRegistry # noqa: E402++CAPABILITIES = ["code_files", "git", "search"]+++def _seed(folder: Path) -> None:+ (folder / "src").mkdir(parents=True)+ (folder / "src" / "app.py").write_text("def greet():\n return 'hello'\n\n# TODO: say more\n")+ (folder / "src" / "util.py").write_text("VALUE = 1\n# TODO: remove\n")+ (folder / "README.md").write_text("# Demo\n\nSome text.\n")+ (folder / "node_modules").mkdir()+ (folder / "node_modules" / "junk.js").write_text("// TODO: never shown\n")+ for cmd in (["init", "-q"], ["add", "-A"], ["-c", "user.name=T", "-c", "[email protected]", "commit", "-qm", "first"]):+ subprocess.run(["git", "-C", str(folder), *cmd], check=True, capture_output=True)+++def _tree(folder: Path) -> dict[str, str]:+ return {+ str(p.relative_to(folder)): p.read_text(errors="replace")+ for p in sorted(folder.rglob("*"))+ if p.is_file() and ".git" not in p.relative_to(folder).parts+ }+++def twins(tmp_path):+ """(direct tools, runner tools, direct folder, runner folder), both folders seeded alike."""+ direct_dir, runner_dir = tmp_path / "direct" / "ws", tmp_path / "runner" / "ws"+ for folder in (direct_dir, runner_dir):+ folder.mkdir(parents=True)+ _seed(folder)+ direct_ctx = AgentContext(workspace=direct_dir)+ provider = RunnerLocalProvider(cwd=runner_dir, runner_path=build_runner_zipapp(tmp_path / "dist"))+ sandbox = RunnerWorkspace(provider, cwd=runner_dir)+ runner_ctx = AgentContext(workspace=runner_dir, executor=sandbox.executor, sandbox=sandbox)+ direct = {t.__name__: t for t in catalog.expand(CAPABILITIES, direct_ctx)}+ through_runner = {t.__name__: t for t in catalog.expand(CAPABILITIES, runner_ctx)}+ yield direct, through_runner, direct_dir, runner_dir+ sandbox.close()+++def _both(twins, name, *args, **kwargs):+ """Run one tool in both modes. Returns the two outcomes with each folder's own path+ replaced by a placeholder, so they can be compared."""+ direct, through_runner, direct_dir, runner_dir = twins+ outcomes = []+ for tools, folder in ((direct, direct_dir), (through_runner, runner_dir)):+ try:+ outcome = ("ok", tools[name](*args, **kwargs))+ except Exception as exc:+ outcome = ("raised", type(exc).__name__, str(exc))+ outcomes.append(repr(outcome).replace(str(folder.resolve()), "<ws>").replace(str(folder), "<ws>"))+ return outcomes+++def test_the_model_sees_the_same_tools_either_way(twins):+ direct, through_runner, _, _ = twins+ assert sorted(direct) == sorted(through_runner)+ a, b = ToolRegistry(), ToolRegistry()+ a.register_all(list(direct.values()))+ b.register_all(list(through_runner.values()))+ for name in direct:+ assert a.get(name).schema == b.get(name).schema, name+ assert vars(a.get(name).metadata) == vars(b.get(name).metadata), name+++ "name, args, kwargs",+ [+ ("read_file", ("src/app.py",), {}),+ ("read_file", ("src/app.py",), {"start_line": 2, "max_lines": 1}),+ ("read_file", ("missing.py",), {}),+ ("read_file", ("../outside.txt",), {}),+ ("list_files", (), {}),+ ("list_files", ("src",), {"pattern": "*.py", "recursive": False}),+ ("grep", ("TODO",), {}),+ ("grep", ("TODO", "src"), {"glob": "util.*", "max_results": 5}),+ ("grep", ("(unclosed",), {}),+ ("grep", ("x", "../.."), {}),+ ("git_status", (), {}),+ ("git_diff", (), {}),+ ("git_log", (), {"max_count": 5}),+ ("git_log", ("src/app.py",), {}),+ ],+)+def test_reading_tools_answer_alike(twins, name, args, kwargs):+ direct_answer, runner_answer = _both(twins, name, *args, **kwargs)+ if name == "git_log": # commit hashes differ between the twin repositories by design+ import re++ direct_answer, runner_answer = (re.sub(r"'hash': '[0-9a-f]+'", "'hash': '<h>'", x) for x in (direct_answer, runner_answer))+ assert direct_answer == runner_answer+++def test_editing_tools_answer_alike_and_leave_the_same_files(twins):+ _, _, direct_dir, runner_dir = twins+ steps = [+ ("write_file", ("notes/new.md", "one\ntwo\nthree\n"), {}),+ ("write_file", ("notes/new.md", "again\n"), {"overwrite": False}), # refuses+ ("replace_in_file", ("src/app.py", "'hello'", "'hi'"), {}),+ ("replace_in_file", ("src/app.py", "not-there", "x"), {}), # raises+ ("replace_in_file", ("src/util.py", "VALUE", "NUMBER"), {"expected_replacements": 2}), # raises+ (+ "apply_unified_diff",+ ("--- a/README.md\n+++ b/README.md\n@@ -1,3 +1,3 @@\n # Demo\n \n-Some text.\n+Some better text.\n",),+ {},+ ),+ (+ "apply_patch",+ ("*** Begin Patch\n*** Add File: notes/added.txt\n+made by a patch\n*** Delete File: src/util.py\n*** End Patch\n",),+ {},+ ),+ ("write_file", ("../escape.txt", "no"), {}), # outside the session's folders+ ("git_status", (), {}),+ ("git_diff", ("README.md",), {}),+ ]+ for name, args, kwargs in steps:+ direct_answer, runner_answer = _both(twins, name, *args, **kwargs)+ assert direct_answer == runner_answer, name+ assert _tree(direct_dir) == _tree(runner_dir)+ assert "Some better text." in (runner_dir / "README.md").read_text()+ assert not (runner_dir / "src" / "util.py").exists()+ assert not (runner_dir.parent / "escape.txt").exists()+++def test_a_folder_granted_later_is_seen_at_once_and_read_only_is_kept(tmp_path):+ """The session's roots list is live: a folder added while the session runs must work+ on the next call, and a read-only folder must refuse writes, exactly as in direct mode."""+ primary, extra = tmp_path / "scratch", tmp_path / "granted"+ primary.mkdir()+ extra.mkdir()+ (extra / "ref.txt").write_text("reference\n")+ roots = [RootDir(path=primary, writable=True)]+ provider = RunnerLocalProvider(cwd=primary, runner_path=build_runner_zipapp(tmp_path / "dist"))+ sandbox = RunnerWorkspace(provider, cwd=primary)+ try:+ ctx = AgentContext(workspace=primary, executor=sandbox.executor, roots=roots, sandbox=sandbox)+ tools = {t.__name__: t for t in catalog.expand(["files"], ctx)}+ assert "error" in tools["read_file"](str(extra / "ref.txt")) # not granted yet+ roots.append(RootDir(path=extra, writable=False))+ assert "reference" in tools["read_file"](str(extra / "ref.txt"))["content"]+ with pytest.raises(PermissionError):+ tools["write_file"](str(extra / "new.txt"), "nope")+ tools["write_file"]("mine.txt", "fine")+ assert (primary / "mine.txt").read_text() == "fine"+ finally:+ sandbox.close()+++def test_direct_mode_uses_the_tools_untouched(tmp_path):+ (tmp_path / "f.txt").write_text("x\n")+ plain = catalog.expand(CAPABILITIES, AgentContext(workspace=tmp_path))+ assert not any(hasattr(t, "__wrapped__") for t in plain) # no proxy in the way+++def test_the_packed_runner_carries_the_toolkits_and_needs_no_site_packages(tmp_path):+ zipapp = build_runner_zipapp(tmp_path)+ with zipfile.ZipFile(zipapp) as zf:+ names = set(zf.namelist())+ assert {"owrunner/aisuite_toolkits/files.py", "owrunner/aisuite_toolkits/git.py", "owrunner/agents.py"} <= names+ probe = (+ "import sys; sys.path.insert(0, sys.argv[1]);"+ "from owrunner import toolcalls;"+ "assert toolcalls.FileToolkit.__module__.startswith('owrunner.'), toolcalls.FileToolkit.__module__;"+ "print(toolcalls.call('list_files', {}, workspace=sys.argv[2]))"+ )+ (tmp_path / "ws").mkdir()+ (tmp_path / "ws" / "a.txt").write_text("a")+ done = subprocess.run([sys.executable, "-S", "-c", probe, str(zipapp), str(tmp_path / "ws")], capture_output=True, text=True)+ assert done.returncode == 0, done.stderr+ assert done.stdout.strip() == "['a.txt']"