Python
List folders as well as files in list_files (OPE-203)
Devika Vermaf9413810e7a0
diff --git a/coworker/catalog.py b/coworker/catalog.pyindex 8d246312..d109b41c 100644--- a/coworker/catalog.py+++ b/coworker/catalog.py@@ -110,12 +110,13 @@ def _placed(context: AgentContext, tools: list) -> list: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`.+ `read_file` replace aisuite's slower `search_files` / `read_file`/`read_file_lines`,+ and our folder-aware `list_files` replaces the toolkit's files-only one (OPE-203).Multi-root aware (universal scratch): with session roots, writes/reads reach thescratch and granted dirs too; the workspace stays the relative-path anchor."""ws = str(context.workspace)- replaced = {"search_files", "read_file", "read_file_lines"}+ replaced = {"search_files", "read_file", "read_file_lines", "list_files"}file_kwargs = ({"roots": context.roots} if context.roots else {"root": ws, "allow_write": True})@@ -132,14 +133,15 @@ def _code_files(context: AgentContext) -> list:def _files(context: AgentContext) -> list:"""Knowledge-work files: multi-root aware (reads/writes across the session's roots).One reader everywhere (owner ruling 2026-08-20): the windowed, line-numbered- `read_file` replaces aisuite's `read_file`/`read_file_lines`, and our `grep`- replaces the slow `search_files` — same set Code uses.+ `read_file` replaces aisuite's `read_file`/`read_file_lines`, our `grep`+ replaces the slow `search_files`, and our folder-aware `list_files` replaces the+ toolkit's files-only one (OPE-203) — same set Code uses."""ws = str(context.workspace)file_kwargs = ({"roots": context.roots} if context.roots else {"root": ws, "allow_write": True})- replaced = {"search_files", "read_file", "read_file_lines"}+ replaced = {"search_files", "read_file", "read_file_lines", "list_files"}files = _describe_edit_tools([tdiff --git a/coworker/sandbox/runner/toolcalls.py b/coworker/sandbox/runner/toolcalls.pyindex 299a1789..efde7035 100644--- a/coworker/sandbox/runner/toolcalls.py+++ b/coworker/sandbox/runner/toolcalls.py@@ -29,7 +29,6 @@ _MAX_SEARCH_BYTES = 1_000_000_GIT_MAX_OUTPUT_CHARS = 20000FILE_TOOLKIT_TOOLS = (- "list_files","read_file_lines","search_files","write_file",@@ -38,7 +37,7 @@ FILE_TOOLKIT_TOOLS = ("replace_in_file",)GIT_TOOLKIT_TOOLS = {"git_status": "status", "git_diff": "diff"}-OWN_TOOLS = ("read_file", "grep", "git_log")+OWN_TOOLS = ("read_file", "list_files", "grep", "git_log")TOOLS = (*FILE_TOOLKIT_TOOLS, *GIT_TOOLKIT_TOOLS, *OWN_TOOLS)@@ -63,6 +62,9 @@ def call(if name == "read_file":extra = [str(r["path"]) for r in (roots or [])]return tools_read.read_file(workspace, roots=extra, **args)+ if name == "list_files":+ extra = [str(r["path"]) for r in (roots or [])]+ return tools_read.list_files(workspace, roots=extra, **args)if name == "grep":return tools_grep.grep(workspace, **args)if name == "git_log":diff --git a/coworker/sandbox/runner/tools_read.py b/coworker/sandbox/runner/tools_read.pyindex 660a47e2..b97adb0f 100644--- a/coworker/sandbox/runner/tools_read.py+++ b/coworker/sandbox/runner/tools_read.py@@ -1,7 +1,10 @@-"""The logic of the `read_file` tool. Standard library only (it also runs inside a sandbox).+"""The logic of the `read_file` and `list_files` tools. Standard library only (it also runs+inside a sandbox).-Returns `cat -n`-style numbered lines, windows big files instead of failing, and tells the-agent how to continue reading. Read-only, scoped to the session's folders.+`read_file` returns `cat -n`-style numbered lines, windows big files instead of failing, and+tells the agent how to continue reading. `list_files` lists folders as well as files (folders+end with '/'), so a workspace whose top level holds nothing but a subfolder never lists as+empty (OPE-203). Both read-only, scoped to the session's folders."""from __future__ import annotations@@ -11,6 +14,71 @@ from typing import Any, Optional, Sequence_DEFAULT_MAX_LINES = 2000_MAX_LINE_CHARS = 500+_DEFAULT_MAX_RESULTS = 100+_MAX_RESULTS_CAP = 2000+# The same skip-list the aisuite file toolkit uses (copied: this module must stay+# standard-library only), so every listing hides the same folders.+_IGNORED_DIRS = (+ ".git", ".venv", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache",+ "node_modules", "dist", "build",+)+++def _home_for(target: Path, root: Path, extra_roots: Sequence[Path]) -> Optional[Path]:+ for r in (root, *extra_roots):+ try:+ target.relative_to(r)+ return r+ except ValueError:+ continue+ return None+++def list_files(+ workspace: str,+ path: str = ".",+ pattern: str = "*",+ recursive: bool = True,+ max_results: int = _DEFAULT_MAX_RESULTS,+ roots: Optional[Sequence[str]] = None,+) -> Any:+ """Files and folders under `path`, folders marked with a trailing '/', sorted. Paths+ inside the workspace come back relative to it; paths inside another of the session's+ `roots` come back absolute."""+ root = Path(workspace).resolve()+ extra_roots = [Path(str(r)).resolve() for r in (roots or [])]+ n = (+ max_results+ if isinstance(max_results, int) and max_results > 0+ else _DEFAULT_MAX_RESULTS+ )+ n = min(n, _MAX_RESULTS_CAP)+ p = Path(str(path or ".")).expanduser()+ base = p.resolve() if p.is_absolute() else (root / p).resolve()+ home = _home_for(base, root, extra_roots)+ if home is None:+ return {"error": "path escapes the session's directories"}+ if not base.is_dir():+ return {"error": f"not a directory: {path}"}++ results: list[str] = []+ try:+ iterator = base.rglob(pattern or "*") if recursive else base.glob(pattern or "*")+ for item in iterator:+ if any(part in _IGNORED_DIRS for part in item.relative_to(home).parts):+ continue+ shown = item.relative_to(root).as_posix() if home == root else str(item)+ if item.is_dir():+ results.append(shown + "/")+ elif item.is_file():+ results.append(shown)+ else:+ continue+ if len(results) >= n:+ break+ except OSError as exc:+ return {"error": f"list failed: {exc}"}+ return sorted(results)def read_file(diff --git a/coworker/tools/files.py b/coworker/tools/files.pyindex 7cde1ce6..d68ee32f 100644--- a/coworker/tools/files.py+++ b/coworker/tools/files.py@@ -1,9 +1,15 @@-"""Line-numbered file reading (`read_file`) — replaces the aisuite toolkit's reader.+"""Line-numbered file reading (`read_file`) and folder-aware listing (`list_files`) —+both replace the aisuite toolkit's versions.The toolkit's `read_file` returns raw text (the agent can't cite path:line withoutcounting) and raises outright on large files (the agent errors and guesses). This onereturns `cat -n`-style numbered lines, windows big files instead of failing, and tellsthe agent how to continue reading. Read-only, workspace-scoped.++The toolkit's `list_files` returns files only, so a workspace whose top level holds+nothing but a subfolder lists as `[]` and the agent concludes it is empty (OPE-203). This+one lists folders too, marked with a trailing `/`, so one non-recursive look shows the+shape of the tree. Both tools are read-only and scoped to the session's roots."""from __future__ import annotations@@ -13,7 +19,11 @@ from typing import Any, Optionalimport aisuite as aifrom ..sandbox.runner import tools_read as _impl-from ..sandbox.runner.tools_read import _DEFAULT_MAX_LINES, _MAX_LINE_CHARS # noqa: F401+from ..sandbox.runner.tools_read import ( # noqa: F401+ _DEFAULT_MAX_LINES,+ _DEFAULT_MAX_RESULTS,+ _MAX_LINE_CHARS,+)_SCHEMA = {"type": "function",@@ -45,17 +55,51 @@ _SCHEMA = {},}+_LIST_SCHEMA = {+ "type": "function",+ "function": {+ "name": "list_files",+ "description": (+ "List files and folders under a path; folders end with '/'. Use "+ "recursive=false to see one level, and pattern (a glob such as '*.py') to "+ "filter by name. Read-only."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string",+ "description": "Folder to list, relative to the workspace (default '.').",+ },+ "pattern": {+ "type": "string",+ "description": "Glob to match names against (default '*').",+ },+ "recursive": {+ "type": "boolean",+ "description": "Descend into subfolders (default true).",+ },+ "max_results": {+ "type": "integer",+ "description": f"Stop after this many entries (default {_DEFAULT_MAX_RESULTS}).",+ },+ },+ "required": [],+ },+ },+}+def file_tools(workspace: str, roots: Optional[list] = None) -> list:- """Windowed read_file rooted at `workspace`. With `roots` (RootDir list), absolute- paths inside ANY root also resolve — multi-root sessions (universal scratch) address- their scratch/extra dirs by the absolute paths the roots context advertises."""+ """Windowed read_file and folder-aware list_files rooted at `workspace`. With `roots`+ (RootDir list), absolute paths inside ANY root also resolve — multi-root sessions+ (universal scratch) address their scratch/extra dirs by the absolute paths the roots+ context advertises."""def read_file(path: str,start_line: int = 1,max_lines: int = _DEFAULT_MAX_LINES,) -> dict[str, Any]:- # `roots` is the session's live list: read it on every call.return _impl.read_file(workspace, path, start_line, max_lines, roots=[str(r.path) for r in (roots or [])])@@ -70,4 +114,26 @@ def file_tools(workspace: str, roots: Optional[list] = None) -> list:requires_approval=False,)read_file.__coworker_schema__ = _SCHEMA- return [read_file]++ def list_files(+ path: str = ".",+ pattern: str = "*",+ recursive: bool = True,+ max_results: int = _DEFAULT_MAX_RESULTS,+ ) -> Any:+ return _impl.list_files(+ workspace, path, pattern, recursive, max_results,+ roots=[str(r.path) for r in (roots or [])],+ )++ list_files.__name__ = "list_files"+ list_files.__doc__ = _LIST_SCHEMA["function"]["description"]+ list_files.__aisuite_tool_metadata__ = ai.ToolMetadata(+ name="list_files",+ category="filesystem",+ risk_level="low",+ capabilities=["list_files"],+ requires_approval=False,+ )+ list_files.__coworker_schema__ = _LIST_SCHEMA+ return [read_file, list_files]diff --git a/coworker/tools/subagent.py b/coworker/tools/subagent.pyindex 17744f77..2b0f98de 100644--- a/coworker/tools/subagent.py+++ b/coworker/tools/subagent.py@@ -52,7 +52,7 @@ def build_explorer_engine(registry = ToolRegistry()# Read-only slice of the Code agent's toolset, with the same toolkit replacements# (our grep for search_files, our windowed read_file for read_file/read_file_lines).- replaced = {"search_files", "read_file", "read_file_lines"}+ replaced = {"search_files", "read_file", "read_file_lines", "list_files"}registry.register_all([tdiff --git a/tests/test_list_files_folders.py b/tests/test_list_files_folders.pynew file mode 100644index 00000000..b05e4653--- /dev/null+++ b/tests/test_list_files_folders.py@@ -0,0 +1,83 @@+"""`list_files` shows folders as well as files (OPE-203).++The aisuite toolkit's listing returns files only, so a workspace whose top level holds+nothing but a subfolder lists as `[]` and the agent concludes the workspace is empty.+Ours lists folders too, marked with a trailing `/`.+"""++from __future__ import annotations++from coworker.agents.base import AgentContext+from coworker.catalog import expand+from coworker.tools.files import file_tools+from coworker.tools.todo import TodoList+++def _list_files(ws):+ return {t.__name__: t for t in file_tools(str(ws))}["list_files"]+++def _site(tmp_path):+ site = tmp_path / "personal-site"+ (site / "_includes").mkdir(parents=True)+ (site / "index.html").write_text("<h1>hi</h1>", encoding="utf-8")+ (site / "_includes" / "about.md").write_text("me", encoding="utf-8")+ return site+++def test_a_workspace_of_subfolders_is_not_reported_empty(tmp_path):+ _site(tmp_path)+ assert _list_files(tmp_path)(path=".", recursive=False) == ["personal-site/"]+++def test_recursive_listing_shows_folders_and_files(tmp_path):+ _site(tmp_path)+ assert _list_files(tmp_path)(path=".", recursive=True) == [+ "personal-site/",+ "personal-site/_includes/",+ "personal-site/_includes/about.md",+ "personal-site/index.html",+ ]+++def test_pattern_and_subpath_apply(tmp_path):+ _site(tmp_path)+ tool = _list_files(tmp_path)+ assert tool(path="personal-site", pattern="*.html", recursive=False) == [+ "personal-site/index.html"+ ]+ assert tool(path="personal-site", recursive=False) == [+ "personal-site/_includes/",+ "personal-site/index.html",+ ]+++def test_ignored_folders_stay_hidden(tmp_path):+ _site(tmp_path)+ (tmp_path / ".git" / "objects").mkdir(parents=True)+ (tmp_path / ".git" / "HEAD").write_text("ref", encoding="utf-8")+ (tmp_path / "node_modules" / "left-pad").mkdir(parents=True)+ listed = _list_files(tmp_path)(path=".", recursive=True)+ assert not any(entry.startswith((".git", "node_modules")) for entry in listed)+ assert "personal-site/" in listed+++def test_max_results_caps_the_listing(tmp_path):+ for i in range(5):+ (tmp_path / f"f{i}.txt").write_text("x", encoding="utf-8")+ assert len(_list_files(tmp_path)(path=".", max_results=3)) == 3+++def test_paths_outside_the_session_are_refused(tmp_path):+ tool = _list_files(tmp_path / "ws")+ (tmp_path / "ws").mkdir()+ assert "error" in tool(path="..")+ assert "error" in tool(path="missing")+++def test_catalog_registers_the_folder_aware_listing(tmp_path):+ ctx = AgentContext(workspace=tmp_path, executor=object(), todo=TodoList())+ for capability in ("code_files", "files"):+ listings = [t for t in expand([capability], ctx) if t.__name__ == "list_files"]+ assert len(listings) == 1, capability+ assert hasattr(listings[0], "__coworker_schema__"), capability