Python
run: a folder request is asked in the terminal and yes gives the folder
Rohit C Prasad6e0d58199a39
diff --git a/coworker/headless/runner.py b/coworker/headless/runner.pyindex 349f81d2..7a920b15 100644--- a/coworker/headless/runner.py+++ b/coworker/headless/runner.py@@ -853,6 +853,22 @@ def _run(args: argparse.Namespace) -> int:if terminal is not None:engine.cards_reach_person = lambda: Trueengine.is_attended = lambda: True++ def grant_folder(folder: Path, writable: bool) -> Path:+ """The person gave the coworker another folder. The engine's list of folders is+ shared with the file tools, the permission checks and the sandbox, so they all+ see it from the next call."""+ from ..basedir import ensure_under_base++ resolved = ensure_under_base(folder, "folder")+ for root in engine.roots:+ if root.path == resolved:+ root.writable = bool(writable) or root.writable+ return resolved+ engine.roots.append(RootDir(path=resolved, writable=bool(writable)))+ return resolved++ terminal.grant_folder = grant_folderif sites:if engine.permissions.sandbox_sites is None:print(diff --git a/coworker/headless/terminal.py b/coworker/headless/terminal.pyindex a2127a9b..03d58a13 100644--- a/coworker/headless/terminal.py+++ b/coworker/headless/terminal.py@@ -13,6 +13,9 @@ approvals with the person.The network card has no "always": a run reads this computer's allowed sites and neverchanges them.++Folder requests and pinned tool installs are asked the same way; they go with the+questions, so `--auto-answer` answers them by rule too."""from __future__ import annotations@@ -100,6 +103,9 @@ class Terminal:# about to be asked. It carries what the request alone does not: the network# request's sites and whether the sandbox blocked them.self.card: dict[str, Any] = {}+ # Adds a folder to the running session and returns its resolved path; raises with+ # the reason when it cannot. Set by the run once the engine exists.+ self.grant_folder: Optional[Callable[[Path, bool], Path]] = Noneself._lock = asyncio.Lock()@classmethod@@ -273,25 +279,55 @@ class Terminal:# -- folders and tool installs --------------------------------------------------------async def directory(self, args: dict[str, Any], _call_id: Optional[str] = None) -> dict[str, Any]:- """The engine's folder-request hook. A run's folders are fixed when it starts- (`--workspace`, `--add-dir`), so the person is told what was asked for and the- coworker is told to work with what it has."""+ """The engine's folder-request hook: the coworker asks for another folder, to read+ or to read and write. The person says yes, yes but read only, no, or types a+ different folder. `grant_folder` (set by the run) adds it to the session."""async with self._lock:- path = str(args.get("path") or "").strip()+ asked = str(args.get("path") or "").strip()+ writable = bool(args.get("writable", False))reason = str(args.get("reason") or "").strip()- lines = ["", "The coworker asked for a folder" + (f": {_home_relative(path)}" if path else "") + "."]+ access = "to read and write" if writable else "to read"+ lines = ["", f"The coworker asks for a folder {access}" + (f": {_home_relative(asked)}" if asked else "")]if reason:lines.append(f" Reason: {_short(reason, 200)}")- lines.append(" A run's folders are set when it starts. To give this one, run again with --add-dir.")+ if asked:+ keys = "[y] yes " + ("[r] yes, read only " if writable else "") + "[n] no"+ lines.append(f" {keys} or type another folder")+ else:+ lines.append(" Type the folder, or n for no")self._say(*lines)- return {- "granted": False,- "error": (- "This run's folders were set when it started and cannot be added to now. Work "- "inside the current workspace. If the task cannot continue without that folder, "- "stop and say which folder is needed, so the user can start the run again with it."- ),- }+ while True:+ typed = await self._prompt()+ if typed is None:+ return {"granted": False, "reason": "the user declined the request"}+ text = typed.strip()+ choice = text.lower()+ if not text:+ continue+ if choice in ("n", "no"):+ return {"granted": False, "reason": "the user declined the request"}+ path, grant_writable = asked, writable+ if choice in ("y", "yes") and asked:+ pass+ elif choice in ("r", "read", "read only") and asked and writable:+ grant_writable = False+ elif choice in ("y", "yes", "r"):+ self._say(" Type the folder, or n for no.")+ continue+ else:+ path = text+ folder = Path(path).expanduser()+ if not folder.is_dir():+ self._say(f" {_home_relative(str(folder))} is not a folder. Type another, or n for no.")+ continue+ if self.grant_folder is None:+ return {"granted": False, "error": "directory requests aren't available here"}+ try:+ granted = self.grant_folder(folder, grant_writable)+ except Exception as exc: # noqa: BLE001 - say why, and let the person choose again+ self._say(f" That folder cannot be given: {exc}. Type another, or n for no.")+ continue+ return {"granted": True, "path": str(granted), "writable": grant_writable}async def tool(self, args: dict[str, Any], _call_id: Optional[str] = None) -> dict[str, Any]:"""The engine's tool-install hook: only reached for a tool in the pinned catalog,diff --git a/docs/headless.md b/docs/headless.mdindex 1264c385..d5ddeb7d 100644--- a/docs/headless.md+++ b/docs/headless.md@@ -102,9 +102,10 @@ or `--approval-mode bypass-approvals`.`--auto-answer` does not touch approvals: at a terminal they are still asked.-Two other requests go with the questions. A pinned tool install is asked at a terminal and-installed by rule otherwise. A request for another folder is declined: a run's folders are-set when it starts, with `--workspace` and `--add-dir`.+Two other requests go with the questions. A request for another folder, to read or to+write, is asked at a terminal: yes, yes but read only, no, or a different folder; with+`--auto-answer` or no terminal it is declined by rule. A pinned tool install is asked at a+terminal and installed by rule otherwise.### Optionsdiff --git a/tests/test_run_cli.py b/tests/test_run_cli.pyindex c7ec5083..467d1778 100644--- a/tests/test_run_cli.py+++ b/tests/test_run_cli.py@@ -287,11 +287,46 @@ def test_grouped_questions_are_asked_in_turn_and_keyed_by_header() -> None:assert got == {"answers": {"Regions": "EU, US", "How often?": "weekly"}}-def test_a_folder_request_tells_the_person_and_is_declined() -> None:- keys = _Keys()- got = asyncio.run(keys.terminal().directory({"path": "/data/exports", "reason": "the report reads last month's exports"}))- assert got["granted"] is False and "cannot be added to now" in got["error"]- assert "The coworker asked for a folder: /data/exports." in keys.printed and "--add-dir" in keys.printed+def test_a_folder_request_is_asked_and_yes_gives_the_folder(tmp_path: Path) -> None:+ exports = tmp_path / "exports"+ exports.mkdir()+ given: list[tuple[Path, bool]] = []++ def terminal(keys: _Keys) -> Terminal:+ term = keys.terminal()+ term.grant_folder = lambda folder, writable: given.append((folder, writable)) or folder.resolve()+ return term++ request = {"path": str(exports), "writable": True, "reason": "the report reads last month's exports"}+ keys = _Keys("y")+ got = asyncio.run(terminal(keys).directory(dict(request)))+ assert got == {"granted": True, "path": str(exports.resolve()), "writable": True}+ assert f"The coworker asks for a folder to read and write: {exports}" in keys.printed+ assert "Reason: the report reads last month's exports" in keys.printed+ assert "[y] yes [r] yes, read only [n] no or type another folder" in keys.printed++ # Read only, although it asked to write.+ assert asyncio.run(terminal(_Keys("r")).directory(dict(request)))["writable"] is False+ # A different folder, typed; one that does not exist is asked again.+ other = tmp_path / "other"+ other.mkdir()+ keys = _Keys(str(tmp_path / "missing"), str(other))+ assert asyncio.run(terminal(keys).directory(dict(request)))["path"] == str(other.resolve())+ assert "is not a folder" in keys.printed+ assert given == [(exports, True), (exports, False), (other, True)]++ # No, and a closed terminal, both decline and give nothing.+ for keys in (_Keys("n"), _Keys()):+ assert asyncio.run(terminal(keys).directory(dict(request))) == {"granted": False, "reason": "the user declined the request"}+ assert len(given) == 3++ # A read request has no read-only choice; a request with no path asks for one.+ keys = _Keys("n")+ asyncio.run(terminal(keys).directory({"path": str(exports)}))+ assert "to read:" in keys.printed and "[r]" not in keys.printed+ keys = _Keys("y", str(exports))+ assert asyncio.run(terminal(keys).directory({"reason": "needs the data"}))["granted"] is True+ assert "Type the folder, or n for no" in keys.printeddef test_a_tool_install_is_asked_and_yes_installs_the_pinned_build(monkeypatch: pytest.MonkeyPatch) -> None:@@ -446,3 +481,39 @@ def test_ctrl_c_at_a_prompt_ends_the_run_and_leaves_the_record(tmp_path: Path) -(folder,) = _session_folders(machine, ws)assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["outcome"] == "interrupted"+++FOLDER_THEN_WRITE = [+ {"text": "", "tool_calls": [{"name": "request_directory", "arguments": {"path": "EXPORTS", "writable": True, "reason": "to save the report there"}}]},+ {"text": "", "tool_calls": [{"name": "write_file", "arguments": {"path": "EXPORTS/report.txt", "content": "done"}}]},+ {"text": "Saved."},+]+++def _folder_script(exports: Path) -> list[dict]:+ return json.loads(json.dumps(FOLDER_THEN_WRITE).replace("EXPORTS", str(exports)))++[email protected](sys.platform == "win32", reason="needs a pseudo-terminal")+def test_at_a_terminal_a_folder_request_is_asked_and_the_folder_can_then_be_written(tmp_path: Path) -> None:+ exports = tmp_path / "exports"+ exports.mkdir()+ code, shown, _out, _ws = _at_a_terminal(+ tmp_path, _folder_script(exports), [("The coworker asks for a folder", "y")], "--approval-mode", "bypass-approvals",+ )+ assert code == 0, shown+ assert "to save the report there" in shown+ assert (exports / "report.txt").read_text(encoding="utf-8") == "done"+++def test_with_auto_answer_a_folder_request_is_declined_by_rule(tmp_path: Path) -> None:+ exports = tmp_path / "exports"+ exports.mkdir()+ proc, ws, machine = _run(+ tmp_path, _folder_script(exports), "--model", "anthropic/claude-sonnet-5", "--approval-mode", "bypass-approvals", "--auto-answer",+ )+ assert proc.returncode == 0, proc.stderr+ assert not (exports / "report.txt").exists()+ (folder,) = _session_folders(machine, ws)+ assert json.loads((folder / "summary.json").read_text(encoding="utf-8"))["answers"]["directory_requests_declined"] == 1+