Skip to content

xnano.sandbox

xnano.sandbox

xnano.sandbox

Run untrusted Python, such as code written by a language model, against a canvas.

The code runs in Monty, a sandboxed Python interpreter, which cannot reach the files, the network or this program. Inside it, the code imports a small xnano module that draws on the canvas you give it, through its devices: canvas.screen.write, canvas.speaker.play, canvas.clock.step and pixel_art, with canvas and pixel_art already defined. SANDBOX_STUBS is that module's whole interface, and every program is type-checked against it before it runs.

This module needs the optional pydantic-monty package: pip install "xnano[monty]".

Classes:

  • Sandbox –

    A Monty sandbox that draws on a canvas and remembers what each program defined.

Functions:

  • run –

    Type-check and run one program in a new Monty sandbox that draws on canvas.

Attributes:

  • DEFAULT_LIMITS (ResourceLimits) –

    The limits a sandbox starts from: ten seconds of running code per

  • SANDBOX_STUBS –

    The .pyi source of the xnano module that sandboxed code imports.

DEFAULT_LIMITS module-attribute

DEFAULT_LIMITS: ResourceLimits = {'max_feed_duration_secs': 10.0, 'max_memory': 256 * 1024 * 1024, 'max_suspensions': 1000000}

The limits a sandbox starts from: ten seconds of running code per Sandbox.run, 256 MiB of memory, and a million calls to the canvas over the sandbox's life. Time spent waiting in time.sleep or inside the canvas does not count toward the ten seconds.

SANDBOX_STUBS module-attribute

SANDBOX_STUBS = '"""Draw on the canvas of the program that runs this code."""\n\nfrom typing import Literal\n\nColor = str | tuple[int, int, int]\n"""A color name such as \'red\', a \'#rrggbb\' string, or a (red, green, blue) tuple."""\n\nPosition = int | str\n"""A number of cells, a percentage such as \'50%\', \'left\', \'center\', \'right\', \'top\' or\n\'bottom\', or \'next\': after what was written before it."""\n\n\nclass Clock:\n    """The canvas\'s clock."""\n\n    @property\n    def elapsed_seconds(self) -> float:\n        """Seconds since the canvas started."""\n\n    @property\n    def frame(self) -> int:\n        """How many frames the clock has counted."""\n\n    def step(self, delta_seconds: float | None = None) -> None:\n        """\n        Move the clock by delta_seconds (one frame when None) and draw a frame.\n\n        A canvas on a screen moves by itself: wait with time.sleep(seconds) instead.\n        """\n\n\nclass Art:\n    """Pixel art made with pixel_art(). Show it with canvas.screen.write(art)."""\n\n    @property\n    def width(self) -> int:\n        """The width in pixels."""\n\n    @property\n    def height(self) -> int:\n        """The height in pixels. A pixel is half a cell tall."""\n\n\nclass Placement:\n    """\n    Something written on the canvas.\n\n    Read its attributes, and change it with its methods: assigning to an attribute is\n    refused.\n    """\n\n    @property\n    def x(self) -> int:\n        """The column of the left edge."""\n\n    @property\n    def y(self) -> int:\n        """The row of the top edge."""\n\n    @property\n    def width(self) -> int:\n        """The width in cells."""\n\n    @property\n    def height(self) -> int:\n        """The height in cells."""\n\n    @property\n    def text(self) -> str:\n        """The text shown, line by line."""\n\n    def move(self, x: int = 0, y: int = 0) -> None:\n        """Move by a number of cells; negative numbers move left and up."""\n\n    def set_position(self, x: Position | None = None, y: Position | None = None) -> None:\n        """Move the left edge to x and the top edge to y; None keeps that one."""\n\n    def set_text(self, text: str) -> None:\n        """Show new text; the placement grows or shrinks to fit it."""\n\n    def remove(self) -> None:\n        """Take it off the canvas. Removing twice is harmless."""\n\n\nclass Screen:\n    """What the canvas shows."""\n\n    @property\n    def width(self) -> int:\n        """The width in cells."""\n\n    @property\n    def height(self) -> int:\n        """The height in cells."""\n\n    def write(\n        self,\n        content: str | list[str] | Art,\n        *,\n        x: Position | None = None,\n        y: Position | None = None,\n        width: Position | None = None,\n        height: Position | None = None,\n        layer: int = 0,\n        foreground: Color | None = None,\n        background: Color | None = None,\n        bold: bool = False,\n        dim: bool = False,\n        italic: bool = False,\n        underline: bool = False,\n        border: Literal[\'plain\', \'rounded\', \'double\', \'thick\'] | bool | None = None,\n        title: str | None = None,\n    ) -> Placement:\n        """\n        Put text (or a list of lines) or pixel art on the canvas. With no x and y it goes on\n        the next line: the first write at the top-left corner, each later one below the lines\n        before it, and the lines follow each other when one grows. A y that is given places\n        it on that row, outside the lines, right after what was written just before when that\n        is on the row. A higher layer is drawn over a lower one.\n        """\n\n\nclass Speaker:\n    """What the canvas plays."""\n\n    def play(\n        self,\n        music: str,\n        *,\n        instrument: str | None = None,\n        beats: float | None = None,\n        volume: float | None = None,\n    ) -> None:\n        """\n        Play a note such as \'C4\', a frequency such as \'440hz\', or melody text such as\n        \'C4 E4 G4:2 rest C5+E5\'. Needs the program to have xnano\'s audio installed.\n        """\n\n\nclass Canvas:\n    """The canvas this code draws on: its screen, its speaker and its clock."""\n\n    @property\n    def screen(self) -> Screen:\n        """What the canvas shows: write on it."""\n\n    @property\n    def speaker(self) -> Speaker:\n        """What the canvas plays."""\n\n    @property\n    def clock(self) -> Clock:\n        """The canvas\'s clock."""\n\n\ncanvas: Canvas\n"""The canvas this code draws on."""\n\n\ndef pixel_art(\n    rows: str | list[str],\n    palette: str | dict[str, Color],\n    *,\n    background: Color | None = None,\n) -> Art:\n    """\n    Build pixel art, one character per pixel, without drawing it.\n\n    rows is a multi-line string or a list of rows of equal length. palette says what each\n    character means, as a dict or a string such as \'R=#e03040 G=green\'; a character it does\n    not name, such as \'.\', is a transparent pixel.\n    """\n'

