# Purpose: CPU bypass for python code execution (sandbox, no LLM/GPU) from __future__ import annotations import ast import io import re import sys import time import traceback from contextlib import redirect_stdout, redirect_stderr from typing import Optional CODE_PREFIXES = ("/py", "/python", "/code", "/run") BLOCK_RE = re.compile(r"```(?:python)?\s*(.*?)\s*```", re.DOTALL | re.IGNORECASE) # blocked imports / calls BLOCKED_NAMES = { "os", "sys", "subprocess", "socket", "shutil", "pathlib", "open", "eval", "exec", "compile", "__import__", "input", "exit", "quit", } BLOCKED_ATTRS = {"system", "popen", "remove", "rmdir", "unlink", "write", "call"} MAX_OUTPUT = 4000 TIMEOUT_SEC = 3 # soft, we check elapsed during exec via timeout logic def _extract_code(message: str) -> tuple[str, bool]: """Extract code from message. Returns (code, had_prefix).""" s = message.strip() low = s.lower() for p in CODE_PREFIXES: if low.startswith(p): body = s[len(p):].strip(" :\n") # if body wrapped in ```, extract m = BLOCK_RE.search(body) if m: body = m.group(1) return body.strip(), True # check for ```python block without prefix m = BLOCK_RE.search(s) if m: code = m.group(1).strip() # only treat as code if it looks like python (has def/class/import/print/for) if re.search(r"\b(def|class|import|print|for|while|if|return)\b", code): return code, True return s, False def should_bypass_llm(message: str) -> bool: if not message or not message.strip(): return False low = message.strip().lower() for p in CODE_PREFIXES: if low.startswith(p): return True if BLOCK_RE.search(message): code, _ = _extract_code(message) if code and len(code) < 2000: return True return False def _is_safe(node: ast.AST) -> tuple[bool, str]: """Basic AST safety check. Returns (ok, reason).""" for n in ast.walk(node): if isinstance(n, ast.Import): for alias in n.names: if alias.name.split(".")[0] in BLOCKED_NAMES: return False, f"blocked import {alias.name}" elif isinstance(n, ast.ImportFrom): if n.module and n.module.split(".")[0] in BLOCKED_NAMES: return False, f"blocked import from {n.module}" elif isinstance(n, ast.Call): # check for open(), eval(), etc. if isinstance(n.func, ast.Name) and n.func.id in BLOCKED_NAMES: return False, f"blocked call {n.func.id}" if isinstance(n.func, ast.Attribute) and n.func.attr in BLOCKED_ATTRS: return False, f"blocked attr {n.func.attr}" elif isinstance(n, ast.Attribute): if n.attr in {"__subclasses__", "__bases__", "__mro__"}: return False, "blocked dunder" return True, "" def solve(query: str) -> str: """Execute python code and return output. Never raises.""" code, had_prefix = _extract_code(query) if not code: return "code: empty" # if query was prefix-like but code empty, try original if len(code) > 3000: return "code: too long (max 3000 chars)" # safety check via AST try: tree = ast.parse(code) except SyntaxError as e: return f"code SyntaxError: {e}" ok, reason = _is_safe(tree) if not ok: return f"code blocked: {reason} (sandbox)" # prepare sandbox globals safe_builtins = { "print": print, "len": len, "range": range, "enumerate": enumerate, "zip": zip, "map": map, "filter": filter, "sorted": sorted, "sum": sum, "min": min, "max": max, "abs": abs, "round": round, "pow": pow, "divmod": divmod, "int": int, "float": float, "str": str, "bool": bool, "list": list, "dict": dict, "set": set, "tuple": tuple, "any": any, "all": all, "math": __import__("math"), "random": __import__("random"), "datetime": __import__("datetime"), "re": __import__("re"), "json": __import__("json"), "collections": __import__("collections"), "itertools": __import__("itertools"), } # provide sympy/z3 if available but not required try: import sympy safe_builtins["sympy"] = sympy except Exception: pass out_buf = io.StringIO() err_buf = io.StringIO() start = time.time() try: with redirect_stdout(out_buf), redirect_stderr(err_buf): # exec with timeout check via simple elapsed # need to handle both expression and statements # try eval for single expression try: # if single expression, eval and print if len(tree.body) == 1 and isinstance(tree.body[0], ast.Expr): val = eval(compile(ast.Expression(tree.body[0].value), "", "eval"), {"__builtins__": safe_builtins}, {}) if val is not None: print(repr(val)) else: exec(compile(tree, "", "exec"), {"__builtins__": safe_builtins}, {}) except Exception: raise if time.time() - start > TIMEOUT_SEC: return "code timeout (>3s)" except Exception: tb = traceback.format_exc() # truncate if len(tb) > MAX_OUTPUT: tb = tb[:MAX_OUTPUT] + "\n... truncated" return f"code error:\n{tb}" out = out_buf.getvalue() err = err_buf.getvalue() combined = (out + ("\n[stderr]\n" + err if err else "")).strip() if not combined: combined = "(no output)" if len(combined) > MAX_OUTPUT: combined = combined[:MAX_OUTPUT] + "\n... truncated" elapsed = time.time() - start return f"🐍 [py · CPU bypass · {elapsed:.3f}s]\n{combined}" def try_solve(message: str) -> Optional[str]: if not should_bypass_llm(message): return None if len(message) > 8000: return None res = solve(message) # if blocked or error, still return (don't fallback to LLM) if prefix was explicit _, had_prefix = _extract_code(message) if had_prefix: return res # for block without prefix, only return if success if "blocked" in res or "SyntaxError" in res: return None return res