cachesurgeon 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. cachesurgeon-0.1.0/LICENSE +21 -0
  2. cachesurgeon-0.1.0/PKG-INFO +121 -0
  3. cachesurgeon-0.1.0/README.md +86 -0
  4. cachesurgeon-0.1.0/cachesurgeon/__init__.py +3 -0
  5. cachesurgeon-0.1.0/cachesurgeon/cli.py +139 -0
  6. cachesurgeon-0.1.0/cachesurgeon/config.py +189 -0
  7. cachesurgeon-0.1.0/cachesurgeon/engine/__init__.py +25 -0
  8. cachesurgeon-0.1.0/cachesurgeon/engine/cascade_router.py +137 -0
  9. cachesurgeon-0.1.0/cachesurgeon/engine/circuit_breaker.py +157 -0
  10. cachesurgeon-0.1.0/cachesurgeon/engine/prefix_surgeon.py +258 -0
  11. cachesurgeon-0.1.0/cachesurgeon/engine/secret_vault.py +185 -0
  12. cachesurgeon-0.1.0/cachesurgeon/engine/tool_firewall.py +154 -0
  13. cachesurgeon-0.1.0/cachesurgeon/engine/ttl_warmer.py +138 -0
  14. cachesurgeon-0.1.0/cachesurgeon/licensing/__init__.py +25 -0
  15. cachesurgeon-0.1.0/cachesurgeon/licensing/billing.py +346 -0
  16. cachesurgeon-0.1.0/cachesurgeon/licensing/keys.py +178 -0
  17. cachesurgeon-0.1.0/cachesurgeon/proxy/__init__.py +5 -0
  18. cachesurgeon-0.1.0/cachesurgeon/proxy/server.py +992 -0
  19. cachesurgeon-0.1.0/cachesurgeon/receipts.py +155 -0
  20. cachesurgeon-0.1.0/cachesurgeon/storage/__init__.py +5 -0
  21. cachesurgeon-0.1.0/cachesurgeon/storage/ledger.py +398 -0
  22. cachesurgeon-0.1.0/cachesurgeon/web/app.js +379 -0
  23. cachesurgeon-0.1.0/cachesurgeon/web/index.html +283 -0
  24. cachesurgeon-0.1.0/cachesurgeon/web/styles.css +564 -0
  25. cachesurgeon-0.1.0/cachesurgeon/web/tokens.css +65 -0
  26. cachesurgeon-0.1.0/cachesurgeon.egg-info/PKG-INFO +121 -0
  27. cachesurgeon-0.1.0/cachesurgeon.egg-info/SOURCES.txt +39 -0
  28. cachesurgeon-0.1.0/cachesurgeon.egg-info/dependency_links.txt +1 -0
  29. cachesurgeon-0.1.0/cachesurgeon.egg-info/entry_points.txt +2 -0
  30. cachesurgeon-0.1.0/cachesurgeon.egg-info/requires.txt +9 -0
  31. cachesurgeon-0.1.0/cachesurgeon.egg-info/top_level.txt +1 -0
  32. cachesurgeon-0.1.0/pyproject.toml +66 -0
  33. cachesurgeon-0.1.0/setup.cfg +4 -0
  34. cachesurgeon-0.1.0/tests/test_billing_fulfillment.py +277 -0
  35. cachesurgeon-0.1.0/tests/test_circuit_breaker.py +61 -0
  36. cachesurgeon-0.1.0/tests/test_licensing_and_ui.py +56 -0
  37. cachesurgeon-0.1.0/tests/test_prefix_surgeon.py +60 -0
  38. cachesurgeon-0.1.0/tests/test_production_hardening.py +256 -0
  39. cachesurgeon-0.1.0/tests/test_proxy_e2e.py +124 -0
  40. cachesurgeon-0.1.0/tests/test_secret_vault.py +52 -0
  41. cachesurgeon-0.1.0/tests/test_tool_firewall_and_ttl.py +117 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 CacheSurgeon Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: cachesurgeon
