# dart_monty

Sandboxed Python interpreter for Dart and Flutter. Run Python from native, web, and mobile — one package, every platform.

FFI (Native) WASM (Browser) REPL Plugins Sandbox

## Quick Start

Three API levels — from one-shot execution to full plugin sessions.

### One-Shot Execution

    // Run Python and get the result
    final result = await Monty.exec('2 + 2');
    print(result.value); // MontyInt(4)

### Stateful REPL

    // Variables, functions, classes persist across calls
    final repl = MontyRepl();
    await repl.feed('x = 42');
    await repl.feed('def double(n): return n * 2');
    final r = await repl.feed('double(x)');
    print(r.value); // MontyInt(84)

### Session with Plugins

    // Full plugin dispatch — template, messaging, sandboxing
    final session = ReplSession(
      plugins: [
        DinjaTemplatePlugin(),
        MessageBusPlugin(),
        SandboxPlugin(platformFactory: () async => MontyFfi()),
      ],
    );

    final r = await session.run(
      "tmpl_render(template='Hello {{ name }}!', context={'name': 'World'})",
    );
    print(r.value); // 'Hello World!'

## REPL — Native Heap Persistence

Functions, classes, closures, and heap objects survive across calls. No JSON serialization — the Rust interpreter maintains state natively.

### MontyRepl

Low-level REPL with `feed()` and `feedStart()`/`resume()` for host function dispatch.

### ReplSession

High-level session combining REPL + plugin dispatch + event streaming. The recommended API.

### Continuation Detection

Detects incomplete input (`>>>` vs `...` prompts) for building REPL UIs.

Try the interactive REPL demo → | REPL documentation →

## Built-in Plugins

Host functions that Python code can call. All plugins work with both `ReplSession` and `AgentSession`.

### TemplatePlugin

Jinja2 template rendering. Variables, loops, conditionals, filters.

tmpl_render(template, context)

### MessageBusPlugin

In-memory named message channels. Send, receive, peek, stats.

msg_send · msg_recv · msg_peek · msg_close · msg_stats

### SandboxPlugin

Spawn isolated child interpreters. Parallel execution, gather, plugin inheritance, grandchildren.

sandbox_spawn · sandbox_await · sandbox_gather · sandbox_free

### OS / Filesystem

Configurable OS call providers for filesystem, time, and environment:

### In-Memory VFS

Read/write filesystem in memory. No host disk access.

### Read-Only Mount

Mount a host directory read-only into the sandbox.

### Overlay

Copy-on-write layer over a read-only base. Writes go to memory.

Plugin documentation → | Sandbox deep dive →

## Architecture

One package. Conditional imports select FFI or WASM at compile time.

dart_monty (single package) ├── lib/src/bridge/ Plugin dispatch, events, middleware dart_monty_core (backends) ├── FFI Native backend (dart:ffi) ├── WASM Web backend (dart:js_interop + Worker) ├── lib/src/repl/ REPL: MontyRepl, ReplSession, ReplPlatform └── native/ Rust C API crate (compiles to .dylib/.so/.dll + .wasm)

### Execution Paths

### Native (FFI)

Dart → dart:ffi → libdart_monty_native → Monty Rust interpreter

Desktop, server, mobile

### Web (WASM)

Dart/JS → js_interop → Web Worker → Monty WASM

Browser (any modern browser)

### Bridge & Events

`DefaultMontyBridge` orchestrates execution. Plugins register host functions. When Python calls one, execution suspends, the bridge dispatches to the handler, and resumes with the result. Every step emits `BridgeEvent`s for real-time UI updates.

Full architecture docs →

## Interactive Demos

All demos run in your browser via WebAssembly. No server required.

#### REPL

Interactive Python REPL with real plugins (template, message bus).

#### Basic Execution

One-shot Python execution, error handling, external functions.

#### Async/Sync Matrix

Six-cell walkthrough of the (Dart × Python) async matrix, including `useFutures: true`.

#### Virtual Filesystem

Python pathlib operations against in-memory VFS.

#### Agent Session

Stateful agent with plugins, telemetry, and event streaming.

#### Python Ladder

350+ compatibility tests across 21 tiers.

#### Sorting Visualizer

Step-by-step sorting algorithm animations in Python.

## Get Started

### Install

    dart pub add dart_monty

### Native (FFI)

Works out of the box on macOS, Linux, and Windows. The Rust native library is built automatically via Dart's native assets hook.

### Web (WASM)

Flutter consumers depend on both `dart_monty` and `dart_monty_core`, list `- package: dart_monty_core` under `flutter.assets`, and call `await DartMonty.ensureInitialized()` before first use. See the README for the full pattern.

Plain-Dart-web consumers copy the assets manually:

    cp dart_monty_core/assets/dart_monty_core_bridge.js web/
    cp dart_monty_core/assets/dart_monty_core_worker.js web/
    cp dart_monty_core/assets/dart_monty_core_native.wasm web/

Serve with `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` headers (required for SharedArrayBuffer).

### Documentation

- Overview — Quick start and API overview
- REPL Guide — Stateful interactive execution
- Plugins — Template, MessageBus, Sandbox
- Architecture — Module structure and internals
- Sandbox — Child spawning, grandchildren, limits
- Host Functions Guide — Writing custom plugins

>