Pi SoloHost AI CostGuard
by xgbtxy
README.md
# Pi SoloHost AI CostGuard & x402 Compute Router
> **Self-hosted AI cost comparator, 80/20 hybrid LLM compute router, local monthly spend redline guard, Streamable HTTP MCP server, Pi SDK Testnet integration, and x402 HTTP 402 compute metering sandbox — packaged natively for Pi Desktop SoloHost.**
- **Live Static Preview (GitHub Pages):** [https://xgbtxy.github.io/pi-solohost-costguard/](https://xgbtxy.github.io/pi-solohost-costguard/)
- **Privacy Policy:** [https://xgbtxy.github.io/pi-solohost-costguard/privacy.html](https://xgbtxy.github.io/pi-solohost-costguard/privacy.html)
- **PiNet Metadata JSON:** [https://xgbtxy.github.io/pi-solohost-costguard/pinet-metadata.json](https://xgbtxy.github.io/pi-solohost-costguard/pinet-metadata.json)
- **Container Image (GHCR):** `ghcr.io/xgbtxy/pi-solohost-costguard:1.0.0` (`linux/amd64`, `linux/arm64`)
- **Pi SoloHost Package Files:** [`solohost/docker-compose.yml`](./solohost/docker-compose.yml) & [`solohost/config_options.yml`](./solohost/config_options.yml) *(verified `ok: true` against Pi's official SoloHost staging validator)*
---
## Why This Matters for 420K+ Pi Desktop Node Operators & AI Builders
AI developers and node operators routinely overpay 4x–10x on LLM API bills by sending routine classification, summarization, and extraction requests to flagship frontier models. **AI CostGuard** runs locally inside **Pi Desktop SoloHost** (`127.0.0.1:18080`, zero external dependencies, zero tracking, zero secret leakage) to solve four concrete problems in one container:
1. **12 Official LLM API Cost Comparator:** Real-time per-request, monthly, and annual USD comparison across 12 official public API models (OpenAI, Anthropic, Google, DeepSeek, Mistral), factoring in prompt-cache discounts.
2. **80/20 Hybrid Compute Router:** Calculates exact monthly/annual USD savings for Hybrid 80/20, Ultra-Frugal 90/10, and Frontier-First 30/70 policies, generating a concrete task-tier routing specification.
3. **Local Spend Redline Guard (`/data/state.json`):** Enforces operator-configured monthly USD spend ceilings (`OK` / `WARNING` / `BREACH`) and computes automatic hybrid downshift fallbacks whenever projected burn exceeds budget.
4. **Native MCP + Pi SDK + x402 Stack:**
- **Streamable HTTP MCP Server (`POST /mcp`):** Exposes `estimate_llm_cost`, `optimize_hybrid_route`, and `check_budget_redline` to any MCP-compatible AI agent.
- **Pi SDK 3-Phase Testnet Payments:** Integrates `Pi.init`, `Pi.authenticate`, `Pi.createPayment` with server-side `POST /api/pi/approve` and `POST /api/pi/complete` (relays to `https://api.minepi.com/v2/payments` when `PI_API_KEY` is configured, or runs safely in zero-key Testnet simulation mode when blank).
- **x402 Programmatic Compute Metering (`POST /api/x402/route-audit`):** Returns a standards-compliant HTTP `402 Payment Required` challenge with base64 `PAYMENT-REQUIRED` header (Base Sepolia `eip155:84532` / Base Mainnet `eip155:8453`, public `payTo` only, zero private keys) and an instant free preview at `?sample=true`.
---
## Architecture
```mermaid
flowchart LR
Op["Pi Desktop / Pi Browser Operator"] -->|"127.0.0.1:18080 (SoloHost)"| Web["CostGuard Server (Node 20 ESM, zero deps)"]
Agent["Local AI Agent / IDE"] -->|"POST /mcp (JSON-RPC 2.0)"| Web
X402["Programmatic x402 Client"] -->|"POST /api/x402/route-audit (402 / 200)"| Web
Web -->|"Persist policy & audits"| Vol[("Named Volume /data/state.json")]
Web -.->|"Optional when PI_API_KEY set"| PiAPI["https://api.minepi.com/v2/payments"]
```
---
## 1-Click Pi SoloHost Deployment
1. Open **Pi Desktop SoloHost** (or SoloHost Publisher).
2. Paste [`solohost/docker-compose.yml`](./solohost/docker-compose.yml) and [`solohost/config_options.yml`](./solohost/config_options.yml).
3. Configure your local loopback port (`18080`), monthly USD budget redline (`25`), default routing profile (`hybrid_80_20`), and optional `PI_API_KEY` (leave blank to start immediately in zero-key Testnet simulation mode).
4. Click **Install & Launch** — Pi Desktop pulls `ghcr.io/xgbtxy/pi-solohost-costguard:1.0.0`, starts the container on `127.0.0.1:18080`, verifies `/health`, and embeds the UI directly in the App tab.
### Reproducible Live SoloHost Validation
Verify the package directly against Pi's official authoritative staging validator:
```bash
npm run validate:solohost
# Or also preview the exact generated .env file:
node scripts/validate-solohost.mjs --preview-env
```
---
## Local Standalone Quickstart (Zero `npm install` Needed)
Requires **Node.js 20+**.
```bash
git clone https://github.com/xgbtxy/pi-solohost-costguard.git
cd pi-solohost-costguard
cp .env.example .env
npm start
# Open http://127.0.0.1:8080
```
Run the full automated test suite:
```bash
npm test
```
---
## MCP Client Configuration
Connect any Streamable HTTP MCP client (Claude Desktop bridge, Cursor, Windsurf, custom agents) to your running SoloHost instance:
```json
{
"mcpServers": {
"pi-solohost-costguard": {
"transport": "streamable-http",
"url": "http://127.0.0.1:18080/mcp"
}
}
}
```
Quick curl smoke test:
```bash
curl -s -X POST http://127.0.0.1:8080/mcp \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
```
---
## x402 HTTP 402 Metering Demo
```bash
# 1. Inspect the standards-compliant HTTP 402 challenge & PAYMENT-REQUIRED header:
curl -i -X POST http://127.0.0.1:8080/api/x402/route-audit \
-H "Content-Type: application/json" \
-d '{"requestsPerMonth":10000,"monthlyBudgetUsd":25}'
# 2. Fetch a free live 12-model routing audit preview (HTTP 200):
curl -s -X POST "http://127.0.0.1:8080/api/x402/route-audit?sample=true" \
-H "Content-Type: application/json" \
-d '{"requestsPerMonth":10000,"monthlyBudgetUsd":25}'
```
---
## Security & Privacy Guarantees
- **Zero runtime npm dependencies** — dramatically reduces supply-chain attack surface.
- **Non-root container (`USER node`)** on `node:20-alpine` with loopback-only host binding (`127.0.0.1:${PORT:-18080}:8080`), no privileged flags, no host bind mounts, and bare named volume persistence (`costguard_data:/data`).
- **Zero private keys** — x402 endpoints use only public recipient address metadata (`X402_PAY_TO`).
- **Strict secret isolation** — optional `PI_API_KEY` stays server-side (`preserve_if_blank: true` in `config_options.yml`) and is never serialized to browser HTML, `/health`, or `/api/config`.
- **`PI_OPERATOR_HANDLE` (`detect: pi_username`)** is strictly for optional local attribution/display and is never used for authentication, ownership, or access control.
---
## License
[MIT](./LICENSE)