Metadata-Version: 2.4
Name: cachesurgeon
Version: 0.3.0
Summary: CacheSurgeon — Active AI Agent Prefix-Cache Surgeon, Sentinel MCP Rug-Pull Guard, Reversible Secret Vault, and Streaming Tool-Call Firewall.
Author-email: Jonathan Sumpter <licenses@cachesurgeon.com>
License-Expression: MIT
Project-URL: Homepage, https://cachesurgeon.com
Project-URL: Repository, https://github.com/jsumpter415/cachesurgeon
Project-URL: Issues, https://github.com/jsumpter415/cachesurgeon/issues
Keywords: ai-agents,prompt-caching,llm-proxy,anthropic,openai,ollama,mcp,security,finops
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Environment :: Web Environment
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.115.0
Requires-Dist: uvicorn>=0.32.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: rich>=13.9.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: openai>=2; extra == "dev"
Dynamic: license-file

# CacheSurgeon

**Active Prefix-Cache Surgeon, Cache TTL Metadata Tracker, Reversible Secret Vault, and Tool-Call Firewall for Autonomous AI Agents.**

> Stop paying 10× for broken prompt caches, runaway coding-agent loops, and accidental `.env` secret leaks.

![CacheSurgeon Sentinel v0.2.0 Live Demo — Per-Tool MCP Rug-Pull Guard, Encoded Exfil Block & Ed25519 Verifier](https://raw.githubusercontent.com/jsumpter415/cachesurgeon/main/docs/assets/sentinel_demo.gif)

---

## Why CacheSurgeon Exists

Passive LLM gateways (LiteLLM, Portkey, Bifrost) forward broken prompts untouched. Multi-turn autonomous agents and SDKs calling OpenAI Chat Completions (`/v1/chat/completions`) or Anthropic Messages (`/v1/messages`) resend 50K–200K tokens on every turn—meaning a single reordered tool JSON key or per-second timestamp in line 1 of the system prompt destroys **100% of prompt caching**.

CacheSurgeon operates **in flight** in `< 2 ms`:

| Stage | What It Does | Real Impact |
|---|---|---|
| **01. Prefix-Cache Surgeon + X-Ray** | Deterministically sorts tool arrays & JSON keys, relocates volatile system timestamps/trace IDs to the trailing user turn, and injects Anthropic `cache_control` breakpoints. | **40–87%** cloud bill cut; **0% → 98.7%** cache hit & **64×** speedup verified on local MLX. |
| **02. Cache TTL Metadata Tracker** | Observes session TTL metadata locally without running idle eligibility checks or sending background keep-alive pings in `0.1.0`. | From 0.1.1, eligible Anthropic sessions can show projected 5-minute vs. 1-hour cache costs in `/api/metrics` (`ttl_analysis`). Projections are not measured savings. No background keep-alive pings are sent. |
| **03. Reversible Secret & PII Vault** | Scrubs AWS, OpenAI, Stripe, Anthropic, Google, GitHub, Slack, JWT, PEM, DB URLs, and PII into opaque tokens (`__CS_AWS_ACCESS_KEY_01__`) before cloud egress. | Zero raw credentials leave your VPC or touch SQLite audit logs. |
| **04. Streaming Tool-Call / MCP Firewall** | Inspects model-emitted OpenAI `tool_calls` and Anthropic `tool_use` blocks *before* local execution—across both JSON and live **SSE streams** with 0ms added text TTFT—blocking `rm -rf`, `DROP TABLE`, `curl \| bash`, SSH key reads, and force-pushes to `main`. | Pre-execution CISO guardrail with structured compliance logs. |
| **05. Loop Breaker & Safe Failover** | Fingerprints repeating failing tool loops (`warn` / autonomous `pivot` / HTTP `429` hard `trip`), enforces hard USD session budgets, and defaults to same-family safe downgrade on upstream `429`. | Eliminates OWASP LLM10 Denial-of-Wallet surprises. |
| **06. Sentinel Shield & Forensics (`v0.2.0`)** | Per-tool SHA-256 MCP rug-pull guard with 100% offline semantic-diff triage (auto-re-pins benign edits, quarantines poisoned tools), multi-turn encoded secret-provenance guard, MCP Schema-Tax + per-seat/repo attribution, and bounded deterministic verifier minting offline Ed25519 receipts. | Stops MCP supply-chain rug pulls & base64 exfiltration with zero alert fatigue. |

---

## 30-Second Quickstart

```bash
pip install cachesurgeon
# Optional: override ledger/key storage (defaults to ~/.cachesurgeon/data, or preserves an existing writable package ledger)
export CACHESURGEON_DATA_DIR="$HOME/.cachesurgeon/data"
cachesurgeon start --port 8787
```

Open the live Power-Grid Telemetry Cockpit at `http://127.0.0.1:8787` (click **Simulate Agent Attack & Leak** to see all 5 stages fire immediately without needing an API key).

### Connect Supported Clients (Tested API Surfaces)

The gateway accepts OpenAI Chat Completions and Responses, Anthropic Messages, and Anthropic token counts. Streaming generation preserves upstream errors and retry headers. Token counting uses the scrubbed and healed prompt without recording a billable turn.

```bash
# OpenAI Chat Completions (POST /v1/chat/completions and POST /v1/responses)
export OPENAI_BASE_URL="http://127.0.0.1:8787/v1"

# Anthropic Messages (POST /v1/messages; preserves query params such as ?beta=true and anthropic-beta/anthropic-version headers; token counts use POST /v1/messages/count_tokens)
export ANTHROPIC_BASE_URL="http://127.0.0.1:8787"

# Local Ollama via OpenAI-compatible client (requires local Ollama running on http://127.0.0.1:11434 or CACHESURGEON_OLLAMA_UPSTREAM; native /api/chat is not exposed)
export OPENAI_BASE_URL="http://127.0.0.1:8787/v1"
# Set model="ollama:<tag>" (e.g. model="ollama:gpt-oss:20b"); CacheSurgeon strips the "ollama:" prefix before forwarding to Ollama.
```

For Codex CLI, select this provider in your Codex configuration. The gateway forwards your provider credentials to the OpenAI upstream.

```toml
model_provider = "cachesurgeon"

[model_providers.cachesurgeon]
name = "CacheSurgeon"
base_url = "http://127.0.0.1:8787/v1"
wire_api = "responses"
env_key = "OPENAI_API_KEY"
```

Local Ollama Responses requests require native stateless Responses support. Requests that reference a previous cloud response need that provider’s conversation state.

For multi-turn clients, send a stable `X-CacheSurgeon-Session` on each turn. Codex's `session_id` header is also recognized. Reusing a prompt prefix across sessions keeps tool pins, reversible redactions, and usage separate. Unlabelled requests get private one-turn state and share the anonymous circuit-breaker budget for their gateway principal. On a shared gateway, configure distinct proxy keys for independent clients and a separate administrator token.

Sentinel returns a signed `X-CacheSurgeon-Sentinel-Receipt` for request inspection. Its session ID, request ID, prefix hash, and admitted tool declaration digest can be checked against the request ledger. A completed node audit has its own verification receipt. Administrators can approve a pin for its session or quarantine the tool across the node. Historical quarantines retain node scope.

### Run Sentinel Forensics & Deterministic Verifier (CLI)

```bash
cachesurgeon sentinel audit
cachesurgeon sentinel verify
```

### Collect evidence for an Anthropic support report

With Sentinel enabled, an Anthropic Messages request routed through CacheSurgeon can produce a signed local observation when the API returns an HTTP error, sends an SSE error event, or explicitly ends a message with `stop_reason="refusal"`. The observer uses the response received by the gateway. An ordinary validation error is recorded as an HTTP error. The provider's internal policy decision remains unknown.

To export one observation, use the provider request ID from the client error. Omitting the ID selects the most recent matching event in the local ledger.

```bash
cachesurgeon sentinel provider-event --request-id req_EXAMPLE
```

The JSON export includes the UTC observation time, HTTP status, outcome, recognized model and provider IDs when available, whether an upstream stream had emitted a content delta, and whether the outbound JSON differed from the client's JSON. It excludes prompt and response text, tool arguments, credentials, and local session labels. Review the identifiers before sharing. Use `verify_sentinel_receipt` with the node public key obtained separately to authenticate the signed claims. The signature identifies the observing gateway. This command only reads evidence captured while the request passed through that gateway.

### Deploy for a 20-Person Team in 5 Minutes

See [docs/team-rollout.md](https://github.com/jsumpter415/cachesurgeon/blob/v0.3.0/docs/team-rollout.md) for single-container Docker VPC deployment, per-developer `X-CacheSurgeon-Seat` / `X-CacheSurgeon-Repo` attribution, and air-gapped Ed25519 Team licensing.

### Deploy On-Premise via Docker

```bash
docker compose up -d
```

### Benchmark the cost of a completed task

With `ANTHROPIC_API_KEY` set, run a paired Anthropic Messages benchmark on your machine.

```bash
cachesurgeon bench
cachesurgeon bench --workload stable --pairs 4 --max-cost-increase-pct 5 --json
```

Each command makes eight billable requests by default. Both routes answer the same four synthetic inventory questions using native five-minute prompt caching on the same model. One route calls Anthropic directly. The other streams through a temporary local CacheSurgeon gateway with routing and fallback disabled. The default workload changes a timestamp near the start of the catalog each turn. Use `--workload stable` to measure overhead when the prefix already caches well.

The copy-ready report includes cold start, estimated USD per correct answer, median time to first visible text, and provider-reported cache reads and writes. Each route gets its own cache namespace. A wrong answer, missing usage, or interrupted stream makes the run incomplete (exit 1). The optional CI threshold compares the two routes within that run and returns exit 2 if the gateway exceeds the allowed percentage. JSON includes each paired measurement. Costs use the bundled model prices. Account discounts and invoice adjustments can differ.

### Export Expense-Ready Executive ROI Receipt

```bash
cachesurgeon receipt --out monthly-roi.html
```

---

## Public Landing Site (`site/`)

The static marketing & interactive surgical operating theater site lives in `site/` (zero build step, zero framework bloat) and ships with `.github/workflows/pages.yml` for 1-click **GitHub Pages** deployment (or drop straight onto Cloudflare Pages / Netlify).

## Offline Ed25519 Licensing (Air-Gapped Friendly)

```bash
# Vendor: generate signing keypair once
cachesurgeon license keygen

# Vendor: mint a signed customer key (no DRM phone-home required)
cachesurgeon license issue --private-key "<PRIV_B64>" --tier team --org "Acme Corp" --seats 25
```

## Recommended Companion: Product Behavior Investigator

Pair **CacheSurgeon** with our open-source Antigravity forensic debugging plugin, **[Product Behavior Investigator](https://github.com/jsumpter415/product-behavior-investigator)** (`v1.1.0`):
- **Product Behavior Investigator** traces user-visible failures across client, edge, API, and rollout cohorts to the first broken contract with a 6-heading Evidence Report.
- **CacheSurgeon** runs underneath it to cut multi-turn investigation token bills 40–87%, scrub `.env`/log secrets before cloud egress, and block destructive tool calls.

## Development & Tests

```bash
pip install -e ".[dev]"
pytest -v
```
