Download scripts/star/eval/_tools.py from pourasrp/star_v1: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/datasets/pourasrp/star_v1/resolve/main/scripts/star/eval/_tools.py
- Command line
-
hf download hf://datasets/pourasrp/star_v1/scripts/star/eval/_tools.py
-
curl -L -o _tools.py https://huggingface.co/datasets/pourasrp/star_v1/resolve/main/scripts/star/eval/_tools.py
16.9 kB
| """Execution environments and the four tools (execute_bash, str_replace_editor, think, finish) of the Tier-1 loop. | |
| Tool names, parameter names and observation wording follow the SWE-Lego / OpenHands trajectories the frozen | |
| detector was built on: an observation is a USER message `EXECUTION RESULT of [tool]:\\n<body>`; bash bodies end with | |
| `[The command completed with exit code N.]` + cwd + interpreter lines; tool rejections start with `ERROR:`. | |
| Strings marked (seen) were checked against the local labelling trajectories; (reconstructed) were not. | |
| Three environments: DockerEnv (a per-task swebench image; needs a Docker daemon), ChrootEnv (the same image unpacked and | |
| run via chroot, for Docker-less Jarvis containers; Path A) and LocalEnv (a plain directory; tests). | |
| """ | |
| from __future__ import annotations | |
| import subprocess | |
| import uuid | |
| from pathlib import Path | |
| from typing import Any | |
| import _common as C | |
| NOCALL_MSG = ("No function call was found in your last message. Reply with exactly one call in the format " | |
| "<function=NAME><parameter=KEY>VALUE</parameter></function>.") # harness rejection (own wording) | |
| REJECTION_TEMPLATES = { # every harness-authored rejection string, for the T1 ratification list | |
| "no_call": NOCALL_MSG, | |
| "unknown_tool": "Unknown function '{name}'. Available functions: execute_bash, str_replace_editor, think, finish.", | |
| "missing_param": "Parameter `{param}` is required for function {name}.", | |
| "bad_command": "Unrecognized command `{cmd}`. The allowed commands for the str_replace_editor tool are: view, create, str_replace, insert, undo_edit.", | |
| "no_replace_missing": "No replacement was performed, old_str `{old}` did not appear verbatim in {path}.", # (seen) | |
| "no_replace_multi": "No replacement was performed. Multiple occurrences of old_str `{old}` in lines {lines}. Please ensure it is unique.", # (seen) | |
| "bad_range": "Invalid `view_range` parameter: {rng}. Its first element `{a}` should be within the range of lines of the file: [1, {n}].", # (seen, simplified) | |
| "path_missing": "The path {path} does not exist. Please provide a valid path.", # (reconstructed) | |
| "exists": "File already exists at: {path}. Cannot overwrite files using command `create`.", # (reconstructed) | |
| } | |
| def err(msg: str) -> str: | |
| return "ERROR:\n" + msg | |
| def clip(s: str, n: int = C.OBS_MAX_CHARS) -> str: | |
| return s if len(s) <= n else s[: n // 2] + "\n<response clipped>\n" + s[-(n // 2):] | |
| def wrap(tool: str, body: str) -> str: | |
| return f"EXECUTION RESULT of [{tool}]:\n{body}" | |
| class Env: | |
| """exec(cmd, timeout) -> (output, rc); read/write file text; cwd attribute.""" | |
| cwd: str | |
| def exec(self, cmd: str, timeout: int) -> tuple[str, int]: | |
| raise NotImplementedError | |
| def read(self, path: str) -> str | None: | |
| raise NotImplementedError | |
| def write(self, path: str, text: str) -> None: | |
| raise NotImplementedError | |
| def list_dir(self, path: str) -> str | None: | |
| """`find path -maxdepth 2` excluding hidden entries, sorted; None if not a directory.""" | |
| out, rc = self.exec(f"test -d '{path}' && find '{path}' -maxdepth 2 -not -path '*/.*' | sort", 60) | |
| return out if rc == 0 and out.strip() else None | |
| def close(self) -> None: | |
| pass | |
| def final_patch(self, base_commit: str, exclude: list[str]) -> str: | |
| ex = " ".join(f'":(exclude){p}"' for p in exclude) | |
| out, rc = self.exec(f"git add -A -- . {ex} && git diff --cached --no-color {base_commit}", 120) | |
| return out if rc == 0 else "" | |
| class LocalEnv(Env): | |
| """Tests only: commands run through the host shell in `workdir`; files are read/written natively.""" | |
| def __init__(self, workdir: str): | |
| self.cwd = workdir | |
| def exec(self, cmd, timeout): | |
| try: | |
| r = subprocess.run(cmd, shell=True, cwd=self.cwd, capture_output=True, text=True, timeout=timeout) | |
| return (r.stdout + r.stderr), r.returncode | |
| except subprocess.TimeoutExpired: | |
| return f"[The command timed out after {timeout} seconds.]", -1 | |
| def read(self, path): | |
| try: | |
| return Path(path).read_text(encoding="utf-8") | |
| except OSError: | |
| return None | |
| def list_dir(self, path): | |
| import os | |
| if not os.path.isdir(path): | |
| return None | |
| out = [] | |
| for root, dirs, files in os.walk(path): | |
| dirs[:] = sorted(d for d in dirs if not d.startswith(".")) | |
| if root[len(path):].count(os.sep) >= 2: | |
| dirs[:] = [] | |
| out += [root.replace(os.sep, "/")] + [(root + "/" + f).replace(os.sep, "/") for f in sorted(files) if not f.startswith(".")] | |
| return "\n".join(sorted(out)) + "\n" | |
| def write(self, path, text): | |
| import os | |
| os.makedirs(os.path.dirname(path) or ".", exist_ok=True) | |
| with open(path, "w", encoding="utf-8", newline="") as fh: | |
| fh.write(text) | |
| class DockerEnv(Env): | |
| """One container per task from the public swebench instance image; no network (the agent must not be able to | |
| fetch the upstream fix). The shell is stateless between calls except for the working directory, which is | |
| tracked with a sentinel (a limitation vs OpenHands' persistent shell: exported variables do not persist).""" | |
| def __init__(self, instance_id: str, tag: str = ""): | |
| self.image = C.swebench_image(instance_id) | |
| self.name = f"star-{tag}-{uuid.uuid4().hex[:8]}" | |
| self.cwd = C.REPO_DIR | |
| subprocess.run(["docker", "run", "-d", "--rm", "--network", "none", "--name", self.name, "-w", C.REPO_DIR, | |
| self.image, "sleep", "infinity"], check=True, capture_output=True, timeout=1800) | |
| def exec(self, cmd, timeout): | |
| script = f'cd "{self.cwd}" 2>/dev/null; {C.CONDA_ACTIVATE}{{\n{cmd}\n}}; __rc=$?; echo "__STAR_CWD__=$(pwd)"; exit $__rc' | |
| try: | |
| r = subprocess.run(["docker", "exec", self.name, "bash", "-c", script], capture_output=True, text=True, | |
| errors="replace", timeout=timeout) | |
| except subprocess.TimeoutExpired: | |
| subprocess.run(["docker", "exec", self.name, "pkill", "-f", "bash -c"], capture_output=True) | |
| return f"[The command timed out after {timeout} seconds.]", -1 | |
| out, keep = r.stdout, [] | |
| for line in out.splitlines(): | |
| if line.startswith("__STAR_CWD__="): | |
| self.cwd = line.split("=", 1)[1] or self.cwd | |
| else: | |
| keep.append(line) | |
| return "\n".join(keep) + ("\n" if keep else "") + r.stderr, r.returncode | |
| def read(self, path): | |
| r = subprocess.run(["docker", "exec", self.name, "cat", path], capture_output=True, timeout=120) | |
| return r.stdout.decode("utf-8", "replace") if r.returncode == 0 else None | |
| def write(self, path, text): | |
| subprocess.run(["docker", "exec", "-i", self.name, "bash", "-c", f'mkdir -p "$(dirname "{path}")" && cat > "{path}"'], | |
| input=text.encode(), check=True, capture_output=True, timeout=120) | |
| def close(self): | |
| subprocess.run(["docker", "rm", "-f", self.name], capture_output=True, timeout=120) | |
| class ChrootEnv(Env): | |
| """Docker-less per-task environment (Path A, plan.md 2026-10-10): the swebench image's layers are unpacked into a | |
| fresh rootfs on the LOCAL disk, every command runs through `chroot --userspec=1000:1000` (non-root: a root process | |
| in a chroot can escape to the host filesystem, verified), the shell is stateless except for the cwd (same sentinel | |
| as DockerEnv) and conda `testbed` is activated exactly as DockerEnv does (C.CONDA_ACTIVATE). | |
| NO NETWORK NAMESPACE (not possible here): /etc/resolv.conf and conda/pip config are removed, proxy/index | |
| environment is never passed, and every command matching chroot_runtime.NET_AUDIT_RE (pip|conda|curl|wget|git clone) | |
| is appended (not blocked) to `audit_path` (<id>.net_audit.jsonl). read()/write() go through the chroot too, so a | |
| symlink planted by the agent cannot redirect a host-side file operation. close() deletes the rootfs.""" | |
| def __init__(self, instance_id: str, tag: str = "", store=None, work_root=None, audit_path=None, dns: bool = False): | |
| import threading | |
| import chroot_runtime as CR | |
| self.CR, self.instance_id, self.tag = CR, instance_id, tag | |
| self.audit_path, self._lock = audit_path, threading.Lock() | |
| self.cwd = C.REPO_DIR | |
| m = CR.materialize(instance_id, store or CR.DEFAULT_STORE, work_root or CR.DEFAULT_WORK_ROOT, dns=dns) | |
| self.rootfs, self.env, self.timings = m["rootfs"], m["env"], {"unpack_s": m["unpack_s"], "layers_s": m["layers_s"]} | |
| self.removed_net_config = m["removed_net_config"] | |
| self._closed = False | |
| def _audit(self, cmd: str) -> None: | |
| if self.CR.NET_AUDIT_RE.search(cmd): | |
| self.CR.audit_write(self.audit_path, self._lock, {"utc": C.now_utc(), "instance_id": self.instance_id, | |
| "tag": self.tag, "command": cmd[:4000]}) | |
| def exec(self, cmd, timeout): | |
| self._audit(cmd) | |
| script = f'cd "{self.cwd}" 2>/dev/null; {C.CONDA_ACTIVATE}{{\n{cmd}\n}}; __rc=$?; echo "__STAR_CWD__=$(pwd)"; exit $__rc' | |
| out_b, err_b, rc, timed_out = self.CR.run_in_chroot(self.rootfs, ["bash", "-c", script], self.env, timeout) | |
| if timed_out: | |
| return f"[The command timed out after {timeout} seconds.]", -1 | |
| keep = [] | |
| for line in out_b.decode("utf-8", "replace").splitlines(): | |
| if line.startswith("__STAR_CWD__="): | |
| self.cwd = line.split("=", 1)[1] or self.cwd | |
| else: | |
| keep.append(line) | |
| return "\n".join(keep) + ("\n" if keep else "") + err_b.decode("utf-8", "replace"), rc | |
| def read(self, path): | |
| out, _err, rc, _to = self.CR.run_in_chroot(self.rootfs, ["cat", "--", path], self.env, 120) | |
| return out.decode("utf-8", "replace") if rc == 0 else None | |
| def write(self, path, text): | |
| _o, err, rc, _to = self.CR.run_in_chroot(self.rootfs, ["bash", "-c", 'mkdir -p "$(dirname "$1")" && cat > "$1"', "_", path], | |
| self.env, 120, stdin=text.encode()) | |
| if rc != 0: | |
| raise RuntimeError(f"chroot write {path} failed rc={rc}: {err.decode('utf-8', 'replace')[:300]}") | |
| def close(self): | |
| if not self._closed: | |
| self._closed = True | |
| self.timings["delete_s"] = self.CR.delete_rootfs(self.rootfs) | |
| # ----------------------------------------------------------------------------- the tools | |
| def numbered(text: str, start: int = 1) -> str: | |
| return "\n".join(f"{i:6}\t{l}" for i, l in enumerate(text.split("\n"), start)) | |
| class Tools: | |
| def __init__(self, env: Env): | |
| self.env, self.history = env, {} | |
| def run(self, name: str, p: dict[str, str]) -> tuple[str, str]: | |
| """-> (observation message content, kind) with kind in ok|rejection|finish.""" | |
| if name == "finish": | |
| return "", "finish" | |
| if name == "think": | |
| return wrap("think", "Your thought has been logged."), "ok" | |
| if name == "execute_bash": | |
| return self.bash(p) | |
| if name == "str_replace_editor": | |
| return self.editor(p) | |
| return wrap("none", err(REJECTION_TEMPLATES["unknown_tool"].format(name=name))), "rejection" | |
| def bash(self, p): | |
| if "command" not in p: | |
| return wrap("execute_bash", err(REJECTION_TEMPLATES["missing_param"].format(param="command", name="execute_bash"))), "rejection" | |
| if p.get("is_input", "false").lower() == "true": | |
| return wrap("execute_bash", err("is_input is not supported by this harness.")), "rejection" | |
| try: | |
| t = max(1, min(int(float(p.get("timeout", C.CMD_TIMEOUT_DEFAULT))), C.CMD_TIMEOUT_MAX)) | |
| except ValueError: | |
| t = C.CMD_TIMEOUT_DEFAULT | |
| out, rc = self.env.exec(p["command"], t) | |
| body = clip(out.rstrip("\n")) | |
| foot = (f"[The command completed with exit code {rc}.]" if rc != -1 else "[The command timed out.]") | |
| return wrap("execute_bash", f"{body}\n{foot}\n[Current working directory: {self.env.cwd}]\n" | |
| f"[Python interpreter: {C.PY_INTERP}]\n[Command finished with exit code {rc}]"), "ok" | |
| def editor(self, p): | |
| T = "str_replace_editor" | |
| cmd, path = p.get("command"), p.get("path") | |
| R = lambda m: (wrap(T, err(m)), "rejection") | |
| for k in ("command", "path"): | |
| if k not in p: | |
| return R(REJECTION_TEMPLATES["missing_param"].format(param=k, name=T)) | |
| if cmd not in ("view", "create", "str_replace", "insert", "undo_edit"): | |
| return R(REJECTION_TEMPLATES["bad_command"].format(cmd=cmd)) | |
| if cmd == "view": | |
| out = self.env.list_dir(path) | |
| if out is not None: | |
| return wrap(T, f"Here's the files and directories up to 2 levels deep in {path}, excluding hidden items:\n{clip(out.rstrip())}"), "ok" | |
| text = self.env.read(path) | |
| if text is None: | |
| return R(REJECTION_TEMPLATES["path_missing"].format(path=path)) | |
| lines, a = text.split("\n"), 1 | |
| if "view_range" in p: | |
| try: | |
| a, b = [int(x) for x in p["view_range"].strip("[] ").split(",")] | |
| except ValueError: | |
| return R(REJECTION_TEMPLATES["bad_range"].format(rng=p["view_range"], a="?", n=len(lines))) | |
| if not 1 <= a <= len(lines): | |
| return R(REJECTION_TEMPLATES["bad_range"].format(rng=p["view_range"], a=a, n=len(lines))) | |
| lines = lines[a - 1: (len(lines) if b == -1 else b)] | |
| return wrap(T, f"Here's the result of running `cat -n` on {path}:\n{clip(numbered(chr(10).join(lines), a))}"), "ok" | |
| cur = self.env.read(path) | |
| if cmd == "create": | |
| if "file_text" not in p: | |
| return R(REJECTION_TEMPLATES["missing_param"].format(param="file_text", name=T)) | |
| if cur is not None: | |
| return R(REJECTION_TEMPLATES["exists"].format(path=path)) | |
| self.env.write(path, p["file_text"]) | |
| self.history[path] = None | |
| return wrap(T, f"File created successfully at: {path}"), "ok" | |
| if cur is None: | |
| return R(REJECTION_TEMPLATES["path_missing"].format(path=path)) | |
| if cmd == "undo_edit": | |
| if self.history.get(path) is None: | |
| return R(f"No edit history found for {path}.") | |
| self.env.write(path, self.history.pop(path)) | |
| return wrap(T, f"Last edit to {path} undone successfully."), "ok" | |
| if cmd == "str_replace": | |
| if "old_str" not in p: | |
| return R(REJECTION_TEMPLATES["missing_param"].format(param="old_str", name=T)) | |
| old, new = p["old_str"], p.get("new_str", "") | |
| n = cur.count(old) | |
| if n == 0: | |
| return R(REJECTION_TEMPLATES["no_replace_missing"].format(old=old, path=path)) | |
| if n > 1: | |
| lines = [cur[:i].count("\n") + 1 for i in range(len(cur)) if cur.startswith(old, i)] | |
| return R(REJECTION_TEMPLATES["no_replace_multi"].format(old=old, lines=lines)) | |
| at = cur.index(old) | |
| res, where = cur.replace(old, new), cur[:at].count("\n") | |
| else: # insert | |
| for k in ("insert_line", "new_str"): | |
| if k not in p: | |
| return R(REJECTION_TEMPLATES["missing_param"].format(param=k, name=T)) | |
| try: | |
| il = int(p["insert_line"]) | |
| except ValueError: | |
| return R(f"Invalid `insert_line` parameter: {p['insert_line']}.") | |
| ls = cur.split("\n") | |
| if not 0 <= il <= len(ls): | |
| return R(f"Invalid `insert_line` parameter: {il}. It should be within the range of lines of the file: [0, {len(ls)}]") | |
| res, where = "\n".join(ls[:il] + p["new_str"].split("\n") + ls[il:]), il | |
| self.history[path] = cur | |
| self.env.write(path, res) | |
| snip = "\n".join(res.split("\n")[max(0, where - 4): where + 4 + p.get("new_str", "").count("\n")]) | |
| return wrap(T, f"The file {path} has been edited. Here's the result of running `cat -n` on a snippet of {path}:\n" | |
| f"{clip(numbered(snip, max(1, where - 3)))}\nReview the changes and make sure they are as expected. Edit the file again if necessary."), "ok" | |