Metadata-Version: 2.4
Name: pop-pay
Version: 0.5.0
Summary: Point One Percent - Semantic Payment Guardrail for AI Agents. it only takes 0.1% of Hallucination to drain 100% of your wallet.
Author: Point One Percent Team
License: MIT
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: pydantic
Requires-Dist: python-dotenv
Provides-Extra: all
Requires-Dist: langchain-core; extra == 'all'
Requires-Dist: mcp>=1.26.0; extra == 'all'
Requires-Dist: openai; extra == 'all'
Requires-Dist: playwright>=1.40.0; extra == 'all'
Requires-Dist: streamlit>=1.55.0; extra == 'all'
Requires-Dist: stripe; extra == 'all'
Requires-Dist: tenacity>=9.1.4; extra == 'all'
Provides-Extra: browser
Requires-Dist: playwright>=1.40.0; extra == 'browser'
Provides-Extra: dashboard
Requires-Dist: streamlit>=1.55.0; extra == 'dashboard'
Provides-Extra: dev
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-asyncio; extra == 'dev'
Provides-Extra: langchain
Requires-Dist: langchain-core; extra == 'langchain'
Provides-Extra: llm
Requires-Dist: openai; extra == 'llm'
Requires-Dist: tenacity>=9.1.4; extra == 'llm'
Provides-Extra: mcp
Requires-Dist: mcp>=1.26.0; extra == 'mcp'
Provides-Extra: stripe
Requires-Dist: stripe; extra == 'stripe'
Description-Content-Type: text/markdown

<p align="center">
    <picture>
        <img src="https://raw.githubusercontent.com/TPEmist/project-aegis/main/project_banner.png" alt="Project Aegis (AgentPay)" width="800">
    </picture>
</p>

# Project Aegis - AgentPay

