omp packages

pi-modal-sandbox0.1.0

On-demand Modal serverless cloud backend, HTTPS port tunnels, persistent volumes, and parallel cloud subagents for Pi coding agent

onlyarthur Published 4 days ago MIT ~0 downloads/mo

Untested on omp

This is a pi package. No one has reported whether it works on omp yet. If you try it, add your result below.

Did it work for you?

Result

One report per person. A new report replaces your old one.

Reports 0

No reports yet.

Readme

pi-modal-sandbox

CI npm version

pi-modal-sandbox is a Pi coding agent package that offloads shell commands, full remote tool sessions, GPU workloads, HTTPS dev-server previews, and parallel autonomous subagents to on-demand Modal serverless sandboxes. It runs on Linux and macOS with zero idle compute cost via automatic filesystem snapshot hibernation.

Status: v0.1.0. Offline test suites run deterministically without Modal credentials; live sandbox execution requires a Modal account (modal setup).

Architecture

flowchart LR
  subgraph Host["User Workstation (Linux / macOS)"]
    PI["Pi Session + Local Extensions"]
    EXT["src/index.ts (pi-modal-sandbox)"]
    TEL["src/telemetry.ts (TUI Widget + Cost)"]
    CFG["~/.pi/agent/modal-backend.json + .pi/modal.json"]
    SUB["pi-subagents (modal-worker)"]
  end

  subgraph PyPkg["python/ (Shared Engine)"]
    CORE["pi_modal_core.py (Sync + Image + Guards + Providers)"]
    BR["bridge.py (NDJSON RPC Daemon)"]
    WK["worker.py (Headless Subagent)"]
  end

  subgraph Cloud["Modal Serverless Cloud"]
    SB["Modal gVisor Sandbox (CPU / RAM / GPU)"]
    TUN["HTTPS Port Tunnels (*.modal.host)"]
    VOL["Persistent Modal Volumes (/cache)"]
    SNAP["Filesystem Snapshot ($0 Idle)"]
  end

  PI --> EXT
  CFG --> EXT
  EXT --> TEL
  EXT -- "NDJSON RPC" --> BR
  PI --> SUB
  SUB -- "stdin" --> WK
  BR --> CORE
  WK --> CORE
  BR -- "Delta Tar / Exec" --> SB
  WK -- "Isolated Run" --> SB
  SB --> TUN
  SB <--> VOL
  SB -. "Hibernate / Hot-Swap" .-> SNAP
  • Pi extension (src/) — manages execution modes (off, bash, full), command routing, tool wrapping, live TUI widget/cost telemetry, /modal doctor, and collision-safe modal-worker registration. Spawns the Python bridge lazily only when Modal is used.
  • Shared Python engine (python/) — pi_modal_core.py holds workspace delta sync, security guards, deterministic container image layering, persistent volume validation, and multi-user cloud LLM provider discovery; bridge.py serves NDJSON RPC; worker.py runs headless Pi inside isolated Modal sandboxes.
  • Portable wrappers (bin/) — POSIX /bin/sh entrypoints (bin/pi-modal-bridge, bin/pi-modal-worker) resolve Python + modal across $PI_MODAL_PYTHON, repo .venv, uv tool install modal, which modal, uv run, and python3.
  • Snapshot hot-swap and hibernation — Modal fixes CPU, RAM, GPU, encrypted ports, and volumes at container creation. Live /modal scale, /modal gpu, /modal tunnel add, and /modal volume add calls snapshot the guest filesystem (snapshot_filesystem()), terminate the old container, and boot the replacement from that snapshot (~5s) so /workspace and /root persist. Idle containers automatically snapshot and terminate after idleTimeoutSec (default 600s, $0 idle).

Threat model and non-goals

pi-modal-sandbox isolates remote command execution inside Modal's gVisor sandboxes and separates local host credentials from cloud execution:

  • No direct host mount: workspace files move via filtered delta tarballs; the host filesystem is never directly mounted into the container.
  • Project config trust boundary: <project>/.pi/modal.json can configure compute resources, image packages, ports, volumes, routing rules, and workerModel, not syncDotEnv or allowHomeDirSync. Those two flags are stripped from project configs (and surfaced as a warning in /modal doctor) and honored only in user-global ~/.pi/agent/modal-backend.json, preventing an untrusted repository from silently enabling .env or $HOME exfiltration.
  • Sync and pull guards: blocks $HOME and / as workspace roots by default; excludes .env, .env.* (allowing .example/.sample/.test/.template), .dev.vars, .npmrc, .pypirc, .netrc, SSH keys, and *.pem; rejects .., absolute paths, and symlink escapes on pull-back.
  • Local-only credentialed commands: git push, git pull, git fetch, git remote, gh, ssh, scp, rsync, sudo, systemctl, journalctl, docker, podman, xdg-open, agent-browser, and modal route locally by default so host SSH keys and tokens do not need to enter the cloud container.

