"""Tools with declared arguments, and the base class for coding tasks.""" import random from dataclasses import dataclass, field from pathlib import Path from typing import Callable from . import runner TYPE_NAMES = {str: "string", int: "integer", float: "number", dict: "object", list: "array"} READ_LINES = 200 @dataclass class Tool: name: str help: str fn: Callable[[dict], str] args: dict[str, type] = field(default_factory=dict) optional: tuple[str, ...] = () final: bool = False def signature(self) -> str: parts = [f'"{k}": {TYPE_NAMES[t]}' + (" (optional)" if k in self.optional else "") for k, t in self.args.items()] return "{" + ", ".join(parts) + "}" def check(self, args: dict) -> str | None: unknown = sorted(set(args) - set(self.args)) if unknown: return f"Unknown argument(s) {unknown} for {self.name}. It takes {self.signature()}." missing = [k for k in self.args if k not in args and k not in self.optional] if missing: return f"Missing argument(s) {missing} for {self.name}. It takes {self.signature()}." for k, t in self.args.items(): if k in args and not (isinstance(args[k], t) and not (t is int and isinstance(args[k], bool))): return f"Argument {k!r} of {self.name} must be a {TYPE_NAMES[t]}." return None class CodingTask: """One generated instance with its own workspace directory. Subclasses implement setup(), brief(), grade().""" family = "" domain = "" levels = (1, 2) max_steps = 30 def __init__(self, rng: random.Random, level: int, group: str = "", **opts): self.rng, self.level, self.group, self.opts = rng, level, group, opts self.ws = runner.new_workspace() try: self.setup() runner.give_to_nobody(self.ws) except BaseException: self.close() raise def close(self): runner.remove(self.ws) # -- to implement -------------------------------------------------------------------------------- def setup(self): raise NotImplementedError def brief(self) -> str: raise NotImplementedError def grade(self, args: dict) -> float: raise NotImplementedError def oracle(self): """Change the workspace into a correct solution (used by tests).""" raise NotImplementedError # -- shared tools -------------------------------------------------------------------------------- def _path(self, rel: str) -> Path | None: rel = str(rel).strip() p = (self.ws / rel.lstrip("/")).resolve() if not rel.startswith(str(self.ws)) else Path(rel).resolve() ws = self.ws.resolve() return p if p == ws or ws in p.parents else None def coding_tools(self, tests: bool = True) -> list[Tool]: tools = [ Tool("list_files", "list files under a directory of the repository (the root if omitted)", self._ls, {"path": str}, optional=("path",)), Tool("read_file", f"show a file with line numbers (lines start-end, at most {READ_LINES} at a time)", self._read, {"path": str, "start": int, "end": int}, optional=("start", "end")), Tool("search", "search the repository for a regular expression (grep -rn)", self._search, {"pattern": str, "path": str}, optional=("path",)), Tool("edit_file", "replace an exact snippet of a file with new text (the snippet must occur once)", self._edit, {"path": str, "old": str, "new": str}), Tool("write_file", "create or overwrite a whole file", self._write, {"path": str, "content": str}), Tool("run", "run a shell command in the repository root (60 s limit), e.g. python -c '...'", self._run, {"command": str}), ] if tests: tools.append(Tool("run_tests", "run pytest on a test file or directory (the whole suite if omitted; " "100 s limit)", self._tests, {"target": str}, optional=("target",))) return tools def _ls(self, a): p = self._path(a.get("path", ".")) if p is None or not p.is_dir(): return f"No directory {a.get('path')!r}." rows = [] for q in sorted(p.rglob("*")): rel = q.relative_to(self.ws).as_posix() if any(part.startswith(".") or part == "__pycache__" for part in rel.split("/")): continue if q.is_file(): rows.append(rel) return "\n".join(rows[:300]) + (f"\n... {len(rows) - 300} more" if len(rows) > 300 else "") or "(empty)" def _read(self, a): p = self._path(a["path"]) if p is None or not p.is_file(): return f"No file {a['path']!r}." lines = p.read_text(errors="replace").split("\n") start = max(1, a.get("start", 1)) end = min(len(lines), a.get("end", start + READ_LINES - 1), start + READ_LINES - 1) body = "\n".join(f"{i:5d} {lines[i - 1]}" for i in range(start, end + 1)) more = f"\n[lines {start}-{end} of {len(lines)}]" if end < len(lines) or start > 1 else "" return body + more def _search(self, a): if not a["pattern"]: return "pattern is empty" p = self._path(a.get("path", ".")) if p is None: return "path is outside the repository" import shlex code, out = runner.run(f"grep -rnE --exclude-dir=__pycache__ -- {shlex.quote(a['pattern'])} " f"{shlex.quote(str(p))} | head -60", self.ws, timeout=20) return out.replace(str(self.ws) + "/", "") or "no matches" def _edit(self, a): p = self._path(a["path"]) if p is None or not p.is_file(): return f"No file {a['path']!r}." text = p.read_text(errors="replace") n = text.count(a["old"]) if a["old"] else 0 if n != 1: return f"The snippet occurs {n} times in {a['path']}; it must occur exactly once (include more context)." p.write_text(text.replace(a["old"], a["new"])) return f"Edited {a['path']}." def _write(self, a): p = self._path(a["path"]) if p is None or p == self.ws.resolve(): return "path must be a file inside the repository" p.parent.mkdir(parents=True, exist_ok=True) p.write_text(a["content"]) runner.give_to_nobody(p.parent) return f"Wrote {len(a['content'])} characters to {a['path']}." def _run(self, a): if not a["command"].strip(): return "command is empty" code, out = runner.run(a["command"], self.ws, timeout=60) return f"exit code {code}\n" + runner.trim(out.replace(str(self.ws) + "/", "")) def _tests(self, a): import shlex target = a.get("target", "").strip() code, out = runner.run("python -m pytest -q -p no:cacheprovider --tb=short -x --hypothesis-seed=0 " + (shlex.quote(target) if target else ""), self.ws, timeout=100) return f"exit code {code}\n" + runner.trim(out.replace(str(self.ws) + "/", ""))