> ## 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 a `worker` machine to run `python3` on Monty, in worker processes Mirage starts:

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

> [tab] YAML
>
> ```yaml theme={null}
> mode: exec
> machines:
>   py:
>     provider: worker
> 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: worker
    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/core/output-limits#limit-a-workspaces-memory)
has left, 96 MB by default.

## 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.