"""Small deterministic tools: calculator, file lookup, sandboxed code runner. Each tool has a strict input/output schema and a `run` method the agent can call. """ from __future__ import annotations import os import re import subprocess import sys import tempfile def _flatten(obj): if isinstance(obj, dict): return {str(k): _flatten(v) for k, v in obj.items()} if isinstance(obj, (list, tuple)): return [_flatten(v) for v in obj] return obj class Tool: name: str description: str schema: dict # {"inputs": {...}, "outputs": {...}} def run(self, **kwargs): raise NotImplementedError class Calculator(Tool): name = "calculator" description = "Evaluate a math expression to a number." schema = {"inputs": {"expr": "string"}, "outputs": {"result": "number"}} def run(self, expr: str): expr = expr.strip() # Only allow numbers, decimals, +, -, *, /, parentheses, and whitespace. if not re.fullmatch(r"[0-9+\-*/().\s]+", expr): raise ValueError("bad expression") return {"result": eval(expr, {"__builtins__": {}}, {})} class FileLookup(Tool): name = "file_lookup" description = "Read a text file or list a directory on the device." schema = {"inputs": {"path": "string", "mode": "'read'|'list'"}, "outputs": {"content": "string"}} def run(self, path: str, mode: str = "read"): if mode == "list": try: return {"content": "\n".join(sorted(os.listdir(path)))} except OSError as e: return {"content": f"error: {e}"} if mode != "read": raise ValueError("mode must be read or list") try: with open(path, encoding="utf-8", errors="replace") as f: return {"content": f.read()} except OSError as e: return {"content": f"error: {e}"} class SandboxRun(Tool): name = "sandbox" description = "Run a short Python snippet in a tight sandbox." schema = {"inputs": {"code": "string"}, "outputs": {"result": "string"}} def run(self, code: str): with tempfile.TemporaryDirectory() as td: src = os.path.join(td, "prog.py") with open(src, "w", encoding="utf-8") as f: f.write(code) try: p = subprocess.run( [sys.executable, src], capture_output=True, text=True, timeout=5, cwd=td, env={**os.environ, "PYTHONNOUSERSITE": "1"}, ) return {"result": (p.stdout or p.stderr or "").strip()[-800:]} except subprocess.TimeoutExpired: return {"result": "timed out"} import sys # noqa: E402 (after use of sys in SandboxRun)