What pi-modal-sandbox does not protect against:

  • Host execution of synced-back artifacts: pi-modal-sandbox does not statically scan files pulled back from /workspace. If untrusted code in the sandbox modifies a build script, git hook, or source file and you execute it locally afterward, it runs with your host user's privileges.
  • Secrets explicitly placed in scope: commands inside the sandbox can read files synced into /workspace, data stored in attached Modal Volumes, static image.env values, and any LLM API key injected into a modal-worker container.
  • Locally routed commands: commands prefixed with @local or matched by localCommandPrefixes/localCommandRegexes run directly on your host with no sandbox boundary.
  • In-memory process persistence: hibernation and snapshot hot-swaps preserve filesystem state, not running process memory; background processes (such as dev servers) stop and must be restarted after a hot-swap or wake.

Requirements

  • Node.js >= 22.19.0
  • Pi coding agent (@earendil-works/pi-coding-agent >= 1.7.0)
  • Python >= 3.11 and uv (or another Python environment with modal>=0.73)
  • Linux or macOS
  • A Modal account configured via modal setup (or MODAL_TOKEN_ID + MODAL_TOKEN_SECRET)

Quickstart

  1. Install and authenticate the Modal CLI:
uv tool install modal
modal setup
  1. Install pi-modal-sandbox in Pi:
pi install npm:pi-modal-sandbox

Or install directly from GitHub:

pi install git:github.com/OnlyOneArthur/pi-modal-sandbox

To try pi-modal-sandbox from a local clone without changing your global Pi installation:

git clone https://github.com/OnlyOneArthur/pi-modal-sandbox.git
cd pi-modal-sandbox
pi --no-extensions -e .
  1. Verify the environment:
./bin/pi-modal-bridge --doctor

Or inside Pi, run /modal doctor.

  1. Enable cloud execution:
# Start Pi directly in hybrid bash mode
pi --modal bash

Or switch inside an existing session with /modal bash or /modal full.

Execution modes and routing

Mode File tools (read/write/edit/ls/find/grep) bash and ! Host extensions (ffgrep, lens_*, etc.)
off (default) Local Local Active
bash (hybrid) Local Modal /workspace (with delta push/pull) Active
full (remote) Modal /workspace Modal /workspace Host-FS-only tools hidden until leaving full

Override routing for any single bash or ! command with a leading directive:

@local git status
@modal pytest -q

#local and #modal work identically. Leading KEY=val assignments are stripped before matching localCommandPrefixes and localCommandRegexes.

/modal commands