> **Note**: This is the PyPI published documentation. For the full architecture diagrams, real UI screenshots, and the **Chinese translation (繁體中文版)**, please visit the [GitHub Repository](https://github.com/TPEmist/project-aegis).

Project Aegis is a payment guardrail and one-time flow protocol specifically designed for Agentic AI (e.g., OpenClaw, NemoClaw, Claude Code, OpenHands). It enables agents to handle financial transactions safely without risking unlimited exposure of human-controlled credit cards.

## 1. The Problem
When Agentic AI encounters a paywall (e.g., domain registration, API credits, compute scaling) during an automated workflow, it is often forced to stop and wait for human intervention. However, providing a physical credit card directly to an agent introduces a "trust crisis": hallucinations or infinite loops could lead to the card being drained.

## 2. Dual Architecture

Project Aegis is designed with a "Dual Architecture" vision to scale from open-source local experiments to enterprise-grade AI production pipelines.

### 1. Hacker Edition (BYOC + DOM Injection)
Built for open-source frameworks like OpenClaw and NemoClaw. The agent **never** receives the true credit card number—it only sees a masked version (\`****-4242\`). When the agent successfully navigates to a checkout paywall, the Aegis \`AegisBrowserInjector\` attaches to the active Chromium browser via the Chrome DevTools Protocol (CDP). It precisely traverses all cross-origin iframes (like Stripe Elements) and injects the real credentials deep into the DOM form elements, delivering **100% protection against prompt injection** or hallucination-driven extractions. Bring Your Own Card (BYOC) locally with absolute peace of mind.

### 2. Enterprise Edition (Stripe Issuing)
The "North Star" for the broader Agentic SaaS ecosystem. Proving that Aegis has the enterprise-grade extensibility required for the real world, it seamlessly connects to verified financial infrastructure. Perfect for platforms building "Agentic Visa" services that programmatically issue real, single-use, burner virtual credit cards (VCCs) via the Stripe API for cloud-hosted AI fleets.

---

## 3. Ecosystem Position: Aegis + Browser Agents = Unstoppable

Modern agentic workflows require two complementary capabilities. Aegis does one, and does it exceptionally well.

### 🎯 What Aegis Is — and Isn't

**Aegis is the agent's financial brain and safe vault.** It is responsible for:
- ✅ Evaluating whether a purchase *should* happen (semantic guardrails)
- ✅ Enforcing hard budget limits (daily cap, per-transaction cap)
- ✅ Issuing one-time virtual cards so real credentials are never exposed
- ✅ Maintaining a full audit trail of every payment attempt

**Aegis does NOT:**
- ❌ Navigate websites or interact with DOM elements
- ❌ Solve CAPTCHAs or bypass bot-detection systems
- ❌ Fill out forms or click "Submit" on behalf of the agent

That's the browser agent's job.

### 🤝 The Handshake: How Aegis and Browser Agents Work Together

The real power emerges when Aegis is paired with a browser automation agent (e.g., OpenHands, browser-use, Skyvern). The workflow is a clean division of labor:

```
1. [Browser Agent]  Navigates to a site, scrapes product info, reaches checkout.
        │
        │  (Hit a paywall / payment form)
        ▼
2. [Browser Agent → Aegis MCP]  Calls request_virtual_card(amount, vendor, reasoning)
        │
        │  (Aegis evaluates: budget OK? vendor approved? no hallucination?)
        ▼
3. [Aegis]  Issues a one-time virtual card (Stripe mode) or mock card (dev mode)
            Returns masked card number to agent. Full card injected only via
            trusted local execution environment — never into the LLM's context.
        │
        ▼
4. [Browser Agent]  Uses the approved credentials to complete the checkout form.
        │
        ▼
5. [The Vault]  Dashboard logs the transaction. Card is immediately burned.
```

### 🌐 Supported Browser Agent Integrations

| Browser Agent | Integration Method | Guide |
|---|---|---|
| **OpenHands** | MCP Tool Call | [Quick Start §5](#5-quick-start-for-openclaw--nemoclaw--claude-code--openhands) |
| **OpenClaw + browser-use** | MCP Tool Call | [Quick Start §5](#5-quick-start-for-openclaw--nemoclaw--claude-code--openhands) |
| **NemoClaw (sandboxed)** | MCP Tool Call inside sandbox | [Quick Start §5](#5-quick-start-for-openclaw--nemoclaw--claude-code--openhands) |
| **Claude Code + Playwright MCP** | Aegis MCP + CDP injection | [Integration Guide §4](./docs/INTEGRATION_GUIDE.md#4-claude-code--full-setup-with-cdp-injection) |
| **Custom Playwright / Selenium** | Python SDK `AegisClient` | [Integration Guide](./docs/INTEGRATION_GUIDE.md) |
| **Skyvern / browser-use** | Python SDK middleware | [Integration Guide](./docs/INTEGRATION_GUIDE.md) |

> See **[docs/INTEGRATION_GUIDE.md](./docs/INTEGRATION_GUIDE.md)** for end-to-end code examples including Playwright injection and System Prompt templates.

---

## 4. Installation

```bash
# Core only (keyword guardrail + mock provider, zero external dependencies)
pip install aegis-pay

# With LLM-based guardrails (supports OpenAI, Ollama, vLLM, OpenRouter)
pip install aegis-pay[llm]

# With Stripe virtual card issuing
pip install aegis-pay[stripe]

# With LangChain integration
pip install aegis-pay[langchain]

# Full installation (all features)
pip install aegis-pay[all]
```

## 5. Quick Start for OpenClaw / NemoClaw / Claude Code / OpenHands

If you're using OpenClaw, NemoClaw, Claude Code, OpenHands, or any MCP-compatible agentic framework, you can get Aegis running in under 2 minutes:

### Step 1: Install & Start MCP Server

```bash
# Clone the repo
git clone https://github.com/TPEmist/Project-Aegis.git
cd Project-Aegis

# Install dependencies
uv sync --all-extras

# Start the MCP server
uv run python -m aegis.mcp_server
```

### Step 2: Connect to Your Agent

**OpenClaw:**
```bash
# Register Aegis as an MCP tool in OpenClaw
openclaw mcp add aegis -- uv run python -m aegis.mcp_server

# Or add to your OpenClaw MCP config file (~/.openclaw/mcp_servers.json)
```
```json
{
  "aegis": {
    "command": "uv",
    "args": ["run", "python", "-m", "aegis.mcp_server"],
    "cwd": "/path/to/Project-Aegis",
    "env": {
      "AEGIS_ALLOWED_CATEGORIES": "[\"aws\", \"cloudflare\", \"openai\"]",
      "AEGIS_MAX_PER_TX": "100.0",
      "AEGIS_MAX_DAILY": "500.0"
    }
  }
}
```

**NemoClaw (NVIDIA sandbox):**

NemoClaw wraps OpenClaw agents in a secure sandbox. Configure Aegis inside your NemoClaw sandbox by editing the MCP config within the sandbox environment:

```bash
# Connect to your NemoClaw sandbox
nemoclaw my-assistant connect

# Inside the sandbox, register the Aegis MCP server
openclaw mcp add aegis -- uv run python -m aegis.mcp_server
```

> **Note:** NemoClaw restricts file access. Make sure Project-Aegis is cloned inside `/sandbox/` so the agent can access it. The `aegis_state.db` will be created in the sandbox's writable directory.

**Claude Code (Hacker Edition / BYOC — Full Setup):**

Claude Code requires three components to enable live CDP card injection. Playwright MCP navigates websites while Aegis injects real card credentials into the same browser window — the card number never enters AI context.

**Step 0 — Launch Chrome with CDP (required every session, must be done first):**
```bash
# macOS
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" \
  --remote-debugging-port=9222 \
  --user-data-dir=/tmp/chrome-aegis-profile

# Linux
google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/chrome-aegis-profile
```
> `--user-data-dir` is required if Chrome is already running — it opens a separate instance with CDP enabled.
> Verify: `curl http://localhost:9222/json/version`

**Step 1 — Configure `.env` (copy from `.env.example`):**
```bash
cp .env.example .env
# Edit .env: set AEGIS_BYOC_NUMBER, AEGIS_BYOC_CVV, AEGIS_BYOC_EXPIRY, etc.
```

**Step 2 — Add Aegis MCP to Claude Code:**
```bash
claude mcp add aegis -- uv run --project /path/to/Project-Aegis python -m aegis.mcp_server
```

**Step 3 — Add Playwright MCP (connected to the same Chrome via CDP):**
```bash
claude mcp add playwright -- npx @playwright/mcp@latest --cdp-endpoint http://localhost:9222
```

**Architecture:**
```
Chrome (--remote-debugging-port=9222)
├── Playwright MCP  ──→ agent uses for navigation
└── Aegis MCP       ──→ injects real card via CDP
         │
         └── Claude Code Agent (only sees ****-****-****-4242)
```

**Recommended System Prompt addition:**
```
Payment rules:
- Only call request_virtual_card when you can see credit card input fields on the current page
- After approval, the system auto-fills the card — just click submit
- Never manually type any card number or CVV
- If request_virtual_card is rejected, do not retry — report to user
```

> See **[docs/INTEGRATION_GUIDE.md §4](./docs/INTEGRATION_GUIDE.md#4-claude-code--full-setup-with-cdp-injection)** for the full step-by-step guide including shell aliases.

**OpenHands:** Add to your MCP configuration:
```json
{
  "mcpServers": {
    "aegis": {
      "command": "uv",
      "args": ["run", "python", "-m", "aegis.mcp_server"],
      "cwd": "/path/to/Project-Aegis"
    }
  }
}
```

### Step 3: Configure Your Policy (Environment Variables)

```bash
export AEGIS_ALLOWED_CATEGORIES='["aws", "cloudflare", "openai", "github"]'
export AEGIS_MAX_PER_TX=100.0        # Max $100 per single transaction
export AEGIS_MAX_DAILY=500.0         # Max $500 per day total
export AEGIS_BLOCK_LOOPS=true        # Block hallucination/retry loops
# Optional: Enable LLM Guardrails (replaces default keyword setup)
export AEGIS_GUARDRAIL_ENGINE=llm    # 'keyword' or 'llm'
export AEGIS_LLM_API_KEY=sk-...      # required if using OpenAI
# export AEGIS_LLM_BASE_URL=http://localhost:11434/v1  # For Ollama
# export AEGIS_LLM_MODEL=llama3.2
# Optional: export AEGIS_STRIPE_KEY=sk_live_... (see §8 for Stripe setup)
```

### Step 4: Use It

Your agent now has access to the `request_virtual_card` tool. When it encounters a paywall:

```
Agent: "I need to purchase an API key from AWS for $15 to continue."
[Tool Call] request_virtual_card(amount=15.0, vendor="AWS", reasoning="Need API key for deployment")
[Aegis] ✅ Payment approved. Card Issued: ****4242, Expiry: 12/25, Amount: 15.0
Agent: "Purchase successful, continuing workflow."
```

If the agent hallucinates or tries to overspend:
```
Agent: "Let me retry buying compute... the previous attempt failed again."
[Tool Call] request_virtual_card(amount=50.0, vendor="AWS", reasoning="failed again, retry loop")
[Aegis] ❌ Payment rejected. Reason: Hallucination or infinite loop detected in reasoning
```

---

## 6. Core Components

### 🛡️ The Vault
A local visualization console powered by **Streamlit** and **SQLite** (`aegis_state.db`). The Vault allows humans to:
- Monitor all issued seals and agent spending activity in real-time.
- Monitor global budget utilization.
- Audit rejection logs from semantic guardrails.

### 📜 The Seal
Virtual, single-use payment credentials with built-in enforcement:
- **Daily Budget Limit Enforcement**: Automatically blocks any request that would exceed the predefined daily spending cap.
- **Burn-after-use Interception**: Ensures that once a virtual card is used, it is immediately invalidated, preventing replay attacks or unauthorized recurring charges.

### 🧠 Semantic Guardrails
Aegis provides two modes of intent evaluation to prevent agents from wasting funds:
1. **Fast Keyword-based Interception** (Default): Uses the `GuardrailEngine` to immediately block requests containing keywords associated with loops or hallucinations (e.g., "retry", "failed again", "ignore previous"). Zero dependencies, zero cost.
2. **LLM-based Guardrail Engine**: Powered by the `LLMGuardrailEngine`, this mode performs deep semantic analysis of the agent's reasoning to detect unrelated purchases or logical inconsistencies. Supports **any OpenAI-compatible endpoint** — including local models via Ollama/vLLM, or cloud providers like OpenAI and OpenRouter.

## 7. Security Statement
Security is a first-class citizen in Aegis. The SDK **masks card numbers by default** (e.g., `****-****-****-4242`) when returning authorization results to the agent. This prevents sensitive payment information from leaking into agent chat logs, model context windows, or persistent logs, ensuring that only the execution environment handles the raw credentials.

## 8. The Vault Dashboard

The Vault is your real-time monitoring console for all agent payment activity. 

### Starting the Dashboard

```bash
cd Project-Aegis
uv run streamlit run dashboard/app.py
# Dashboard opens at http://localhost:8501
```

### Dashboard Layout

| Section | Description |
|---|---|
| **Sidebar: Max Daily Budget slider** | Adjust the displayed budget cap for visualization (does not affect backend policy — backend policy is configured via env vars or SDK) |
| **Today's Spending** | Total amount spent by agents today |
| **Remaining Budget** | How much budget is left for the day |
| **Budget Utilization** | Visual progress bar showing spend % |
| **💳 Issued Seals & Activity** | Full table of all payment attempts (approved + rejected) with seal ID, amount, vendor, status, and timestamp |
| **🚫 Rejected Summary** | Filtered view showing only rejected/blocked attempts for quick auditing |

### Tips
- Click **Refresh Data** in the sidebar to pull latest activity from the database.
- The dashboard reads from `aegis_state.db` — the same database the SDK writes to. Keep both running simultaneously for live monitoring.
- Each row in the table corresponds to a single `request_virtual_card` call from an agent.

---

## 9. Python SDK Quickstart

Integrate Aegis into your custom Python or LangChain workflows in just a few lines:

```python
from aegis.client import AegisClient
from aegis.providers.stripe_mock import MockStripeProvider
from aegis.core.models import GuardrailPolicy

# Define your safety policy
policy = GuardrailPolicy(
    allowed_categories=["API", "Cloud", "SaaS"], 
    max_amount_per_tx=50.0, 
    max_daily_budget=200.0,
    block_hallucination_loops=True
)

# Initialize the client with keyword-only guardrails (default)
client = AegisClient(
    provider=MockStripeProvider(), 
    policy=policy,
    db_path="aegis_state.db"
)

# Or use LLM-based guardrails with a local model (e.g., Ollama)
from aegis.engine.llm_guardrails import LLMGuardrailEngine

llm_engine = LLMGuardrailEngine(
    base_url="http://localhost:11434/v1",  # Ollama endpoint
    model="llama3.2",
    use_json_mode=False
)
client = AegisClient(
    provider=MockStripeProvider(),
    policy=policy,
    engine=llm_engine
)

# Use with LangChain Tool
from aegis.tools.langchain import AegisPaymentTool
tool = AegisPaymentTool(client=client, agent_id="agent-01")
```

### Supported LLM Providers

| Provider | `base_url` | `model` |
|---|---|---|
| OpenAI (default) | *(not needed)* | `gpt-4o-mini` |
| Ollama (local) | `http://localhost:11434/v1` | `llama3.2` |
| vLLM / LM Studio | `http://localhost:8000/v1` | Your model name |
| OpenRouter | `https://openrouter.ai/api/v1` | `anthropic/claude-3-haiku` |
| Any OpenAI-compatible | Your endpoint URL | Your model name |

---

## 10. Payment Providers: Stripe vs Mock

### Without Stripe (Default — Mock Provider)

By default, Aegis uses the `MockStripeProvider` which simulates virtual card issuance. This is perfect for:
- **Development and testing** — no real money involved
- **Demo and evaluation** — see the full flow without any API keys
- **Hackathons** — get a working prototype in minutes

Mock cards are fully functional within the Aegis system (budget tracking, burn-after-use, guardrails all work), but they are not real payment instruments.

```python
from aegis.providers.stripe_mock import MockStripeProvider

client = AegisClient(
    provider=MockStripeProvider(),  # No API key needed
    policy=policy
)
```

### BYOC — Bring Your Own Card (Hacker Edition)

For developers who want to use their **own physical credit card** with Aegis without a Stripe account. The `LocalVaultProvider` reads card credentials from environment variables and injects them into browser payment forms via CDP — the raw PAN is never exposed to the agent.

**Set the following environment variables (or copy `.env.example`):**
```bash
export AEGIS_BYOC_NUMBER="4111111111111111"   # Your real card number
export AEGIS_BYOC_CVV="123"
export AEGIS_BYOC_EXPIRY="12/27"
export AEGIS_BYOC_NAME="Your Name"            # Optional: cardholder name
# The MCP server will automatically use LocalVaultProvider
uv run python -m aegis.mcp_server
```

**Provider priority (high → low):** Stripe Issuing → BYOC Local → Mock.

If `AEGIS_STRIPE_KEY` is set, Stripe takes precedence. If `AEGIS_BYOC_NUMBER` is set (but no Stripe key), `LocalVaultProvider` is used. If neither is set, `MockStripeProvider` is used for development.

```python
from aegis.providers.byoc_local import LocalVaultProvider

client = AegisClient(
    provider=LocalVaultProvider(),  # reads from env vars automatically
    policy=policy
)
```

> **Security note:** Never commit real card numbers to version control. Always use `.env` (which is `.gitignore`d) or a secrets manager. The CDP injection ensures the full card number is only handled by the local trusted process, never by the LLM.

### With Real Stripe Issuing

To issue **real virtual credit cards** through [Stripe Issuing](https://stripe.com/issuing):

**Prerequisites:**
1. A Stripe account with [Issuing](https://stripe.com/issuing) enabled (requires application approval)
2. Your Stripe secret key (`sk_live_...` or `sk_test_...`)

**Option A: Via Environment Variable (for MCP Server)**
```bash
export AEGIS_STRIPE_KEY=sk_live_your_stripe_key_here
uv run python -m aegis.mcp_server
# The MCP server will automatically use StripeIssuingProvider
```

**Option B: Via Python SDK**
```python
from aegis.providers.stripe_real import StripeIssuingProvider

client = AegisClient(
    provider=StripeIssuingProvider(api_key="sk_live_your_stripe_key_here"),
    policy=policy
)
```

**What Stripe Issuing does:**
- Creates a real Stripe Cardholder (`Aegis Agent`)
- Issues a virtual card with a spending limit matching the approved amount
- Returns masked card details (last 4 digits only) to the agent
- All Stripe errors are caught and returned as rejection reasons

> **Note:** Stripe Issuing is a premium Stripe product that requires approval. For most development and demo use cases, the Mock provider is sufficient.