3
+ Version: 0.1.0
4
+ Summary: CacheSurgeon — Active AI Agent Prefix-Cache Surgeon, Net-Savings TTL Warmer, Reversible Secret Vault, and Tool-Call Firewall.
5
+ Author-email: Jonathan Sumpter <licenses@cachesurgeon.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://cachesurgeon.com
8
+ Project-URL: Repository, https://github.com/jsumpter415/cachesurgeon
9
+ Project-URL: Issues, https://github.com/jsumpter415/cachesurgeon/issues
10
+ Keywords: ai-agents,prompt-caching,llm-proxy,anthropic,openai,ollama,mcp,security,finops
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: System Administrators
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
23
+ Requires-Python: >=3.11
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: fastapi>=0.115.0
27
+ Requires-Dist: uvicorn>=0.32.0
28
+ Requires-Dist: httpx>=0.27.0
29
+ Requires-Dist: pydantic>=2.7.0
30
+ Requires-Dist: cryptography>=42.0.0
31
+ Requires-Dist: rich>=13.9.0
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=8.0; extra == "dev"
34
+ Dynamic: license-file
35
+
36
+ # CacheSurgeon
37
+
38
+ **Active Prefix-Cache Surgeon, Net-Savings TTL Warmer, Reversible Secret Vault, and Tool-Call Firewall for Autonomous AI Agents.**
39
+
40
+ > Stop paying 10× for broken prompt caches, idle 5-minute TTL rebuilds, runaway coding-agent loops, and accidental `.env` secret leaks.
41
+
42
+ ---
43
+
44
+ ## Why CacheSurgeon Exists
45
+
46
+ Passive LLM gateways (LiteLLM, Portkey, Bifrost) forward broken prompts untouched. Autonomous coding agents (**Codex**, **Claude Code**, **Cursor**, **Horizon Zero**, **OpenHands**) 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**.
47
+
48
+ CacheSurgeon operates **in flight** in `< 2 ms`:
49
+
50
+ | Stage | What It Does | Real Impact |
51
+ |---|---|---|
52
+ | **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. |
53
+ | **02. Net-Savings TTL Warmer** | Tracks active Anthropic 5-min / OpenAI TTL windows and pings *only* when `cold_rebuild_cost > 2× ping_cost`, reporting transparent `Gross − Ping = Net` savings. | Prevents **10×** cold cache rebuild spikes after short code-review pauses. |
54
+ | **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. |
55
+ | **04. Tool-Call / MCP Firewall** | Inspects model-emitted OpenAI `tool_calls` and Anthropic `tool_use` blocks *before* local execution, blocking `rm -rf`, `DROP TABLE`, `curl \| bash`, SSH key reads, and force-pushes to `main`. | Pre-execution CISO guardrail with structured compliance logs. |
56
+ | **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. |
57
+
58
+ ---
59
+
60
+ ## 30-Second Quickstart
61
+
62
+ ```bash
63
+ pip install git+https://github.com/jsumpter415/cachesurgeon.git
64
+ cachesurgeon start --port 8787
65
+ ```
66
+
67
+ 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).
68
+
69
+ ### Connect Any Coding Agent (1 Env Var)
70
+
71
+ ```bash
72
+ # OpenAI / Codex / Cursor / Product Behavior Investigator
73
+ export OPENAI_BASE_URL="http://127.0.0.1:8787/v1"
74
+
75
+ # Anthropic / Claude Code
76
+ export ANTHROPIC_BASE_URL="http://127.0.0.1:8787"
77
+
78
+ # Local Ollama (accelerated through CacheSurgeon)
79
+ export OLLAMA_BASE_URL="http://127.0.0.1:8787/v1"
80
+ ```
81
+
82
+ ### Deploy On-Premise via Docker
83
+
84
+ ```bash
85
+ docker compose up -d
86
+ ```
87
+
88
+ ### Export Expense-Ready Executive ROI Receipt
89
+
90
+ ```bash
91
+ cachesurgeon receipt --out monthly-roi.html
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Public Landing Site (`site/`)
97
+
98
+ 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).
99
+
100
+ ## Offline Ed25519 Licensing (Air-Gapped Friendly)
101
+
102
+ ```bash
103
+ # Vendor: generate signing keypair once
104
+ cachesurgeon license keygen
105
+
106
+ # Vendor: mint a signed customer key (no DRM phone-home required)
107
+ cachesurgeon license issue --private-key "<PRIV_B64>" --tier team --org "Acme Corp" --seats 25
108
+ ```
109
+
110
+ ## Recommended Companion: Product Behavior Investigator
111
+
112
+ Pair **CacheSurgeon** with our open-source Antigravity & Codex forensic debugging plugin, **[Product Behavior Investigator](https://github.com/jsumpter415/product-behavior-investigator)** (`v1.1.0`):
113
+ - **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.
114
+ - **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.
115
+
116
+ ## Development & Tests
117
+
118
+ ```bash
119
+ pip install -e ".[dev]"
120
+ pytest -v
121
+ ```
@@ -0,0 +1,86 @@
1
+ # CacheSurgeon
2
+
3
+ **Active Prefix-Cache Surgeon, Net-Savings TTL Warmer, Reversible Secret Vault, and Tool-Call Firewall for Autonomous AI Agents.**
4
+
5
+ > Stop paying 10× for broken prompt caches, idle 5-minute TTL rebuilds, runaway coding-agent loops, and accidental `.env` secret leaks.
6
+
7
+ ---
8
+
9
+ ## Why CacheSurgeon Exists
10
+
11
+ Passive LLM gateways (LiteLLM, Portkey, Bifrost) forward broken prompts untouched. Autonomous coding agents (**Codex**, **Claude Code**, **Cursor**, **Horizon Zero**, **OpenHands**) 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**.
12
+
13
+ CacheSurgeon operates **in flight** in `< 2 ms`:
14
+
15
+ | Stage | What It Does | Real Impact |
16
+ |---|---|---|
17
+ | **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. |
18
+ | **02. Net-Savings TTL Warmer** | Tracks active Anthropic 5-min / OpenAI TTL windows and pings *only* when `cold_rebuild_cost > 2× ping_cost`, reporting transparent `Gross − Ping = Net` savings. | Prevents **10×** cold cache rebuild spikes after short code-review pauses. |
19
+ | **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. |
20
+ | **04. Tool-Call / MCP Firewall** | Inspects model-emitted OpenAI `tool_calls` and Anthropic `tool_use` blocks *before* local execution, blocking `rm -rf`, `DROP TABLE`, `curl \| bash`, SSH key reads, and force-pushes to `main`. | Pre-execution CISO guardrail with structured compliance logs. |
21
+ | **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. |
22
+
23
+ ---
24
+
25
+ ## 30-Second Quickstart
26
+
27
+ ```bash
28
+ pip install git+https://github.com/jsumpter415/cachesurgeon.git
29
+ cachesurgeon start --port 8787
30
+ ```
31
+
32
+ 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).
33
+
34
+ ### Connect Any Coding Agent (1 Env Var)
35
+
36
+ ```bash
37
+ # OpenAI / Codex / Cursor / Product Behavior Investigator
38
+ export OPENAI_BASE_URL="http://127.0.0.1:8787/v1"
39
+
40
+ # Anthropic / Claude Code
41
+ export ANTHROPIC_BASE_URL="http://127.0.0.1:8787"
42
+
43
+ # Local Ollama (accelerated through CacheSurgeon)
44
+ export OLLAMA_BASE_URL="http://127.0.0.1:8787/v1"
45
+ ```
46
+
47
+ ### Deploy On-Premise via Docker
48
+
49
+ ```bash
50
+ docker compose up -d
51
+ ```
52
+
53
+ ### Export Expense-Ready Executive ROI Receipt
54
+
55
+ ```bash
56
+ cachesurgeon receipt --out monthly-roi.html
57
+ ```
58
+
59
+ ---
60
+
61
+ ## Public Landing Site (`site/`)
62
+
63
+ 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).
64
+
65
+ ## Offline Ed25519 Licensing (Air-Gapped Friendly)
66
+
67
+ ```bash
68
+ # Vendor: generate signing keypair once
69
+ cachesurgeon license keygen
70
+
71
+ # Vendor: mint a signed customer key (no DRM phone-home required)
72
+ cachesurgeon license issue --private-key "<PRIV_B64>" --tier team --org "Acme Corp" --seats 25
73
+ ```
74
+
75
+ ## Recommended Companion: Product Behavior Investigator
76
+
77
+ Pair **CacheSurgeon** with our open-source Antigravity & Codex forensic debugging plugin, **[Product Behavior Investigator](https://github.com/jsumpter415/product-behavior-investigator)** (`v1.1.0`):
78
+ - **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.
79
+ - **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.
80
+
81
+ ## Development & Tests
82
+
83
+ ```bash
84
+ pip install -e ".[dev]"
85
+ pytest -v
86
+ ```
@@ -0,0 +1,3 @@
1
+ """CacheSurgeon — Active AI Agent Prefix-Cache Surgeon, Secret Vault & Circuit Breaker."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,139 @@
1
+ """Command-line interface for CacheSurgeon (`start`, `receipt`, `license`, `demo`)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import asyncio
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import uvicorn
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+ from rich.table import Table
14
+
15
+ from cachesurgeon import __version__
16
+ from cachesurgeon.config import CacheSurgeonSettings
17
+ from cachesurgeon.licensing import generate_keypair, issue_license_key, verify_license_key
18
+ from cachesurgeon.proxy.server import CacheSurgeonRuntime, create_app
19
+ from cachesurgeon.receipts import render_executive_receipt_html
20
+
21
+ console = Console()
22
+
23
+
24
+ def build_parser() -> argparse.ArgumentParser:
25
+ parser = argparse.ArgumentParser(
26
+ prog="cachesurgeon",
27
+ description="CacheSurgeon — Active AI Agent Prefix-Cache Surgeon, Secret Vault & Circuit Breaker.",
28
+ )
29
+ parser.add_argument("--data-dir", type=Path, default=None, help="SQLite ledger directory.")
30
+ sub = parser.add_subparsers(dest="command")
31
+
32
+ start_p = sub.add_parser("start", help="Launch the proxy gateway and Power-Grid Cockpit UI.")
33
+ start_p.add_argument("--host", default="127.0.0.1")
34
+ start_p.add_argument("--port", type=int, default=8787)
35
+
36
+ receipt_p = sub.add_parser("receipt", help="Export the printable Executive ROI & Security Receipt.")
37
+ receipt_p.add_argument("--out", type=Path, default=Path("cachesurgeon-receipt.html"))
38
+
39
+ sub.add_parser("demo", help="Run a 5-turn runaway-agent + secret-leak simulation into the ledger.")
40
+
41
+ lic_p = sub.add_parser("license", help="Generate or verify offline Ed25519 customer license keys.")
42
+ lic_sub = lic_p.add_subparsers(dest="lic_cmd")
43
+ lic_sub.add_parser("keygen", help="Generate a new Ed25519 vendor signing keypair.")
44
+
45
+ issue_p = lic_sub.add_parser("issue", help="Mint a signed Pro/Team/Enterprise license key.")
46
+ issue_p.add_argument("--private-key", required=True)
47
+ issue_p.add_argument("--tier", choices=("pro", "team", "enterprise"), default="pro")
48
+ issue_p.add_argument("--org", required=True)
49
+ issue_p.add_argument("--seats", type=int, default=5)
50
+ issue_p.add_argument("--days", type=int, default=365)
51
+
52
+ ver_p = lic_sub.add_parser("verify", help="Verify a signed CacheSurgeon license key.")
53
+ ver_p.add_argument("--key", required=True)
54
+ ver_p.add_argument("--public-key", default="")
55
+
56
+ return parser
57
+
58
+
59
+ def main(argv: list[str] | None = None) -> int:
60
+ parser = build_parser()
61
+ args = parser.parse_args(argv)
62
+
63
+ settings_kwargs = {"data_dir": args.data_dir.resolve()} if args.data_dir else {}
64
+ settings = CacheSurgeonSettings(**settings_kwargs)
65
+
66
+ if args.command == "license":
67
+ if args.lic_cmd == "keygen":
68
+ priv, pub = generate_keypair()
69
+ console.print(
70
+ Panel(
71
+ f"[bold yellow]PRIVATE KEY (KEEP SECRET — VENDOR ONLY):[/bold yellow]\n{priv}\n\n"
72
+ f"[bold cyan]PUBLIC KEY (SET AS CACHESURGEON_PUBLIC_KEY_B64):[/bold cyan]\n{pub}",
73
+ title="CacheSurgeon Ed25519 Keypair",
74
+ )
75
+ )
76
+ return 0
77
+ if args.lic_cmd == "issue":
78
+ key = issue_license_key(
79
+ private_key_b64=args.private_key,
80
+ tier=args.tier,
81
+ org=args.org,
82
+ seats=args.seats,
83
+ valid_days=args.days,
84
+ )
85
+ console.print(Panel(key, title=f"Signed {args.tier.upper()} License for {args.org}"))
86
+ return 0
87
+ if args.lic_cmd == "verify":
88
+ status = verify_license_key(args.key, args.public_key)
89
+ console.print(status)
90
+ return 0 if status.valid else 1
91
+ parser.parse_args(["license", "--help"])
92
+ return 0
93
+
94
+ if args.command == "receipt":
95
+ runtime = CacheSurgeonRuntime(settings)
96
+ html = render_executive_receipt_html(
97
+ org_name=settings.org_name,
98
+ tier=runtime.license.tier,
99
+ summary=runtime.ledger.summary(),
100
+ incidents=runtime.ledger.recent_incidents(25),
101
+ )
102
+ args.out.write_text(html, encoding="utf-8")
103
+ console.print(f"[green]Executive receipt written to {args.out.resolve()}[/green]")
104
+ return 0
105
+
106
+ if args.command == "demo":
107
+ runtime = CacheSurgeonRuntime(settings)
108
+ snap = asyncio.run(runtime.run_demo_simulation())
109
+ s = snap["summary"]
110
+ table = Table(title="CacheSurgeon Live Simulation Results")
111
+ table.add_column("Metric", style="cyan")
112
+ table.add_column("Value", style="bold green")
113
+ table.add_row("Total Requests", str(s["total_requests"]))
114
+ table.add_row("Prefix Cache Hit Rate", f"{s['cache_hit_pct']}%")
115
+ table.add_row("Verified Spend Saved", f"${s['total_saved_usd']:.4f} ({s['savings_pct']}%)")
116
+ table.add_row("Secrets / PII Blocked", str(s["secrets_redacted"]))
117
+ table.add_row("Runaway Loops Halted", str(s["loops_halted"]))
118
+ console.print(table)
119
+ return 0
120
+
121
+ host = getattr(args, "host", "127.0.0.1")
122
+ port = getattr(args, "port", 8787)
123
+ console.print(
124
+ Panel(
125
+ f"[bold cyan]CacheSurgeon v{__version__}[/bold cyan] listening on "
126
+ f"[bold white]http://{host}:{port}[/bold white]\n"
127
+ f"OpenAI / Codex / Ollama base URL: [green]http://{host}:{port}/v1[/green]\n"
128
+ f"Anthropic / Claude Code base URL: [green]http://{host}:{port}[/green]",
129
+ title="CACHESURGEON GATEWAY",
130
+ border_style="yellow",
131
+ )
132
+ )
133
+ app = create_app(settings=settings)
134
+ uvicorn.run(app, host=host, port=port, log_level="info")
135
+ return 0
136
+
137
+
138
+ if __name__ == "__main__":
139
+ sys.exit(main())
@@ -0,0 +1,189 @@
1
+ """Configuration, guardrail policies, and per-model token pricing registry for CacheSurgeon."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+ from typing import Literal
9
+
10
+ from pydantic import BaseModel, Field
11
+
12
+ BreakerAction = Literal["warn", "pivot", "trip"]
13
+ SecretMode = Literal["off", "redact", "reversible"]
14
+ ToolFirewallMode = Literal["off", "audit", "block"]
15
+ CascadeMode = Literal["off", "same_family", "auto", "local_fallback"]
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class ModelPrice:
20
+ """USD per 1,000,000 tokens for input, cached input, and output."""
21
+
22
+ input_per_m: float
23
+ cached_input_per_m: float
24
+ output_per_m: float
25
+
26
+
27
+ MODEL_PRICING: dict[str, ModelPrice] = {
28
+ "gpt-5": ModelPrice(2.50, 0.25, 10.00),
29
+ "gpt-4.1": ModelPrice(2.00, 0.50, 8.00),
30
+ "gpt-4.1-mini": ModelPrice(0.40, 0.10, 1.60),
31
+ "gpt-4o": ModelPrice(2.50, 1.25, 10.00),
32
+ "gpt-4o-mini": ModelPrice(0.15, 0.075, 0.60),
33
+ "o3": ModelPrice(2.00, 0.50, 8.00),
34
+ "o4-mini": ModelPrice(1.10, 0.275, 4.40),
35
+ "claude-sonnet-4": ModelPrice(3.00, 0.30, 15.00),
36
+ "claude-opus-4": ModelPrice(15.00, 1.50, 75.00),
37
+ "claude-3-7-sonnet": ModelPrice(3.00, 0.30, 15.00),
38
+ "claude-3-5-sonnet": ModelPrice(3.00, 0.30, 15.00),
39
+ "claude-3-5-haiku": ModelPrice(0.80, 0.08, 4.00),
40
+ "gemini-2.5-pro": ModelPrice(1.25, 0.31, 10.00),
41
+ "gemini-2.5-flash": ModelPrice(0.15, 0.0375, 0.60),
42
+ "gemini-3.8-flash": ModelPrice(0.20, 0.05, 0.80),
43
+ "gemini-4-hydrogen": ModelPrice(1.50, 0.375, 10.00),
44
+ "gemini-4-neon": ModelPrice(2.50, 0.625, 12.00),
45
+ }
46
+
47
+ DEFAULT_CLOUD_PRICE = ModelPrice(2.50, 0.50, 10.00)
48
+ LOCAL_FREE_PRICE = ModelPrice(0.0, 0.0, 0.0)
49
+
50
+
51
+ def lookup_model_price(model: str) -> ModelPrice:
52
+ """Finds the best-matching pricing entry for a model identifier."""
53
+ normalized = (model or "").strip().lower()
54
+ if normalized.startswith(("ollama:", "local:")) or (
55
+ any(tag in normalized for tag in ("gemma4", "llama", "qwen", "deepseek", "mistral"))
56
+ and not any(cloud in normalized for cloud in ("gpt", "claude", "gemini"))
57
+ ):
58
+ return LOCAL_FREE_PRICE
59
+ for prefix, price in MODEL_PRICING.items():
60
+ if normalized == prefix or normalized.startswith(prefix):
61
+ return price
62
+ return DEFAULT_CLOUD_PRICE
63
+
64
+
65
+ def estimate_costs(
66
+ model: str,
67
+ prompt_tokens: int,
68
+ cached_tokens: int,
69
+ completion_tokens: int,
70
+ assumed_unhealed_cached_tokens: int = 0,
71
+ original_model: str | None = None,
72
+ ) -> tuple[float, float, float]:
73
+ """Returns (raw_unhealed_usd, actual_usd, saved_usd)."""
74
+ actual_price = lookup_model_price(model)
75
+ raw_price = lookup_model_price(original_model or model)
76
+
77
+ uncached_actual = max(0, prompt_tokens - cached_tokens)
78
+ actual_usd = (
79
+ (uncached_actual * actual_price.input_per_m)
80
+ + (cached_tokens * actual_price.cached_input_per_m)
81
+ + (completion_tokens * actual_price.output_per_m)
82
+ ) / 1_000_000.0
83
+
84
+ uncached_raw = max(0, prompt_tokens - assumed_unhealed_cached_tokens)
85
+ raw_usd = (
86
+ (uncached_raw * raw_price.input_per_m)
87
+ + (assumed_unhealed_cached_tokens * raw_price.cached_input_per_m)
88
+ + (completion_tokens * raw_price.output_per_m)
89
+ ) / 1_000_000.0
90
+
91
+ saved_usd = max(0.0, raw_usd - actual_usd)
92
+ return round(raw_usd, 6), round(actual_usd, 6), round(saved_usd, 6)
93
+
94
+
95
+ class GuardrailPolicy(BaseModel):
96
+ """Live-configurable protection, caching, routing, and budget rules."""
97
+
98
+ prefix_surgeon_enabled: bool = True
99
+ relocate_timestamps: bool = True
100
+ inject_anthropic_cache_control: bool = True
101
+ secret_vault_mode: SecretMode = "reversible"
102
+ redact_pii: bool = True
103
+ tool_firewall_mode: ToolFirewallMode = "block"
104
+ ttl_warmer_enabled: bool = True
105
+ circuit_breaker_enabled: bool = True
106
+ breaker_action: BreakerAction = "pivot"
107
+ loop_repeat_threshold: int = Field(default=3, ge=2, le=20)
108
+ max_session_usd: float = Field(default=5.00, ge=0.05, le=10_000.0)
109
+ cascade_mode: CascadeMode = "same_family"
110
+ cheap_cascade_model: str = "gpt-4.1-mini"
111
+ local_fallback_model: str = "gemma4:e4b"
112
+ local_speed_mode: Literal["turbo", "balanced", "deep"] = "turbo"
113
+
114
+
115
+ class CacheSurgeonSettings(BaseModel):
116
+ """Top-level server settings resolved from environment variables or overrides."""
117
+
118
+ data_dir: Path = Field(
119
+ default_factory=lambda: Path(
120
+ os.environ.get(
121
+ "CACHESURGEON_DATA_DIR",
122
+ str(Path(__file__).resolve().parent.parent / "data"),
123
+ )
124
+ ).resolve()
125
+ )
126
+ openai_upstream: str = Field(
127
+ default_factory=lambda: os.environ.get(
128
+ "CACHESURGEON_OPENAI_UPSTREAM", "https://api.openai.com/v1"
129
+ ).rstrip("/")
130
+ )
131
+ anthropic_upstream: str = Field(
132
+ default_factory=lambda: os.environ.get(
133
+ "CACHESURGEON_ANTHROPIC_UPSTREAM", "https://api.anthropic.com"
134
+ ).rstrip("/")
135
+ )
136
+ ollama_upstream: str = Field(
137
+ default_factory=lambda: os.environ.get(
138
+ "CACHESURGEON_OLLAMA_UPSTREAM", "http://127.0.0.1:11434/v1"
139
+ ).rstrip("/")
140
+ )
141
+ license_key: str = Field(
142
+ default_factory=lambda: os.environ.get("CACHESURGEON_LICENSE_KEY", "").strip()
143
+ )
144
+ org_name: str = Field(
145
+ default_factory=lambda: os.environ.get("CACHESURGEON_ORG_NAME", "Engineering Team").strip()
146
+ )
147
+ admin_token: str = Field(
148
+ default_factory=lambda: os.environ.get("CACHESURGEON_ADMIN_TOKEN", "").strip()
149
+ )
150
+ proxy_api_keys: list[str] = Field(
151
+ default_factory=lambda: [
152
+ k.strip()
153
+ for k in os.environ.get("CACHESURGEON_PROXY_API_KEYS", "").split(",")
154
+ if k.strip()
155
+ ]
156
+ )
157
+ cors_origins: list[str] = Field(
158
+ default_factory=lambda: [
159
+ o.strip()
160
+ for o in os.environ.get("CACHESURGEON_CORS_ORIGINS", "").split(",")
161
+ if o.strip()
162
+ ]
163
+ )
164
+ webhook_secret: str = Field(
165
+ default_factory=lambda: os.environ.get("CACHESURGEON_WEBHOOK_SECRET", "").strip()
166
+ )
167
+ vendor_private_key_b64: str = Field(
168
+ default_factory=lambda: os.environ.get("CACHESURGEON_VENDOR_PRIVATE_KEY_B64", "").strip()
169
+ )
170
+ resend_api_key: str = Field(
171
+ default_factory=lambda: os.environ.get("CACHESURGEON_RESEND_API_KEY", "").strip()
172
+ )
173
+ email_from: str = Field(
174
+ default_factory=lambda: os.environ.get(
175
+ "CACHESURGEON_EMAIL_FROM", "CacheSurgeon <onboarding@resend.dev>"
176
+ ).strip()
177
+ )
178
+ owner_email: str = Field(
179
+ default_factory=lambda: os.environ.get("CACHESURGEON_OWNER_EMAIL", "").strip()
180
+ )
181
+ billing_portal_url: str = Field(
182
+ default_factory=lambda: os.environ.get("CACHESURGEON_BILLING_PORTAL_URL", "").strip()
183
+ )
184
+ policy: GuardrailPolicy = Field(default_factory=GuardrailPolicy)
185
+
186
+ @property
187
+ def db_path(self) -> Path:
188
+ self.data_dir.mkdir(parents=True, exist_ok=True)
189
+ return self.data_dir / "cachesurgeon.db"
@@ -0,0 +1,25 @@
1
+ """Core active protection and acceleration engines for CacheSurgeon."""
2
+
3
+ from cachesurgeon.engine.cascade_router import CascadeRouter, RouteDecision, same_family_fallback
4
+ from cachesurgeon.engine.circuit_breaker import BreakerVerdict, CircuitBreaker
5
+ from cachesurgeon.engine.prefix_surgeon import PrefixHealReport, PrefixSurgeon
6
+ from cachesurgeon.engine.secret_vault import SecretRedactionReport, SecretVault, StreamRehydrator
7
+ from cachesurgeon.engine.tool_firewall import BlockedToolCall, ToolCallFirewall, ToolFirewallReport
8
+ from cachesurgeon.engine.ttl_warmer import KeepAliveDecision, TTLCacheWarmer
9
+
10
+ __all__ = [
11
+ "BlockedToolCall",
12
+ "BreakerVerdict",
13
+ "CascadeRouter",
14
+ "CircuitBreaker",
15
+ "KeepAliveDecision",
16
+ "PrefixHealReport",
17
+ "PrefixSurgeon",
18
+ "RouteDecision",
19
+ "SecretRedactionReport",
20
+ "SecretVault",
21
+ "TTLCacheWarmer",
22
+ "ToolCallFirewall",
23
+ "ToolFirewallReport",
24
+ "same_family_fallback",
25
+ ]