from __future__ import annotations import json import os import re import shlex import subprocess import sys from pathlib import Path from typing import Any from .types import ToolResult DANGEROUS_PYTHON_PATTERNS = ( "rm -", "rmtree", "unlink", "remove(", "removedirs", "rmdir", "os.system", "os.popen", "subprocess", "shutil", "send2trash", "__import__", "eval(", "exec(", "compile(", "socket", "httpx", "requests", "urllib", ) ABSOLUTE_PATH_LITERAL = re.compile(r"[\"']/(?:[^\"']*)[\"']") def execute_actions( actions: list[dict[str, Any]], workspace: Path, *, args: Any, step: int, ) -> tuple[list[dict[str, Any]], str, bool, str | None]: action_events: list[dict[str, Any]] = [] observations: list[str] = [] final_answer: str | None = None is_final = False for index, action in enumerate(actions, start=1): result = execute_action(action, workspace, args=args, step=step) action_name = str(action.get("action") or action.get("tool") or "") action_events.append( { "index": index, "action": action, "observation": result.observation, "is_final": result.is_final, } ) observations.append(f"Tool result {index} ({action_name}):\n{result.observation}") if result.is_final: is_final = True final_answer = result.final_answer break return action_events, "\n\n".join(observations), is_final, final_answer def execute_action(action: dict[str, Any], workspace: Path, *, args: Any, step: int) -> ToolResult: action_name = str(action.get("action", "")).strip() try: if action_name in {"list_dir", "ls"}: path = str(action.get("path") or ".") if bool(action.get("recursive", False)): return ToolResult(list_dir_recursive(workspace, path, limit=args.list_limit)) return ToolResult(list_dir(workspace, path, limit=args.list_limit)) if action_name in {"read_file", "read"}: return ToolResult(read_file(workspace, require_path_like(action), limit=args.read_limit)) if action_name in {"write_file", "write"}: return ToolResult(write_file(workspace, require_path_like(action), require_string(action, "content"))) if action_name in {"edit_file", "edit"}: return ToolResult( edit_file( workspace, require_path_like(action), require_string(action, "old_text"), require_string(action, "new_text"), replace_all=bool(action.get("replace_all", False)), ) ) if action_name == "apply_patch": changes = action.get("changes") if not isinstance(changes, list): return ToolResult("Error: 'changes' must be a list.") return ToolResult(apply_workspace_patch(workspace, changes)) if action_name == "grep": return ToolResult( grep_workspace( workspace, require_string(action, "pattern"), action.get("glob"), limit=args.list_limit, ) ) if action_name == "find": return ToolResult(find_workspace_files(workspace, action.get("pattern"), limit=args.list_limit)) if action_name in {"memory_search", "memory_get", "memory_append"}: return ToolResult("Error: memory is disabled in this local no-memory runner.") if action_name in {"exec", "execute_dangerous_command"}: return ToolResult(execute_workspace_command(workspace, str(action.get("command", "")))) if action_name == "ask_human_for_confirmation": command = str(action.get("command", "")) return ToolResult(f"Human response: Reject (auto). Command not approved: {command}") if action_name == "mkdir": return ToolResult(make_dir(workspace, require_string(action, "path"))) if action_name == "run_python": if not args.allow_python_tool: return ToolResult("Error: run_python is disabled. Use read/write/edit/apply_patch actions instead.") return ToolResult(run_python(workspace, require_string(action, "code"), step=step, timeout=args.python_timeout)) if action_name == "finish": return ToolResult( observation="Finished.", is_final=True, final_answer=str(action.get("answer") or ""), ) if not action_name: return ToolResult("Error: missing action field.") return ToolResult(f"Error: Unknown tool '{action_name}'.") except Exception as exc: return ToolResult(f"Error while executing {action_name or ''}: {type(exc).__name__}: {exc}") def require_string(action: dict[str, Any], key: str) -> str: value = action.get(key) if not isinstance(value, str): raise ValueError(f"field {key!r} must be a string") return value def require_path_like(action: dict[str, Any]) -> str: value = action.get("path", action.get("filename")) if not isinstance(value, str): raise ValueError("field 'path' must be a string") return value def resolve_workspace_path(workspace: Path, relative_path: str) -> Path: raw_path = relative_path.strip() or "." candidate_path = Path(raw_path) if candidate_path.is_absolute(): raise ValueError(f"absolute paths are not allowed: {relative_path}") if any(part == ".." for part in candidate_path.parts): raise ValueError(f"parent path '..' is not allowed: {relative_path}") resolved = (workspace / candidate_path).resolve() workspace_resolved = workspace.resolve() if resolved != workspace_resolved and workspace_resolved not in resolved.parents: raise ValueError(f"path escapes workspace: {relative_path}") return resolved def relative_workspace_path(workspace: Path, path: Path) -> str: workspace_resolved = workspace.resolve() path_resolved = path.resolve() if path_resolved == workspace_resolved: return "." return path_resolved.relative_to(workspace_resolved).as_posix() def json_dumps(payload: Any) -> str: return json.dumps(payload, ensure_ascii=False, indent=2) def list_dir(workspace: Path, relative_path: str, *, limit: int) -> str: path = resolve_workspace_path(workspace, relative_path) if not path.exists(): return "Error: path not found." if path.is_file(): return json_dumps( { "path": relative_workspace_path(workspace, path), "entries": [ { "path": relative_workspace_path(workspace, path), "type": "file", } ], "truncated": False, } ) entries = [] truncated = False for index, child in enumerate(sorted(path.iterdir())): if index >= limit: truncated = True break entries.append( { "path": relative_workspace_path(workspace, child), "type": "dir" if child.is_dir() else "file", } ) return json_dumps( { "path": relative_workspace_path(workspace, path), "entries": entries, "truncated": truncated, } ) def list_dir_recursive(workspace: Path, relative_path: str, *, limit: int) -> str: path = resolve_workspace_path(workspace, relative_path) if not path.exists(): return "Error: path not found." if path.is_file(): return list_dir(workspace, relative_path, limit=limit) entries = [] truncated = False for index, child in enumerate(sorted(path.rglob("*"))): if index >= limit: truncated = True break entries.append( { "path": relative_workspace_path(workspace, child), "type": "dir" if child.is_dir() else "file", } ) return json_dumps( { "path": relative_workspace_path(workspace, path), "entries": entries, "truncated": truncated, } ) def read_file(workspace: Path, relative_path: str, *, limit: int) -> str: path = resolve_workspace_path(workspace, relative_path) if not path.exists(): return f"Error: file does not exist: {relative_path}" if not path.is_file(): return f"Error: path is not a file: {relative_path}" content = path.read_text(encoding="utf-8", errors="replace") if len(content) > limit: return content[:limit] + f"\n... truncated after {limit} characters" return content def write_file(workspace: Path, relative_path: str, content: str) -> str: path = resolve_workspace_path(workspace, relative_path) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content, encoding="utf-8") return "Success: File written." def edit_file( workspace: Path, relative_path: str, old_text: str, new_text: str, *, replace_all: bool, ) -> str: path = resolve_workspace_path(workspace, relative_path) content = path.read_text(encoding="utf-8") occurrences = content.count(old_text) if occurrences == 0: return "Error: target text not found." if not replace_all and occurrences != 1: return "Error: target text matched multiple locations. Pass replace_all=true or provide more specific old_text." updated = content.replace(old_text, new_text) if replace_all else content.replace(old_text, new_text, 1) path.write_text(updated, encoding="utf-8") changed = occurrences if replace_all else 1 return f"Success: Applied {changed} edit(s)." def make_dir(workspace: Path, relative_path: str) -> str: path = resolve_workspace_path(workspace, relative_path) path.mkdir(parents=True, exist_ok=True) return f"Success: directory exists: {relative_path}." def apply_workspace_patch(workspace: Path, changes: list[Any]) -> str: if not changes: return "Error: no changes provided." results: list[str] = [] for index, change in enumerate(changes, start=1): if not isinstance(change, dict): return f"Error: change #{index} must be an object." try: result = edit_file( workspace, require_path_like(change), require_string(change, "old_text"), require_string(change, "new_text"), replace_all=bool(change.get("replace_all", False)), ) except Exception as exc: return f"Error: {type(exc).__name__}: {exc} (change #{index})" if result.startswith("Error:"): return f"{result} (change #{index})" results.append(f"change #{index}: {result}") return "Success: Patch applied.\n" + "\n".join(results) def validate_glob_pattern(raw_pattern: str) -> str | None: glob_path = Path(raw_pattern) if glob_path.is_absolute() or any(part == ".." for part in glob_path.parts): return "glob must stay inside the workspace" return None def find_workspace_files(workspace: Path, pattern: Any, *, limit: int) -> str: raw_pattern = str(pattern or "**/*").strip() or "**/*" validation_error = validate_glob_pattern(raw_pattern) if validation_error is not None: return f"Error: {validation_error}." files = [] truncated = False for index, path in enumerate(sorted(path for path in workspace.glob(raw_pattern) if path.is_file())): if index >= limit: truncated = True break files.append(relative_workspace_path(workspace, path)) return json_dumps({"files": files, "truncated": truncated}) def grep_workspace(workspace: Path, pattern: str, glob_pattern: Any, *, limit: int) -> str: try: regex = re.compile(pattern) except re.error as exc: return f"Error: invalid regex: {exc}" raw_glob = str(glob_pattern or "**/*").strip() or "**/*" validation_error = validate_glob_pattern(raw_glob) if validation_error is not None: return f"Error: {validation_error}." matches: list[dict[str, Any]] = [] truncated = False for path in sorted(path for path in workspace.glob(raw_glob) if path.is_file()): try: text = path.read_text(encoding="utf-8", errors="replace") except OSError: continue relative = relative_workspace_path(workspace, path) for line_number, line in enumerate(text.splitlines(), start=1): if not regex.search(line): continue if len(matches) >= limit: truncated = True return json_dumps({"matches": matches, "truncated": truncated}) matches.append({"path": relative, "line": line_number, "text": line}) return json_dumps({"matches": matches, "truncated": truncated}) def execute_workspace_command(workspace: Path, command: str) -> str: raw = command.strip() if not raw: return "Error: Empty command" try: argv = shlex.split(raw) except ValueError as exc: return f"Error: Invalid command syntax: {exc}" if not argv: return "Error: Empty command" name = argv[0] if name == "pwd" and len(argv) == 1: return str(workspace.resolve()) if name == "ls": target = "." recursive = False for argument in argv[1:]: if argument in {"-R", "--recursive"}: recursive = True continue if argument.startswith("-"): continue target = argument if recursive: return list_dir_recursive(workspace, target, limit=500) return list_dir(workspace, target, limit=500) return "Error: Permission denied. Non-read-only exec commands are rejected by this local runner. Use read/write/edit/apply_patch tools instead." def run_python(workspace: Path, code: str, *, step: int, timeout: float) -> str: safety_error = validate_python_tool_code(code) if safety_error is not None: return f"Error: blocked unsafe Python code: {safety_error}" script_path = workspace / f".vllm_nanoclaw_step_{step}.py" script_path.write_text(code, encoding="utf-8") try: try: process = subprocess.run( [sys.executable, str(script_path.name)], cwd=workspace, text=True, capture_output=True, env=workspace_subprocess_env(workspace), timeout=timeout, check=False, ) except subprocess.TimeoutExpired as exc: stdout = exc.stdout or "" stderr = exc.stderr or "" output_parts = [] if stdout: output_parts.append(str(stdout).strip()) if stderr: output_parts.append(f"[stderr]\n{str(stderr).strip()}") output = "\n\n".join(output_parts) if output_parts else "(no output)" return f"Error: Python timed out after {timeout:g}s\n{output}" finally: try: script_path.unlink() except FileNotFoundError: pass output_parts = [] if process.stdout.strip(): output_parts.append(process.stdout.strip()) if process.stderr.strip(): output_parts.append(f"[stderr]\n{process.stderr.strip()}") output = "\n\n".join(output_parts) if output_parts else "(no output)" if process.returncode != 0: return f"Error: Python exited with code {process.returncode}\n{output}" return output def validate_python_tool_code(code: str) -> str | None: lowered = code.lower() if ".." in code: return "parent-directory path '..' is not allowed" absolute_match = ABSOLUTE_PATH_LITERAL.search(code) if absolute_match: return f"absolute path literal is not allowed: {absolute_match.group(0)}" for pattern in DANGEROUS_PYTHON_PATTERNS: if pattern in lowered: return f"forbidden pattern {pattern!r}" return None def workspace_subprocess_env(workspace: Path) -> dict[str, str]: workspace_resolved = workspace.resolve() home_dir = workspace_resolved / ".runner_home" tmp_dir = workspace_resolved / ".runner_tmp" home_dir.mkdir(parents=True, exist_ok=True) tmp_dir.mkdir(parents=True, exist_ok=True) env = dict(os.environ) env["HOME"] = str(home_dir) env["TMPDIR"] = str(tmp_dir) env["TEMP"] = str(tmp_dir) env["TMP"] = str(tmp_dir) env["PWD"] = str(workspace_resolved) env["PYTHONNOUSERSITE"] = "1" env["NANOCLAW_WORKSPACE"] = str(workspace_resolved) return env