The .pyi source of the xnano module that sandboxed code imports.

Every program is type-checked against it before it runs. Give it to whoever writes the code, such as a language model, so that it knows what it can call.

Sandbox

Sandbox(canvas: Canvas[DepsT, StateT], *, limits: ResourceLimits | None = None)

A Monty sandbox that draws on a canvas and remembers what each program defined.

Every run continues the same session: names, functions and placements that one program made are there for the next, so a language model can build a picture over several turns. For a single program, run is shorter. The sandbox starts a Monty worker process when it is created; close it, or use it in a with block, to stop that process.

Parameters:

  • canvas (Canvas[DepsT, StateT]) –

    The canvas the code draws on, from new or open.

  • limits (ResourceLimits | None, default: None ) –

    Monty's ResourceLimits. The keys you give replace those of DEFAULT_LIMITS; a key set to None turns that limit off.

Attributes:

  • canvas –

    The canvas the code draws on.

Raises:

  • ImportError –

    pydantic-monty is not installed. Install it with pip install "xnano[monty]".

  • TypeError –

    canvas is not a canvas.

Examples:

import xnano
from xnano.sandbox import Sandbox

with xnano.new(width=12, height=2) as canvas, Sandbox(canvas) as sandbox:
    sandbox.run("label = canvas.screen.write('hello')")
    sandbox.run("label.set_text('goodbye')")
    assert canvas.screen.render().splitlines()[0] == 'goodbye'

Start a Monty worker process whose code draws on canvas.

Parameters:

  • canvas (Canvas[DepsT, StateT]) –

    The canvas the code draws on.

  • limits (ResourceLimits | None, default: None ) –

    Monty's ResourceLimits, over DEFAULT_LIMITS.

Methods:

  • run –

    Type-check and run a program in the sandbox, and return its last expression.

  • close –

    Stop the sandbox's worker process. Closing twice is harmless.

Source code in xnano/sandbox.py
def __init__(
    self, canvas: Canvas[DepsT, StateT], *, limits: ResourceLimits | None = None
) -> None:
    """
    Start a Monty worker process whose code draws on ``canvas``.

    Args:
        canvas: The canvas the code draws on.
        limits: Monty's ``ResourceLimits``, over
            [`DEFAULT_LIMITS`][xnano.sandbox.DEFAULT_LIMITS].
    """
    self._start(canvas, limits, None)

run

run(code: str) -> object

Type-check and run a program in the sandbox, and return its last expression.

canvas and pixel_art are defined, and import xnano gives the same module; see SANDBOX_STUBS. What the program prints goes where this program's prints go, which a canvas on the screen holds back. A placement the program returns comes back as the Placement itself.

Parameters:

  • code (str) –

    The Python source to run.

Returns:

  • object –

    The value of the program's last line when it is an expression, else None.

