pi-modal-sandbox0.1.0
On-demand Modal serverless cloud backend, HTTPS port tunnels, persistent volumes, and parallel cloud subagents for Pi coding agent
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.
Reports 0
No reports yet.
Readme
pi-modal-sandbox
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-safemodal-workerregistration. Spawns the Python bridge lazily only when Modal is used. - Shared Python engine (
python/) —pi_modal_core.pyholds workspace delta sync, security guards, deterministic container image layering, persistent volume validation, and multi-user cloud LLM provider discovery;bridge.pyserves NDJSON RPC;worker.pyruns headless Pi inside isolated Modal sandboxes. - Portable wrappers (
bin/) — POSIX/bin/shentrypoints (bin/pi-modal-bridge,bin/pi-modal-worker) resolve Python +modalacross$PI_MODAL_PYTHON, repo.venv,uv tool install modal,which modal,uv run, andpython3. - 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 addcalls snapshot the guest filesystem (snapshot_filesystem()), terminate the old container, and boot the replacement from that snapshot (~5s) so/workspaceand/rootpersist. Idle containers automatically snapshot and terminate afteridleTimeoutSec(default600s,$0idle).
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.jsoncan configure compute resources, image packages, ports, volumes, routing rules, andworkerModel, notsyncDotEnvorallowHomeDirSync. 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.envor$HOMEexfiltration. - Sync and pull guards: blocks
$HOMEand/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, andmodalroute 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-sandboxdoes 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, staticimage.envvalues, and any LLM API key injected into amodal-workercontainer. - Locally routed commands: commands prefixed with
@localor matched bylocalCommandPrefixes/localCommandRegexesrun 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.11anduv(or another Python environment withmodal>=0.73) - Linux or macOS
- A Modal account configured via
modal setup(orMODAL_TOKEN_ID+MODAL_TOKEN_SECRET)
Quickstart
- Install and authenticate the Modal CLI:
uv tool install modal
modal setup
- Install
pi-modal-sandboxin 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 .
- Verify the environment:
./bin/pi-modal-bridge --doctor
Or inside Pi, run /modal doctor.
- 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):
- Built-in defaults (
defaultMode: "off",cpu: 4,memoryMb: 8192,gpu: null,sandboxTimeoutSec: 3600,idleTimeoutSec: 600,maxArchiveMb: 100,widget: true) - Global user config:
~/.pi/agent/modal-backend.json(respectsPI_CODING_AGENT_DIR) - Project config:
<project>/.pi/modal.json(syncDotEnvandallowHomeDirSyncstripped) - Environment overrides:
PI_MODAL_MODE,PI_MODAL_CPU,PI_MODAL_MEMORY_MB,PI_MODAL_GPU - 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.mdor<project>/.pi/agents/modal-worker.mdalready 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.pyreads<PI_CODING_AGENT_DIR>/{settings,models,auth}.jsonplus 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:PI_MODAL_PROVIDER/PI_MODAL_MODEL.pi/modal.jsonworkerModel- Active default provider from
settings.json(if cloud-reachable) - 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