# AgentPaaS

**Agent Platform as a Service** — wraps [lambdagent](../lambdagent/) into a production-grade platform.

[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](../LICENSE)
[![Tests](https://img.shields.io/badge/tests-70%20passed-brightgreen.svg)]()

**Stats**: 50 Python files | 2,000+ lines | 28 REST endpoints | 7 LLM providers built-in

## Architecture

```
┌─────────────────────────────────────────────────────┐
│                     AgentPaaS                       │
│                                                     │
│  ┌─────────┐ ┌──────────┐ ┌───────┐ ┌───────────┐  │
│  │ Gateway  │ │ Registry │ │Engine │ │   CLI     │  │
│  │ Auth/Rate│ │ Version  │ │Queue  │ │ Provider  │  │
│  │ Limit   │ │ Traffic  │ │Sandbox│ │ Mgmt      │  │
│  └────┬────┘ └────┬─────┘ └───┬───┘ └───────────┘  │
│       │           │           │                     │
│  ┌────▼───────────▼───────────▼──────────────────┐  │
│  │         Tenant / Billing / Secrets / Metrics   │  │
│  └───────────────────┬───────────────────────────┘  │
│                      │                              │
├──────────────────────┼──────────────────────────────┤
│                      ▼                              │
│  ┌───────────────────────────────────────────────┐  │
│  │              lambdagent (kernel)               │  │
│  │  from_config · Runtime · Executor · Context    │  │
│  └───────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────┘
```

## Quick Start

```bash
# Install
pip install fastapi uvicorn pyyaml

# Start server (dev mode, SQLite)
python -m agentpaas serve --dev

# Create a tenant + get API key
python -m agentpaas create-tenant --name "My Org"
# → API Key: ap_xxxxxxxxxxxxxxxx
```

### Create & Run an Agent

```bash
# Create agent
curl -X POST http://localhost:8000/api/v1/agents \
  -H "Authorization: Bearer ap_xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "assistant",
    "config": {
      "type": "simple",
      "systemPrompt": "You are a helpful assistant.",
      "model": {"provider": "dashscope", "name": "qwen3-max"}
    }
  }'

# Run agent
curl -X POST http://localhost:8000/api/v1/agents/ag_xxx/run \
  -H "Authorization: Bearer ap_xxx" \
  -d '{"input": "Hello!"}'
```

### LLM Provider Management

```bash
# List all providers (7 built-in)
python -m agentpaas provider list

# Add API key for a provider
python -m agentpaas provider add dashscope --api-key sk-xxx

# Test provider connection
python -m agentpaas provider test dashscope --prompt "Say hello"

# Add custom OpenAI-compatible provider
python -m agentpaas provider add my-llm \
  --name "My LLM" \
  --base-url https://my-llm.com/v1 \
  --api-key xxx \
  --models "model-a,model-b"

# List available models
python -m agentpaas provider models dashscope
```

**Built-in Providers**: Anthropic (Claude), OpenAI (GPT), DashScope (Qwen), DeepSeek, Zhipu AI (GLM), Moonshot (Kimi), Ollama (local)

## API Endpoints (28 routes)

### Agent Management
| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/agents` | Create agent |
| GET | `/api/v1/agents` | List agents |
| GET | `/api/v1/agents/{id}` | Get agent |
| PUT | `/api/v1/agents/{id}` | Update (auto-version) |
| DELETE | `/api/v1/agents/{id}` | Soft delete |
| POST | `/api/v1/agents/{id}/rollback` | Rollback version |
| GET | `/api/v1/agents/{id}/versions` | Version history |

### Execution
| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/agents/{id}/run` | Synchronous execution |
| GET | `/api/v1/agents/{id}/runs` | Execution history |
| GET | `/api/v1/jobs/{id}` | Async job status |
| POST | `/api/v1/jobs/{id}/cancel` | Cancel job |

### Auth & Admin
| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/v1/auth/keys` | Create API key |
| GET | `/api/v1/auth/keys` | List keys |
| DELETE | `/api/v1/auth/keys/{id}` | Revoke key |
| POST | `/api/v1/admin/tenants` | Create tenant |
| PUT | `/api/v1/admin/tenants/{id}/quota` | Set quota |
| GET | `/api/v1/admin/tenants/{id}/usage` | Usage stats |

### Observability & Billing
| Method | Path | Description |
|--------|------|-------------|
| GET | `/api/v1/traces/{run_id}` | Execution trace |
| GET | `/api/v1/billing/usage` | Usage report |
| GET | `/api/v1/metrics/overview` | Platform metrics |
| GET | `/.well-known/agent.json` | A2A discovery |
| GET | `/health` | Health check |

Full OpenAPI docs at: `http://localhost:8000/docs`

## Module Structure

```
agentpaas/
├── api/                    # FastAPI routes + middleware
│   ├── app.py              #   Application entry (28 routes)
│   ├── deps.py             #   Dependency injection
│   ├── middleware/
│   │   └── auth.py         #   API Key auth (SHA-256)
│   └── v1/
│       ├── agents.py       #   CRUD + /run execution
│       ├── jobs.py         #   Async job management
│       ├── auth.py         #   API Key management
│       ├── admin.py        #   Tenant management
│       ├── billing.py      #   Usage queries
│       ├── traces.py       #   Execution traces
│       ├── metrics.py      #   Platform metrics
│       └── discovery.py    #   A2A agent discovery
├── engine/                 # Execution engine
│   ├── dispatcher.py       #   Sync/async/stream dispatch
│   ├── queue.py            #   Job queue (memory + Redis)
│   ├── sandbox.py          #   L0 in-process / L1 subprocess
│   ├── worker.py           #   Background job consumer
│   ├── cache.py            #   Compile cache (LRU)
│   ├── retry.py            #   Retry + circuit breaker
│   └── stream.py           #   SSE + WebSocket adapters
├── registry/               # Agent registry
│   ├── store.py            #   CRUD + search
│   ├── version.py          #   Version management + rollback
│   ├── traffic.py          #   Canary weighted routing
│   └── discovery.py        #   A2A Agent Card
├── tenant/                 # Multi-tenancy
│   ├── quota.py            #   Token quota + concurrency
│   ├── rbac.py             #   Admin / Developer / Viewer
│   └── isolation.py        #   Data isolation
├── observability/          # Observability
│   ├── logging.py          #   Structured JSON logging
│   ├── metrics.py          #   Prometheus-style metrics
│   └── tracing.py          #   lambdagent trace bridge
├── secrets/                # Secret management
│   ├── vault.py            #   AES-256-GCM encryption
│   └── inject.py           #   Env var injection
├── billing/                # Billing
│   ├── metering.py         #   Token usage recording
│   ├── pricing.py          #   Per-model pricing (6 models)
│   └── report.py           #   Monthly reports
├── db/                     # Data layer
│   ├── models.py           #   7 tables (SQLite → PostgreSQL)
│   └── session.py          #   Connection management
├── cli/
│   └── main.py             #   CLI: serve, create-tenant, provider mgmt
├── config.py               #   Global config (env vars)
├── Dockerfile
├── docker-compose.yml
└── pyproject.toml
```

## Design Principles

| # | Principle | Description |
|---|-----------|-------------|
| P1 | **Kernel zero-invasion** | AgentPaaS only calls lambdagent public API |
| P2 | **API First** | All features via REST; Dashboard + CLI are API consumers |
| P3 | **Progressive complexity** | SQLite + memory queue for dev; PostgreSQL + Redis for prod |
| P4 | **Formal traceability** | Preserves lambdagent β-reduction trace + OTel distributed trace |
| P5 | **Open protocols** | Native MCP, A2A support |
| P6 | **Secure by default** | Encrypted secrets, RBAC, audit trail |

## Deployment

### Development (single process)
```bash
python -m agentpaas serve --dev    # SQLite, in-memory queue, L0 sandbox
```

### Docker Compose
```bash
docker-compose up                  # PostgreSQL + Redis + API + Worker
```

### Kubernetes
- HPA on API pods (CPU > 60%)
- HPA on Worker pods (queue depth > 10)
- Helm chart in `deploy/`

## Testing

```bash
python -m pytest tests/ -v        # 70 tests, < 0.3s
```

## License

MIT — see [LICENSE](../LICENSE)