Raises:

  • MontyTypingError –

    The program does not fit the sandbox's interface, such as an unknown keyword or an assignment to a placement's attribute. Nothing ran, and the message points at the line.

  • MontySyntaxError –

    The program is not valid Python.

  • MontyRuntimeError –

    The program raised an error or went over a limit. Its display() is the sandbox's traceback. The sandbox stays usable.

  • TypeError –

    code is not a string.

Source code in xnano/sandbox.py
def run(self, code: str) -> object:
    """
    Type-check and run a program in the sandbox, and return its last expression.

    ``canvas`` and ``pixel_art`` are defined, and ``import xnano`` gives the same module; see
    [`SANDBOX_STUBS`][xnano.sandbox.SANDBOX_STUBS]. What the program prints goes where
    this program's prints go, which a canvas on the screen holds back. A placement the
    program returns comes back as the [`Placement`][xnano.layout.Placement] itself.

    Args:
        code: The Python source to run.

    Returns:
        The value of the program's last line when it is an expression, else ``None``.

    Raises:
        pydantic_monty.MontyTypingError: The program does not fit the sandbox's
            interface, such as an unknown keyword or an assignment to a placement's
            attribute. Nothing ran, and the message points at the line.
        pydantic_monty.MontySyntaxError: The program is not valid Python.
        pydantic_monty.MontyRuntimeError: The program raised an error or went over a
            limit. Its ``display()`` is the sandbox's traceback. The sandbox stays usable.
        TypeError: ``code`` is not a string.
    """
    if not isinstance(code, str):
        raise TypeError(
            f'Sandbox.run() takes the program as a string, but got '
            f'{type(code).__name__}. Pass Python source such as "canvas.screen.write(\'hi\')".'
        )
    return _host_value(self._session.feed_run(code, print_callback=_print))

close

close() -> None

Stop the sandbox's worker process. Closing twice is harmless.

Source code in xnano/sandbox.py
def close(self) -> None:
    """Stop the sandbox's worker process. Closing twice is harmless."""
    self._resources.close()

run

run(code: str, canvas: Canvas[DepsT, StateT], *, limits: ResourceLimits | None = None) -> object

Type-check and run one program in a new Monty sandbox that draws on canvas.

This is Sandbox(canvas, limits=limits).run(code) with the sandbox closed afterwards; see Sandbox to run several programs in one session.

Parameters:

  • code (str) –

    The Python source to run. canvas and pixel_art are defined in it.

  • canvas (Canvas[DepsT, StateT]) –

    The canvas the code draws on.

  • limits (ResourceLimits | None, default: None ) –

    Monty's ResourceLimits, over DEFAULT_LIMITS.

Returns:

  • object –

    The value of the program's last line when it is an expression, else None.

Raises:

  • ImportError –

    pydantic-monty is not installed. Install it with pip install "xnano[monty]".

  • MontyError –

    The program did not type-check, was not valid Python, raised an error or went over a limit; see Sandbox.run.

Examples:

import xnano
import xnano.sandbox

with xnano.new(width=16, height=3) as canvas:
    xnano.sandbox.run(
        "canvas.screen.write('sandboxed', x='center', y=1, foreground='green')", canvas
    )
    assert canvas.screen.render().splitlines()[1] == '   sandboxed'
Source code in xnano/sandbox.py
def run(
    code: str,
    canvas: Canvas[DepsT, StateT],
    *,
    limits: ResourceLimits | None = None,
) -> object:
    """
    Type-check and run one program in a new Monty sandbox that draws on ``canvas``.

    This is ``Sandbox(canvas, limits=limits).run(code)`` with the sandbox closed afterwards;
    see [`Sandbox`][xnano.sandbox.Sandbox] to run several programs in one session.

    Args:
        code: The Python source to run. ``canvas`` and ``pixel_art`` are defined in it.
        canvas: The canvas the code draws on.
        limits: Monty's ``ResourceLimits``, over [`DEFAULT_LIMITS`][xnano.sandbox.DEFAULT_LIMITS].

    Returns:
        The value of the program's last line when it is an expression, else ``None``.

    Raises:
        ImportError: ``pydantic-monty`` is not installed. Install it with
            ``pip install "xnano[monty]"``.
        pydantic_monty.MontyError: The program did not type-check, was not valid Python,
            raised an error or went over a limit; see
            [`Sandbox.run`][xnano.sandbox.Sandbox.run].

    Examples:
        ```python
        import xnano
        import xnano.sandbox

        with xnano.new(width=16, height=3) as canvas:
            xnano.sandbox.run(
                "canvas.screen.write('sandboxed', x='center', y=1, foreground='green')", canvas
            )
            assert canvas.screen.render().splitlines()[1] == '   sandboxed'
        ```
    """
    with Sandbox(canvas, limits=limits) as sandbox:
        return sandbox.run(code)