Command Action
/modal off [pull|discard] Return to local mode (pull fetches guest diffs first; discard drops them)
/modal bash Switch to hybrid mode (file tools local, shell commands in Modal)
/modal full Switch to full remote mode (all 7 built-in tools in Modal /workspace)
/modal status Show mode, container state, specs, tunnels, volumes, uptime, and estimated cost
/modal widget [on|off] Toggle the 2-line TUI status widget
/modal doctor Run Python, Modal SDK, Modal auth, cloud provider, trust-boundary, and subagent diagnostics
/modal rules Display active localCommandPrefixes and localCommandRegexes
/modal scale <cpu> [memoryMb] Resize CPU and RAM (hot-swaps via filesystem snapshot if running)
/modal gpu <type|off> Attach or detach a GPU (T4, L4, A10G, L40S, A100-40GB, A100-80GB, H100, H200, B200, H100:2, or off)
/modal tunnel [list|add <port>|rm <port>] Manage encrypted HTTPS port tunnels (https://*.modal.host); hot-swaps if running
/modal volume [list|add <name>:<mountPath>|rm <mountPath>] Manage persistent Modal Volumes; / and /workspace are rejected
/modal push Push host workspace deltas to /workspace
/modal pull Pull guest /workspace changes back to the host
/modal hibernate Snapshot filesystem and terminate container ($0 idle)
/modal stop Terminate container and clear active snapshot

Configuration

Configuration merges in the following precedence order (later wins):

  1. Built-in defaults (defaultMode: "off", cpu: 4, memoryMb: 8192, gpu: null, sandboxTimeoutSec: 3600, idleTimeoutSec: 600, maxArchiveMb: 100, widget: true)
  2. Global user config: ~/.pi/agent/modal-backend.json (respects PI_CODING_AGENT_DIR)
  3. Project config: <project>/.pi/modal.json (syncDotEnv and allowHomeDirSync stripped)
  4. Environment overrides: PI_MODAL_MODE, PI_MODAL_CPU, PI_MODAL_MEMORY_MB, PI_MODAL_GPU
  5. Live session commands: /modal scale, /modal gpu, /modal tunnel, /modal volume, /modal widget

Example <project>/.pi/modal.json with JSON Schema validation (schema/modal.schema.json):

{
  "$schema": "./schema/modal.schema.json",
  "defaultMode": "off",
  "cpu": 8,
  "memoryMb": 16384,
  "gpu": null,
  "idleTimeoutSec": 600,
  "ports": [3000],
  "volumes": {
    "/cache/pip": "my-project-pip-cache"
  },
  "workerModel": "anthropic/claude-sonnet-4-5",
  "image": {
    "apt": ["ripgrep", "build-essential"],
    "pip": ["pytest", "ruff"],
    "npm": [],
    "commands": [],
    "env": {
      "PIP_CACHE_DIR": "/cache/pip"
    }
  },
  "localCommandRegexes": ["^terraform\\s+apply"]
}

Outside this repository, point "$schema" to https://raw.githubusercontent.com/OnlyOneArthur/pi-modal-sandbox/main/schema/modal.schema.json for VS Code, Zed, or Neovim autocomplete.

Parallel cloud subagents (modal-worker)

When pi-subagents is installed, pi-modal-sandbox registers a modal-worker runtime agent (pi-subagents:runtime-agent-register:v1) backed by bin/pi-modal-worker:

  • Collision guard: if ~/.pi/agent/agents/modal-worker.md or <project>/.pi/agents/modal-worker.md already exists, runtime registration is skipped automatically so custom user definitions win without duplicate-agent warnings.
  • Project inheritance: each worker loads <project>/.pi/modal.json (cpu, memoryMb, gpu, image, volumes, workerModel) and runs inside an isolated Modal container.
  • Multi-user cloud LLM discovery: pi_modal_core.py reads <PI_CODING_AGENT_DIR>/{settings,models,auth}.json plus standard provider env vars (ANTHROPIC_API_KEY, OPENAI_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY, DEEPSEEK_API_KEY, GROQ_API_KEY, XAI_API_KEY, MISTRAL_API_KEY), filters out unreachable loopback/local endpoints (localhost, 127.0.0.1, ::1, 0.0.0.0, .local), and selects the provider/model in order:
    1. PI_MODAL_PROVIDER / PI_MODAL_MODEL
    2. .pi/modal.json workerModel
    3. Active default provider from settings.json (if cloud-reachable)
    4. First authenticated cloud provider

Telemetry and cost estimation

When mode is bash or full and the widget is enabled (/modal widget on), pi-modal-sandbox renders a compact footer status and a 2-line TUI widget showing mode, container state, CPU/RAM/GPU allocation, active operation, live tunnel URLs, active uptime, and approximate session spend (~$0.0000).

Cost estimation accumulates only while state === "running" (paused when cold or hibernated) and segments rates across mid-session /modal scale and /modal gpu hot-swaps using published Modal per-second CPU, memory, and GPU rates. Figures are estimates, not authoritative billing invoices.

Development and testing

Offline checks require no Modal account or cloud credentials; the Python suite uses PI_MODAL_BACKEND=local-exec to exercise delta sync, fs_op, SIGTERM cancellation, hibernation, and hot-swap behavior deterministically:

npm ci
uv sync --locked --extra dev
npm run test

Individual checks:

npm run typecheck    # tsc --noEmit
npm run test:ts      # node --experimental-strip-types --test tests/ts/*.test.ts
npm run lint:py      # uv run --extra dev ruff check python tests/python
npm run test:py      # uv run --extra dev pytest
npm run doctor       # ./bin/pi-modal-bridge --doctor

Live Modal cloud end-to-end smoke test (boots a real sandbox, hot-adds HTTPS tunnel port 8765 and CPU scaling, fetches HTTP 200 through *.modal.host, and verifies clean shutdown):

uv run --extra dev python tests/python/live_smoke.py
modal container list

License

MIT