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

# Pyodide

> Run Python and packages such as numpy in the TypeScript SDK, in Node and browsers.

What to install and a runnable TypeScript example. The settings, how the workspace connects and the notes are on [Pyodide](https://docs.mirage.strukto.ai/home/setup/runtime/pyodide.md), shared by both SDKs.

## Usage

```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: 'pyodide' } } },
)
try {
  const inline = await ws.shell("python3 -c 'print(1 + 1)'")
  console.log(inline.stdoutText) // 2

  await ws.shell(`echo 'import sys; print(sys.argv[1:])' > /data/hello.py`)
  const script = await ws.shell('python3 /data/hello.py alice bob')
  console.log(script.stdoutText) // ['alice', 'bob']

  const piped = await ws.shell("echo 'print(1 + 1)' | python3")
  console.log(piped.stdoutText) // 2
} finally {
  await ws.close()
}
```

## Packages

[Pyodide's packages](https://pyodide.org/en/stable/usage/packages-in-pyodide.html),
such as numpy, load when a program imports them. The first import downloads
the package from the Pyodide CDN; Node keeps it beside the installed
`pyodide` package for later runs.

| Config key | What it does |
| - | - |
| `packages` | Load these when each interpreter starts, before the program runs. |
| `auto_load_from_imports` | Load what a program imports. Default `true`; `false` loads only `packages`. |
| `deny_packages` | Never download these for an import. An import still works when the package is reachable another way, such as through `sys_path`. |
| `sys_path` | Mount paths to put first on `sys.path`: directories, globs, or pure-Python `.whl` files. |
| `package_base_url` | Where packages download from; point it at a local copy to work offline. |

```typescript theme={null}
import { MountMode, RAMVFS, Workspace } from '@struktoai/mirage-node'
import { PyodideRuntime } from '@struktoai/mirage-core/runtime/python/pyodide'

const runtime = new PyodideRuntime({
  config: {
    packages: ['numpy'],
    denyPackages: ['requests'],
    sysPath: ['/data/vendor', '/data/wheels/*.whl'],
  },
})
const ws = new Workspace({ '/data': new RAMVFS() }, { mode: MountMode.EXEC, machines: { py: runtime } })
```

## Scripts and flags

* Each command and one-shot evaluation starts a fresh interpreter, so imports
  do not carry over; files on the mounts do. A console session keeps its own
  interpreter.
* A script runs as in CPython: `__file__` is absolute, tracebacks quote its
  lines, and `sys.path[0]` is its directory. `-P` leaves that entry off, and
  for `-c` and stdin omits the working directory entry. `sys_path` entries
  stay either way.
* `-P`, `-O`/`-OO` and `-B` show in a read-only `sys.flags`. `-O` and `-OO`
  compile imported modules from source. Flags and import paths reset when the
  command ends, errors included.
* An installed Python CLI gets bare `argv` (its name at index 0) and `stdin`
  (bytes, or `None`), as on Monty; Pyodide also keeps `sys.argv` and
  `sys.stdin`.
* Standard streams support text and `.buffer` I/O, but do not expose native
  OS file descriptors.

## Files

* Native packages such as PIL and NumPy reach the same mounts as `open()`.
* A file is fetched on first access and cached for the run; edits made
  elsewhere during the run are not seen.
* A create, delete, rename, mkdir, chmod or truncate reaches the mount when
  the call is made, and a write when the file is closed, so a refusal fails
  that call with the mount's errno. Writes still open at the end land then; a
  failure there exits nonzero with a message. Concurrent writes are not
  conflict-checked.
* A path no mount serves answers `ENOTSUP` to `os.getxattr`.
* A console keeps its own `os.chdir()`, even through an exception; if its
  directory disappears, the next input fails, resets the working directory to
  `/` and keeps the variables.
* Mount files under a prefix such as `/data`: a mount at `/` cannot replace
  Pyodide's own filesystem, which holds its standard library.

## Worker and browser setup

Pyodide runs in a worker, which Node needs no setup for. In a browser, the
page needs one of two things:

* **Cross-origin isolation:** the page is served with
  `Cross-Origin-Opener-Policy: same-origin` and
  `Cross-Origin-Embedder-Policy: require-corp`.
* **Mirage's service worker**, on any other page: copy
  `node_modules/@struktoai/mirage-browser/dist/pyodide-sw.js` to the folder
  your site serves at its root, and register it before the first `python3`:

```ts theme={null}
const container = navigator.serviceWorker
await container.register('/pyodide-sw.js')
if (container.controller === null) {
  const controlled = new Promise((resolve) => {
    container.addEventListener('controllerchange', resolve, { once: true })
  })
  ;(await container.ready).active?.postMessage('claim')
  await controlled
}
```

The service worker answers only the file calls of Pyodide and QuickJS, which
runs in a worker the same way, and lets every other request through. The check after `register` covers a first visit and a hard
reload, which both leave the page uncontrolled. Service workers need HTTPS or
`localhost`. A site that already has a service worker adds the bridge to it
instead: call `importScripts('/pyodide-sw.js')` at the top of that worker
(`import '/pyodide-sw.js'` in a module worker) and register it in place of
`/pyodide-sw.js`.

With neither, `python3` and `node` exit 127 and say why. JSPI is not needed.

In a browser, Pyodide loads from its CDN unless `home` names another place,
such as a folder on your site holding the `pyodide` package's files
(`home: '/pyodide/'`). Mirage starts its workers from `blob:` URLs, so a
Content-Security-Policy needs `blob:` in `worker-src`, and
`https://cdn.jsdelivr.net` in `script-src` and `connect-src` while Pyodide
loads from the CDN.

## Concurrency and timeouts

* `max_concurrency` (default 1) bounds active top-level commands, one-shot
  evaluations and inputs to distinct consoles; extra calls wait. Calls in one
  shell session stay ordered; give independent work its own session with
  `ws.createSession(id)` and `{ sessionId: id }`. Nested subprocesses bypass
  the limit. In a browser the limit stays 1, so commands from every session
  take turns; a second `Workspace` runs alongside the first.
* A timeout raises `KeyboardInterrupt` in the program, even in a busy loop.
  That needs `SharedArrayBuffer`. Without it, a workspace command's worker is
  stopped instead, and a standalone run on the main thread blocks the event
  loop until it ends.

## Sockets

`connect` and `sendto` raise `ENETUNREACH`, and `listen`, a UDP `bind` and
`socket.socketpair()` raise `ENETDOWN`, so `urllib.request.urlopen` fails
fast. Compare against `errno.ENETUNREACH`, not a number: the values are
Emscripten's. `socket.socket()`, a TCP `bind` and name lookups still answer.
An `init_module` that calls `useNodeSockFS()` installs real sockets.

## Containment

Guest Python can run JavaScript in its worker through Pyodide. On Node with
`module.registerHooks`, Mirage hardens the worker after interpreter setup
and before guest execution:

* Further module loads are refused, including `import('node:child_process')`
  and imports of already loaded Node modules.
* Host globals (`process`, `global`, `fetch`, `WebSocket`, and an injected
  `require`) are removed.
* Exposed host filesystem and socket APIs are disabled, including
  `mountNodeFS`, `mountNativeFS`, `useNodeSockFS`, `NODEFS`, and host file
  preloading. Binary reads are restricted to configured local distribution
  and package directories, with traversal and symlink escape checks.

Automatic package loading still works from a local distribution. After the
seal, network package loading and CDN fallback are unavailable. Packages
listed in `packages` and trusted `bootstrap_code` run during initialization,
before the seal.

An `init_module` opts into host access (`reach: process`), so its worker is
left unsealed. Node releases without `module.registerHooks`, including Node
20 and Node 22 before 22.15, also run unsealed; use them only for trusted
code. Standalone SDK execution without a workspace can run on the main
thread and is trusted-only. Workspace-backed execution requires a worker.

Browser workers are left unsealed: JavaScript can still use `fetch` and
module loading, subject to the page's Content Security Policy. Each command
gets its own worker.

These measures close known host access paths. They do not make arbitrary
JavaScript safe: Pyodide exposes mutable interpreter internals, and a worker
thread shares the host process. For hostile code, use a
[machine](https://docs.mirage.strukto.ai/home/setup/machine/overview.md) with a process and kernel boundary.

## Child processes

`subprocess` runs Mirage commands:

```python theme={null}
import subprocess

result = subprocess.run(["printf", "%s", "hello"], capture_output=True, text=True, check=True)
print(result.stdout)
```

* Supported: `run`, `call`, `check_call`, `check_output`, `Popen` with live
  pipes, `poll`, `wait`, `communicate`, termination, timeout retries, text
  mode, `stderr=STDOUT`, and `shell=True` through the workspace's `sh`.
* `sys.executable` is `/usr/bin/python3`, and `shutil.which` sees the
  profile's programs. Functions and shell builtins are not programs.
* The environment is inherited unless `env` replaces it. Writes land before
  each process call, and file caches reset after it.
* A timed-out `wait` or `communicate` leaves the child running; `run` kills
  it. Children still running when the program ends are cancelled.
* Not supported: native descriptors, PTYs, process groups, user switching,
  `preexec_fn`, `asyncio.create_subprocess_exec` and signal handlers. An
  unsupported option fails with an error.

## Configuration

The package keys are on the [Pyodide](https://docs.mirage.strukto.ai/home/setup/runtime/pyodide.md#packages)
page. The others:

| Key (YAML) | Meaning |
| - | - |
| `home` | Where the distribution loads from. Without it, `MIRAGE_PYODIDE_HOME`, then the installed package in Node or the pinned CDN in browsers. |
| `max_concurrency` | Active top-level calls, default 1. |
| `lock_file_url` | A custom `pyodide-lock.json`. |
| `bootstrap_code` | Python run when each interpreter starts. |
| `init_module` | A trusted host module whose default export receives Pyodide before `bootstrap_code`, and may return a cleanup. |

`init_module` runs per command or evaluation and once per console, inside
the worker. It has host privileges, so keep it in deployment config:
`POST /v1/workspaces` rejects it, and setting it gives the runtime host
access. Only an in-process shutdown calls its cleanup.


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