> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mirage.strukto.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Monty

> A Python runtime in both Mirage SDKs, supporting a subset of Python.

[Pydantic Monty](https://github.com/pydantic/monty) runs `python3` in both
SDKs, including Node and browsers. It supports a subset of Python and works
with workspace files under the same permissions as shell commands. Programs
cannot access host files, host environment variables or the network.

## Installation

> [tab] Python
>
> ```bash theme={null}
> pip install 'mirage-ai[monty]'
> ```

> [tab] TypeScript
>
> ```bash theme={null}
> pnpm add @pydantic/monty
> ```

## Usage

Declare an [`in_process`](https://docs.mirage.strukto.ai/home/setup/machine/in_process) machine with
`runtime: monty` to run `python3` on Monty:

> [tab] Python
>
> ```python theme={null}
> from mirage import RAMVFS, MountMode, Workspace
>
> ws = Workspace(
>     {"/data": RAMVFS()},
>     mode=MountMode.EXEC,
>     machines={"py": {"provider": "in_process", "runtime": "monty"}},
> )
> await ws.shell("python3 -c 'print(1 + 1)'")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node'
>
> const ws = new Workspace(
>   { '/data': new RAMVFS() },
>   { mode: MountMode.EXEC, machines: { py: { provider: 'in_process', runtime: 'monty' } } },
> )
> await ws.shell("python3 -c 'print(1 + 1)'")
> ```

> [tab] YAML
>
> ```yaml theme={null}
> mode: exec
> machines:
>   py:
>     provider: in_process
>     runtime: monty
> mounts:
>   /data:
>     vfs: ram
> ```

## Memory

Set `max_memory` to limit the Python program's memory per run, using a size
such as `64M`:

```yaml theme={null}
machines:
  py:
    provider: in_process
    runtime: monty
    max_memory: 64M
```

A run that needs more raises `MemoryError`. A run also holds no more than its
workspace's [`max_memory`](https://docs.mirage.strukto.ai/home/limits#memory)
has left, 96 MB by default.

## How runs execute

* Mirage runs each program in one of four worker processes that every
  workspace in the process shares, so an idle workspace holds none. A run
  past four waits for a free one. On Cloudflare Workers, which start no
  processes, Monty runs inside the isolate.
* A timeout or `kill` stops the worker running the program, and
  `kill -STOP` pauses it.
* `ps` lists each run under its machine, such as `in_process:monty`, with
  its words as expanded, as it lists any machine's programs.

## Remote server

A `remote` machine with `runtime: monty` runs `python3` on a remote Monty
server, such as
[Logfire Agent Sandboxes](https://pydantic.dev/logfire), instead of local
workers. File and environment calls still come back to Mirage, so mounts,
mount modes and policy apply as they do locally. It runs in the Python SDK
and in Node; the browser and Cloudflare Workers refuse it.

```yaml theme={null}
machines:
  py:
    provider: remote
    runtime: monty
    api_key: ${LOGFIRE_API_KEY}
    max_memory: 64M
```

* For Logfire, use a project API key with the
  `project:execute_agent_sandboxes` scope. The region the key names, the
  `us` in `pylf_v2_us_…` or `eu`, picks the server,
  `https://logfire-us.pydantic.dev` or `https://logfire-eu.pydantic.dev`, so
  no `url` is needed.
* Set `url` for any other Monty gRPC server, such as a self-hosted one; it
  always takes precedence. `api_key` is sent as a bearer token; leave it out
  for a server that takes none. A key that is not a Logfire key from a known
  region needs a `url`.
* The key never appears in snapshots, the server API or error messages.
* Each machine keeps its own connection, opened on its first run and closed
  with the workspace; workspaces never share one.
* A server that refuses, cannot be reached or drops the connection fails the
  run with exit 1 and `monty: remote server: <reason>` on stderr.
* A timeout or `kill` ends the run's session on the server. `kill -STOP`
  cannot pause a remote run.
* `ps` lists each run under `remote:<name>`.

Each `python3` run opens a session on the server, and each file or
environment call is a round trip. Measured against Logfire's US region from
about 25 ms away:

| Step | Cost |
| - | - |
| open a session, once per `python3` run | about 650 ms |
| a run with no file calls | about 140 ms |
| each file or environment call | about 98 ms |

`open(path).read()` makes two or three calls. Logfire allows 1,000 file and
environment calls per session, whatever Mirage asks for; a program past them
stops with `suspension limit 1000 exceeded`. Its documented limits are 50 ms of
interpreter CPU per run and 20 MiB of memory per session. A remote server
suits compute-light programs with a few file calls, not scripts that walk
directories.

## Python compatibility

Support applies to both SDKs unless a row says otherwise.
For Python syntax and standard-library coverage, see
[Monty's limitations](https://pydantic.dev/docs/monty/limitations/).

Examples assume a writable `/data` mount. Mount modes and permissions still apply.

### `open()`

Modes and modifiers are listed separately; for example, `rb` combines `r` and `b`.

| Mode or modifier | Support |
| - | - |
| `r` | ✓ |
| `w` | ✓ |
| `a` | ✓ |
| `b` | ✓ |

> [accordion] Example: append to a workspace file
>
> ```python theme={null}
> with open("/data/log.txt", "a") as f:
>     f.write("Job completed.\n")
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `x` | Exclusive creation is not supported. |
> | `+` | Read/write update modes (`r+`, `w+`, `a+`) are not supported. |

### File objects

| API | Support |
| - | - |
| `f.read()` | ✓ |
| `f.readline()` | ✓ |
| `f.readlines()` | ✓ |
| `f.seek()` | ✓ |
| `f.tell()` | ✓ |
| `f.write()` | ✓ |
| `for line in f` | ✓ |

> [accordion] Example: write and read lines
>
> ```python theme={null}
> with open("/data/example.txt", "w") as f:
>     f.write("first\nsecond\n")
>
> with open("/data/example.txt", "r") as f:
>     print(f.readline())  # first
>     f.seek(0)
>     print(f.tell())  # 0
>     print(f.readlines())  # ["first\n", "second\n"]
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | Reads and seeks | The whole file is loaded into memory; reads and seeks use that copy. |
> | `f.truncate()` | ✗ |
> | `f.fileno()` | ✗ |
> | `f.write()` | Each call is written at once. |

### `os`

The working directory and environment come from the Mirage session, not the host.

#### File operations

| API | Support |
| - | - |
| `os.remove()` | ✓ |
| `os.unlink()` | ✓ |
| `os.rename()` | ✓ |
| `os.replace()` | ✓ |

#### Directory operations

| API | Support |
| - | - |
| `os.listdir()` | ✓ |
| `os.scandir()` | ✓ |
| `os.walk()` | ✓ |
| `os.mkdir()` | ✓ |
| `os.makedirs()` | ✓ |
| `os.rmdir()` | ✓ |

#### Metadata and links

| API | Support |
| - | - |
| `os.stat()` | ✓ |

#### Environment and working directory

| API | Support |
| - | - |
| `os.getcwd()` | ✓ |
| `os.chdir()` | Python SDK only |
| `os.environ` | ✓ |
| `os.getenv()` | ✓ |
| `os.urandom()` | ✓ |

> [accordion] Example: list a workspace directory
>
> ```python theme={null}
> import os
>
> print(os.listdir("/data"))
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `os.open()` | ✗ |
> | File descriptors | ✗ |
> | `os.truncate()` | ✗ |
> | `os.lstat()` | ✗ |
> | `os.fstat()` | ✗ |
> | `os.symlink()` | ✗ |
> | `os.readlink()` | ✗ |
> | `os.link()` | ✗ |
> | `os.utime()` | ✗ |
> | `os.chmod()` | ✗ |
> | `os.getxattr()` | ✗ |
> | `os.rename()`, `os.replace()` | Raises `OSError` across mounts. |
> | `os.stat()` | In TypeScript, use named fields such as `st.st_size`. Whole-second timestamps may be integers. |
> | `os.chdir()` | Lasts for the run. Raises `RuntimeError` in TypeScript. |
> | `os.urandom()` | Up to 1 MiB per call. |

### `os.path`

| API | Support |
| - | - |
| `os.path.exists()` | ✓ |
| `os.path.isfile()` | ✓ |
| `os.path.isdir()` | ✓ |
| `os.path.islink()` | ✓ |
| `os.path.getsize()` | Python SDK only |
| `os.path.getmtime()` | Python SDK only |
| `os.path.realpath()` | ✓ |
| `os.path.join()`, `os.path.basename()`, `os.path.dirname()`, `os.path.splitext()` | ✓ |
| `os.path.abspath()`, `os.path.relpath()`, `os.path.normpath()` | ✓ |

> [accordion] Example: check a workspace path
>
> ```python theme={null}
> import os
>
> path = os.path.join("/data", "input.txt")
> print(os.path.exists(path), os.path.splitext(path))
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `os.path.getsize()`, `os.path.getmtime()` | Raise `RuntimeError` in TypeScript. Use `os.stat(path).st_size` and `.st_mtime`. |

### `pathlib`

`Path.cwd()` and relative path resolution use the shell's working directory.

| API | Support |
| - | - |
| `Path.open()` | ✓ |
| `Path.read_text()` | ✓ |
| `Path.read_bytes()` | ✓ |
| `Path.write_text()` | ✓ |
| `Path.write_bytes()` | ✓ |
| `Path.stat()` | ✓ |
| `Path.exists()` | ✓ |
| `Path.is_file()` | ✓ |
| `Path.is_dir()` | ✓ |
| `Path.is_symlink()` | ✓ |
| `Path.iterdir()` | ✓ |
| `Path.glob()` | ✓ |
| `Path.rglob()` | ✓ |
| `Path.walk()` | ✓ |
| `Path.mkdir()` | ✓ |
| `Path.rmdir()` | ✓ |
| `Path.unlink()` | ✓ |
| `Path.rename()` | ✓ |
| `Path.cwd()` | ✓ |
| `Path.resolve()` | ✓ |

> [accordion] Example: create and inspect a workspace file
>
> ```python theme={null}
> from pathlib import Path
>
> path = Path("/data/example.txt")
> path.write_text("hello\n")
> print(path.read_text())
> print(path.stat().st_size)
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `Path.touch()` | ✗ |
> | `Path.stat()` | In TypeScript, use the named fields (`st.st_size`), not `st[6]`. |
> | `Path.rename()` | Raises `OSError` across mounts. |

### `sys`

Mirage passes command inputs through the [runtime globals](#runtime-globals).

> [accordion] Example: use Mirage command inputs
>
> ```python theme={null}
> print(argv[1:])
> print(stdin)
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | `sys.argv` | Does not receive the invocation's arguments. Use `argv` instead. |
> | `sys.stdin` | Not available. Use `stdin` for piped input. |

### `time` and `datetime`

The clocks start at the workspace's [system time](https://docs.mirage.strukto.ai/home/configuration/workspace.md#system-time)
when it sets one, and files the program writes are stamped from the same
clock. `time.monotonic()` and `time.perf_counter()` measure elapsed time.

| API | Support |
| - | - |
| `time.time()`, `time.time_ns()` | ✓ |
| `time.localtime()`, `time.gmtime()`, `time.strftime()` | ✓ |
| `time.monotonic()`, `time.perf_counter()` | ✓ |
| `datetime.datetime.now()` | ✓ |
| `datetime.date.today()` | ✓ |

> [accordion] Example: print today's date
>
> ```python theme={null}
> import datetime
>
> print(datetime.date.today())
> ```

> [accordion] Limitations
>
> | API or behavior | Limitation |
> | - | - |
> | Local times | The session's `TZ`, UTC without one. |

### `json`

JSON parsing and serialization come from Monty; see its
[`json` reference](https://pydantic.dev/docs/monty/limitations/json/).

| API | Support |
| - | - |
| `json.load()` | ✓ |
| `json.dump()` | ✓ |
| `json.loads()` | ✓ |
| `json.dumps()` | ✓ |

> [accordion] Example: write and read workspace JSON
>
> ```python theme={null}
> import json
>
> with open("/data/result.json", "w") as f:
>     json.dump({"status": "done"}, f)
>
> with open("/data/result.json") as f:
>     print(json.load(f)["status"])
> ```

### `csv`, `tomllib` and `hashlib`

These modules read and write workspace files through `open()`.

| API | Support |
| - | - |
| `csv.reader()`, `csv.DictReader()` | ✓ |
| `csv.writer()` | ✓ |
| `tomllib.load()` | ✓ |
| `hashlib` | ✓ |

> [accordion] Example: read a workspace CSV
>
> ```python theme={null}
> import csv
>
> with open("/data/orders.csv", newline="") as f:
>     for row in csv.DictReader(f):
>         print(row["id"], row["total"])
> ```

### Runtime globals

| API | Support |
| - | - |
| `argv` | ✓ |
| `stdin` | ✓ |
| `__file__` | ✓ |

* `argv`: The invocation name and arguments.
* `stdin`: The piped input.
* `__file__`: The script's name under the starting directory.

> [accordion] Example: read invocation inputs
>
> ```python theme={null}
> print(argv)
> print(stdin)
> ```

## Notes

* A run starts in the shell's working directory. The script and every
  relative path pass the same mount and permission checks as `cat`: a rule
  protecting `/data/job.py` refuses `python3 job.py` from `/data`.
* Script arguments follow shell expansion, including globs.
* A console session takes the working directory on its first input and keeps
  its own after that.
* `raise SystemExit` exits successfully. `raise SystemExit("message")` exits
  with status 1 and prints the message.

## Python subset

Monty 1.4.0 implements a subset of Python, and Mirage never falls back to
another interpreter.

Monty maintains the details of its
[standard-library modules](https://pydantic.dev/docs/monty/limitations/modules/)
and [language limitations](https://pydantic.dev/docs/monty/limitations/language/).
Those pages track upstream Monty; the integration tables above describe the
version used by Mirage. Third-party imports are unavailable.

## Unsupported modules

Common modules unavailable in Monty 1.4.0:

* **Files:** `glob`, `io`, `shutil`, `tempfile`.
* **Networking:** `http`, `socket`, `ssl`, `urllib`.
* **Processes and concurrency:** `concurrent.futures`, `multiprocessing`, `queue`, `subprocess`, `threading`.
* **Data formats and archives:** `array`, `pickle`, `struct`, `zipfile`, `zlib`.
* **Numbers and hashing:** `fractions`, `hmac`, `uuid`.
* **Language and introspection:** `abc`, `contextlib`, `ctypes`, `importlib`, `inspect`, `types`, `weakref`.
* **CLI and diagnostics:** `argparse`, `logging`, `traceback`, `unittest`, `warnings`.
* **Other utilities:** `enum`, `heapq`, `operator`, `string`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.