Skip to content

hylo.codeagents.sandbox

Package: hylo-code-agents · Core contracts

sandbox

A restricted namespace for model-written Python (RFC-0006: "programs are data until gated").

Every block is parsed and checked against an allow-list before it runs
  • imports: only math and numpy (and numpy.linalg / random / fft)
  • no names or attributes that start with an underscore (no dunders, no private toolkit state)
  • no open / exec / eval / compile / globals / getattr / ... (they are not in the builtins either)
  • no frame, generator or code-object internals, no numpy file I/O
  • no class definitions, no async code

Builtins are a small allow-list; print writes to a buffer the agent returns to the model. The namespace persists between blocks (one per episode or research session). Each block has a wall-clock limit that excludes the time the robot spends executing (paused(), used around Executor.run): on expiry an exception is raised inside the running thread (CPython async exception), so a busy loop stops; a call stuck inside C code stops when it returns.

This is a guard against mistakes and casual escapes by a model, not an OS-level jail: run untrusted models in a container as well. Memory use is not limited.

MAX_SOURCE_CHARS module-attribute

MAX_SOURCE_CHARS = 40000

ALLOWED_IMPORTS module-attribute

ALLOWED_IMPORTS = {'math', 'numpy', 'numpy.linalg', 'numpy.random', 'numpy.fft'}

NAMESPACE_IMPORTS module-attribute

NAMESPACE_IMPORTS = {'skills'}

DENIED_NAMES module-attribute

DENIED_NAMES = {'open', 'exec', 'eval', 'compile', 'globals', 'locals', 'vars', 'getattr', 'setattr', 'delattr', 'hasattr', 'input', 'breakpoint', 'help', 'exit', 'quit', 'memoryview', 'type', 'object', 'super', 'dir', 'classmethod', 'staticmethod', 'property', '__import__', '__builtins__', 'importlib', 'os', 'sys', 'subprocess'}

DENIED_ATTRS module-attribute

DENIED_ATTRS = {'gi_frame', 'gi_code', 'gi_yieldfrom', 'cr_frame', 'cr_code', 'cr_await', 'ag_frame', 'ag_code', 'f_globals', 'f_locals', 'f_builtins', 'f_back', 'f_code', 'tb_frame', 'tb_next', 'co_code', 'co_consts', 'func_globals', 'func_code', 'mro', 'tofile', 'dump', 'dumps', 'load', 'loads', 'save', 'savez', 'savez_compressed', 'savetxt', 'loadtxt', 'genfromtxt', 'fromfile', 'fromregex', 'memmap', 'ctypes', 'ctypeslib', 'lib', 'f2py', 'distutils', 'testing', 'DataSource', 'core', 'system', 'popen'}

SAFE_BUILTINS module-attribute

SAFE_BUILTINS = ('abs', 'all', 'any', 'bool', 'callable', 'chr', 'dict', 'divmod', 'enumerate', 'filter', 'float', 'format', 'frozenset', 'hash', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'list', 'map', 'max', 'min', 'next', 'ord', 'pow', 'range', 'repr', 'reversed', 'round', 'set', 'slice', 'sorted', 'str', 'sum', 'tuple', 'zip', 'ArithmeticError', 'AssertionError', 'Exception', 'IndexError', 'KeyError', 'LookupError', 'NotImplementedError', 'RuntimeError', 'StopIteration', 'TypeError', 'ValueError', 'ZeroDivisionError')

SAFE_NUMPY module-attribute

SAFE_NUMPY = _SafeModule(np, 'numpy')

SAFE_MATH module-attribute

SAFE_MATH = _SafeModule(math, 'math')

CodeRejected

Bases: ValueError

The source failed validation; nothing ran.

ProgramTimeout

Bases: BaseException

Raised inside a block that ran past its wall-clock limit (BaseException: except Exception cannot eat it).

ProgramCancelled

Bases: BaseException

Raised inside a block whose episode or session is over.

CodeChecker

CodeChecker()

Bases: NodeVisitor

The AST allow-list check behind validate(); subclasses widen or narrow it (scene programs).

problems instance-attribute

problems: list[str] = []

visit_FunctionDef class-attribute instance-attribute

visit_FunctionDef = _def

visit_AsyncFunctionDef class-attribute instance-attribute

visit_AsyncFunctionDef = _async

visit_AsyncFor class-attribute instance-attribute

visit_AsyncFor = _async

visit_AsyncWith class-attribute instance-attribute

visit_AsyncWith = _async

visit_Await class-attribute instance-attribute

visit_Await = _async

visit_Import

visit_Import(node: Import) -> None

visit_ImportFrom

visit_ImportFrom(node: ImportFrom) -> None

visit_Name

visit_Name(node: Name) -> None

visit_Attribute

visit_Attribute(node: Attribute) -> None

visit_ClassDef

visit_ClassDef(node: ClassDef) -> None

visit_keyword

visit_keyword(node: keyword) -> None

visit_alias

visit_alias(node: alias) -> None

BlockResult dataclass

BlockResult(output: str = '', error: str | None = None, value: Any = None, seconds: float = 0.0, timed_out: bool = False, cancelled: bool = False, rejected: bool = False)

output class-attribute instance-attribute

output: str = ''

error class-attribute instance-attribute

error: str | None = None

value class-attribute instance-attribute

value: Any = None

seconds class-attribute instance-attribute

seconds: float = 0.0

timed_out class-attribute instance-attribute

timed_out: bool = False

cancelled class-attribute instance-attribute

cancelled: bool = False

rejected class-attribute instance-attribute

rejected: bool = False

Sandbox

Sandbox(names: dict[str, Any] | None = None, *, block_timeout_s: float = 60.0, max_output: int = 6000)

A persistent restricted namespace. names are what programs see (robot, finish, skills, ...).

ns instance-attribute

ns: dict[str, Any] = dict(self._base)

add

add(**names: Any) -> None

Make names visible to programs (this namespace, and fresh ones made by define).

take_output

take_output() -> str

paused

paused() -> Iterator[None]

Stop the block's clock (and the watchdog) while the robot executes.

interrupt

interrupt() -> bool

Stop the running block now (the episode or session ended).

short_traceback

short_traceback(exc: BaseException) -> str

run

run(source: str, *, timeout_s: float | None = None) -> BlockResult

Validate and run one block in the persistent namespace. A final bare expression is printed (REPL style).

program_source

program_source(entry: str = 'solve') -> str | None

A self-contained program from the blocks run so far: the imports, function definitions and constant assignments made at the top level of any block (the latest definition of each name), in the order last defined. None if no block defined entry. Statements that act (calls, loops, other assignments) are left out, so submitting it does not replay an experiment.

call

call(fn: Callable[..., Any], *args: Any, timeout_s: float | None = None, **kwargs: Any) -> BlockResult

Call a function defined in this namespace under the time limit (code.program runs solve(robot)).

define

define(source: str, name: str, *, fresh: bool = True) -> Callable[..., Any]

Validate source, run its definitions (in a fresh namespace with this one's builtins, print and initial names, unless fresh=False) and return the function name. Raises CodeRejected. Not time-limited by itself: call it inside call or a block.

validate

validate(source: str, *, filename: str = '<program>') -> ast.Module

Parse and check a program; raises CodeRejected listing every problem found.

defines

defines(tree: Module, name: str) -> bool

truncate

truncate(text: str, limit: int) -> str