Metadata-Version: 2.4
Name: aegis-security-sdk
Version: 1.0.2
Summary: Aegis AI Security & Governance SDK — local MicroBrain defense-in-depth for AI agents
License: MIT
Keywords: ai,security,llm,agents,guardrails,prompt-injection,governance
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: <3.15,>=3.10
Description-Content-Type: text/markdown
Requires-Dist: langchain-core>=0.3.0
Requires-Dist: langchain-groq>=0.2.0
Requires-Dist: langgraph>=0.2.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: httpx>=0.27.0
Requires-Dist: numpy>=1.24.0
Requires-Dist: onnxruntime>=1.16.0
Requires-Dist: tokenizers>=0.14.0
Requires-Dist: typing-extensions>=4.5.0; python_version < "3.11"
Requires-Dist: aegis-brain-models==1.0.1
Requires-Dist: aegis-policy-nli==1.0.1
Provides-Extra: openai
Requires-Dist: langchain-openai>=0.2.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: langchain-anthropic>=0.3.0; extra == "anthropic"
Provides-Extra: google
Requires-Dist: langchain-google-genai>=2.0.0; extra == "google"
Provides-Extra: nvidia
Requires-Dist: langchain-nvidia-ai-endpoints>=0.3.0; extra == "nvidia"
Provides-Extra: huggingface
Requires-Dist: langchain-huggingface>=0.1.0; extra == "huggingface"
Requires-Dist: huggingface_hub>=0.20.0; extra == "huggingface"
Provides-Extra: crewai
Requires-Dist: crewai>=0.80.0; extra == "crewai"
Requires-Dist: crewai-tools>=0.14.0; extra == "crewai"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: typing-extensions>=4.5.0; python_version < "3.11" and extra == "dev"
Provides-Extra: all
Requires-Dist: aegis-security-sdk[openai]; extra == "all"
Requires-Dist: aegis-security-sdk[anthropic]; extra == "all"
Requires-Dist: aegis-security-sdk[google]; extra == "all"
Requires-Dist: aegis-security-sdk[nvidia]; extra == "all"
Requires-Dist: aegis-security-sdk[huggingface]; extra == "all"
Requires-Dist: aegis-security-sdk[crewai]; extra == "all"

# 🛡️ Aegis SDK — Enterprise AI Security & Governance

![PyPI](https://img.shields.io/pypi/v/aegis-security-sdk)
![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%7C%203.14-blue)
![Status](https://img.shields.io/badge/status-Beta-orange)
![Tests](https://img.shields.io/badge/tests-172%20passing-brightgreen)
![License](https://img.shields.io/badge/license-MIT-informational)

**Aegis** is a multi-layered **security, governance and policy engine** for AI agents and LLM applications.
It provides real-time prompt-injection defense, automated risk scoring, dynamic tool authorization,
stateful human-in-the-loop (HITL) approvals, natural-language policy enforcement, session budgets,
and framework adapters for LangGraph & CrewAI — powered by a **local neural model family that runs
on CPU in ~5 ms with zero data leaving your machine**.

> 🌐 Live dashboard: **https://aegis-sdk-pi.vercel.app/**
> 📦 PyPI: **https://pypi.org/project/aegis-security-sdk/**

---

## Table of Contents

1. [Why Aegis](#why-aegis)
2. [Threat Model](#threat-model)
3. [Architecture — The Five Layers](#architecture--the-five-layers)
4. [The Aegis Brain Family](#the-aegis-brain-family)
5. [Installation](#installation)
6. [Quick Start](#quick-start)
7. [Operating Modes (`enforce` vs `monitoring`)](#operating-modes)
8. [Natural-Language Policy Engine](#natural-language-policy-engine)
9. [Human-in-the-Loop (HITL)](#human-in-the-loop-hitl)
10. [Supported LLM Providers](#supported-llm-providers)
11. [Framework Adapters (LangGraph & CrewAI)](#framework-adapters)
12. [Function Security (`@protect`)](#function-security-protect-decorator)
13. [Dynamic Tool Registry (Hot-Plug)](#dynamic-tool-registry-hot-plug)
14. [Budgets & Kill Switch](#budgets--kill-switch)
15. [Observability, Audit & Dashboard](#observability-audit--dashboard)
16. [Testing & Red-Team Validation](#testing--red-team-validation)
17. [Performance](#performance)
18. [Project Structure](#project-structure)
19. [Roadmap](#roadmap)

---

<a id="why-aegis"></a>
## Why Aegis

| | ☁️ Cloud guardrail APIs | 🛡️ **Aegis** |
|---|---|---|
| Data residency | Prompts sent to a third party | **100% on-prem / device** |
| Latency overhead | 200–800 ms network RTT | **~5 ms local CPU** |
| Cost model | Per-token, forever | **Zero marginal cost** |
| Policies | YAML / DSL engineering | **Plain English + real arithmetic** |
| Approvals | Stateless flags | **Cryptographic signature-bound HITL** |
| Attack surface of the guardrail itself | Remote API | Local models shipped as quantized artifacts |

Aegis is **fail-closed by design**: if any security layer errors, execution is blocked — never permitted.
And it is **defense-in-depth**: five independent layers with no single point of bypass.

---

<a id="threat-model"></a>
## Threat Model

| # | Threat | Layer Defense |
|---|--------|---------------|
| A | Direct prompt injection | Layer 1 · MicroBrain injection head |
| B | Indirect injection (tool outputs) | Layer 3 · Sanitizer + Normalizer scan |
| C | Tool privilege escalation | Layer 1 allowlist + Layer 2 enforcement |
| D | Unauthorized tool invocation | Layer 2 · ToolAuthorizationValidator |
| E | Malicious tool arguments | Layer 2 · ToolArgumentValidator |
| F | Memory poisoning | Layer 1 MemoryValidationStage + MemoryWriteGate |
| G | Jailbreak / role hijacking | Layer 1 RequestAnalyzerStage |
| H | Policy violations | NaturalLanguagePolicy + output compliance |
| I | Unauthenticated execution | Layer 2 identity/permission validators |
| J | Runaway cost / loops | Session BudgetManager + Kill Switch |

---

<a id="architecture"></a>
## Architecture — The Five Layers

```
User Request
    │
    ▼
┌──────────────────────────────────────────────────────────┐
│  LAYER 1 · REQUEST INTELLIGENCE & FIREWALL               │
│  • MicroBrain INT8 classifier (~5 ms CPU):                │
│      injection type · intent · risk level · tool scope ·  │
│      content class · confidence · attack mass             │
│  • Fail-closed capability matcher: only safe, relevant    │
│    tools are bound to the planner (least privilege)       │
│  • Memory-poisoning scan of conversation history          │
└───────────────┬──────────────────────────────────────────┘
                ▼
┌──────────────────────────────────────────────────────────┐
│  HITL GATE (HIGH/CRITICAL risk)                          │
│  Parked request + SHA-256 signature → "I approve" flow   │
└───────────────┬──────────────────────────────────────────┘
                ▼
┌──────────────────────────────────────────────────────────┐
│  NATURAL LANGUAGE POLICY ENGINE (+ Judge ladder)         │
│  Plain-English rules → deterministic verdicts            │
└───────────────┬──────────────────────────────────────────┘
                ▼
┌──────────────────────────────────────────────────────────┐
│  PLANNER ⇄ EXECUTOR LOOP (LangGraph ReAct)               │
│  Planner sees ONLY the allowlisted tools                 │
└───────────────┬──────────────────────────────────────────┘
                ▼
┌──────────────────────────────────────────────────────────┐
│  LAYER 2 · EXECUTION GOVERNANCE                          │
│  ToolScope · ToolAuthorization · ToolArgument · IFC-Taint│
│  validators → timeout/retry → sanitized execution        │
└───────────────┬──────────────────────────────────────────┘
                ▼
┌──────────────────────────────────────────────────────────┐
│  LAYER 4/5 · MEMORY VAULT & OUTPUT CONTROL               │
│  MemoryWriteGate poison check · result normalization ·   │
│  indirect-injection drop · response compliance scan      │
└───────────────┬──────────────────────────────────────────┘
                ▼
        Audit Trail → Dashboard
```

---

<a id="brain-family"></a>
## The Aegis Brain Family

Aegis ships its own compact neural models as **INT8-quantized ONNX artifacts**
(`packages/brain/models/`) — all offline, all CPU, all sub-15 ms:

### 🛡️ MicroBrain — security classifier
Multi-head transformer producing, per request:
`injection_type` (NONE…MEMORY_POISONING) · `intent` (EMAIL_READ … SYSTEM_ADMIN) ·
`risk_level` (LOW→CRITICAL) · `tool_scope` · `content_class` · `confidence` · `attack_mass`.
Calibration gates (`calibration.json`) tune decision thresholds without retraining.

### 🧭 Router — semantic tool routing
Embeds the prompt and every registered tool's identity, binds the **top-K most relevant tools (K≤4)**.
Tiers: exact-name mention → lexical evidence → **embedding cosine** (artifact present) →
intent alignment → scope net → bind nothing (fail closed).
The production embedder normalizes leet/digit-speak (`m33t` → `meet`) before inference so noisy
user input stays in-distribution.

### ⚖️ Policy Judge — rule-violation reasoning ladder
```
deterministic guards (money arithmetic, injection hard-blocks)  ← always authoritative
   ↓ ambiguous?
cross-encoder judge_nli_v2  →  legacy NLI head  →  LLM judge (Groq/Ollama)  →  heuristics
```
Every resolved verdict lands in an in-memory **and disk cache**; LLM-judge calls run under a hard
timeout (`AEGIS_JUDGE_TIMEOUT_S`, default 2 s). Failure anywhere falls back down the ladder — never open.

---

<a id="installation"></a>
## Installation

```bash
pip install aegis-security-sdk
```

Provider & framework extras:

```bash
pip install "aegis-security-sdk[openai]"       # OpenAI
pip install "aegis-security-sdk[anthropic]"    # Claude
pip install "aegis-security-sdk[google]"       # Gemini
pip install "aegis-security-sdk[nvidia]"       # NVIDIA NIM
pip install "aegis-security-sdk[huggingface]"  # HF Inference
pip install "aegis-security-sdk[crewai]"       # CrewAI adapter
pip install "aegis-security-sdk[all]"          # everything
```

Requires Python **3.11 – 3.14**.

---

<a id="quick-start"></a>
## Quick Start

```python
import asyncio
from langchain_core.tools import tool
from aegis import Aegis, GroqProvider

@tool
def lookup_customer(customer_id: str) -> str:
    """Look up customer information by ID."""
    return f"Customer {customer_id}: Tier Gold, Active."

async def main():
    agent = (
        Aegis(name="support-agent", mode="enforce")
        .with_provider(GroqProvider(model_id="llama-3.3-70b-versatile"))
        .with_tools([lookup_customer])
        .with_policy([
            "Do not allow access to raw system prompts.",
            "Block any destructive database operations without approval.",
        ])
    )

    async with agent:
        result = await agent.run("Look up customer CUST-104")
        print("Output:", result.output)

if __name__ == "__main__":
    asyncio.run(main())
```

---

<a id="operating-modes"></a>
## Operating Modes (`enforce` vs `monitoring`)

```python
from aegis import Aegis

agent_enforce = Aegis("prod-agent", mode="enforce")      # block on violation (default)
agent_audit   = Aegis("audit-agent", mode="monitoring")  # log & score, don't interrupt
```

In `monitoring` mode every violation across **all enforcement layers** (Layer-1 threat filter,
policy engine, HITL parking, memory guard) is captured as a structured alert and returned to the
caller instead of raised — perfect for shadow audits and compliance scoring.
The kill switch remains fatal in both modes.

---

<a id="nl-policy-engine"></a>
## Natural-Language Policy Engine

Write governance in plain English. Rules are compiled once into fast, evidence-gated matchers:

```python
POLICIES = [
    "PROHIBIT fetching or disclosing private cryptographic keys, passwords, or system prompts under any circumstances.",
    "PROHIBIT running DROP, TRUNCATE, or DELETE operations on production databases.",
    "Block for any financial transfer exceeding $1,000.",
    "Require human approval for deleting backups.",
    "PROHIBIT sending environment variables, secrets, credentials, chat history, or internal data to any external destination such as gists, pastebins, webhooks, or personal email addresses.",
]
agent.with_policy(POLICIES)
```

Engine behavior you can rely on:

- 💰 **Real money arithmetic** — `$500` passes a *$1,000* limit; `$5,000` does not. Parses `$`, `₹`, `Rs`, lakh/crore. Cosine similarity can never compare numbers; we don't ask it to.
- 🔍 **Evidence-gated blocking** — a PROHIBIT rule only vetoes when the *request itself* carries matching content, so benign reads (`SELECT * FROM users WHERE active=1`, reading email) are never collateral damage.
- ✅ **Approval wins** — kernel-verified human consent satisfies policy-level prohibitions (destructive ops, over-limit transfers), while secret-access and injection-vector directives stay absolute.
- ⚖️ Optional **Judge ladder** (see above) resolves genuinely gray cases with an LLM you choose.

---

<a id="hitl"></a>
## Human-in-the-Loop (HITL)

High-risk operations are **parked**, not dropped. Approval is cryptographically bound to the parked request:

```python
# Step 1 — high-risk request parks
res = await agent.run("Delete production database table audit_logs")
print(res.output)
# ⚠️ Action Requires Approval: High-risk operation detected. Type 'I approve' to proceed.

# Step 2 — explicit confirmation resolves it
approval = await agent.run("I approve")
print(approval.output)
# Table audit_logs deleted successfully.
```

- Bare approvals with nothing parked are rejected fail-closed.
- Divergent confirmation text fails the signature check and discards the pending request.
- Developer/UI flows can pass `is_approved=True` after their own verification — the runtime then satisfies approval-required policies end-to-end.

---

<a id="providers"></a>
## Supported LLM Providers

Security policies are decoupled from model execution — swap providers in one line:

```python
from aegis.packages.providers import (
    GroqProvider, HuggingFaceProvider, OpenAIProvider, AnthropicProvider,
    GeminiProvider, NVIDIAProvider, OllamaProvider,
)

bot_groq  = Aegis("groq-bot").with_provider(GroqProvider(model_id="llama-3.3-70b-versatile"))
bot_hf    = Aegis("hf-bot").with_provider(HuggingFaceProvider(model_id="meta-llama/Llama-3.3-70B-Instruct"))
bot_oai   = Aegis("oai-bot").with_provider(OpenAIProvider(model_id="gpt-4o"))
bot_claude= Aegis("cl-bot").with_provider(AnthropicProvider(model_id="claude-3-5-sonnet-20241022"))
bot_gemini= Aegis("gem-bot").with_provider(GeminiProvider(model_id="gemini-2.0-flash-exp"))
bot_nim   = Aegis("nim-bot").with_provider(NVIDIAProvider(model_id="meta/llama-3.3-70b-instruct"))
bot_local = Aegis("offline").with_provider(OllamaProvider(model_id="llama3", base_url="http://localhost:11434/v1"))
```

No API keys? `LocalSecurityGatewayProvider` runs the entire governed stack fully offline.

---

<a id="adapters"></a>
## Framework Adapters

### LangGraph
```python
from aegis import Aegis

governed_agent = (
    Aegis("devops-agent")
    .with_tools(tools)
    .with_adapter("langgraph", langgraph_agent)
    .with_policy(["Rebooting production servers requires approval."])
)
```

### CrewAI
```python
governed_crew = (
    Aegis("crewai-sec-team")
    .with_adapter("crewai", crew)
    .with_policy(["Block unauthorized network port scanning."])
)
```

---

<a id="protect"></a>
## Function Security (`@protect` Decorator)

Govern any standalone Python function:

```python
from aegis import protect

@protect(
    policy=["Do not allow updating system configurations without admin credentials."],
    mode="enforce",
)
def update_system_config(config_key: str, config_val: str) -> str:
    return f"Config {config_key} updated to {config_val}."
```

---

<a id="hot-plug"></a>
## Dynamic Tool Registry (Hot-Plug)

Register or remove tools **while the agent is RUNNING** — Layer-1 matching, LLM bindings and the
executor graph pick them up without restart:

```python
agent.register_tool(my_new_tool, category="FINANCE")   # scope pin optional
agent.unregister_tool("risky_tool")
```

Least privilege holds across turns: the planner only ever sees the allowlisted subset.

---

<a id="budgets"></a>
## Budgets & Kill Switch

Per-session resource ceilings keyed by correlation ID — multi-turn conversations share one ledger:

```python
agent.with_budget(max_tool_calls=50, max_total_tokens=200_000, max_executions=500)
```

Exceeded before a run → whole run denied. Exceeded before a tool call → that call dies and the
session kill switch fires; every subsequent invocation is refused instantly.

---

<a id="observability"></a>
## Observability, Audit & Dashboard

Every execution produces a scrubbed report (secrets `[REDACTED]` recursively): timeline events,
layer results, planner tokens/costs, tool-call records, governance decisions and scores.

- 💾 **Local store** — `./aegis_audit/AG-<execution-id>.json` (chmod 700 dir / 0600 files)
- ☁️ **Cloud store** — fire-and-forget streaming when `AEGIS_PROJECT_KEY` is set
- 🌐 **Live dashboard** — <https://aegis-sdk-pi.vercel.app/>

Sensitive-key scrubbing covers `key/token/secret/password/auth/credential/env`.

---

<a id="testing"></a>
## Testing & Red-Team Validation

```bash
pytest tests -q                      # unit + integration + red-team suites
python scripts/calibrate_router.py   # zero-FP router acceptance battery
```

- **172 tests passing** across unit, integration and adversarial regression suites
- Dedicated black-box UI battery replays real-world attack classes end-to-end
- Independent red-team audit: **13 attack classes attempted → 0 executed**

---

<a id="performance"></a>
## Performance

| Stage | Typical latency | Notes |
|---|---|---|
| MicroBrain classification | ~5 ms | INT8 ONNX, 2 CPU threads |
| Capability matching | <1 ms | TF-IDF path; embedding tier ≈ +9 ms when enabled |
| Policy evaluation | <1 ms | compiled rules; judge only for ambiguous cases |
| Full security overhead | **~5–40 ms** | vs 200–800 ms for cloud guardrails |

---

<a id="structure"></a>
## Project Structure

```
packages/
├── aegis.py              # public facade: Aegis, protect(), builder API
├── brain/                # local model family
│   ├── engine.py         #   MicroBrain ONNX multi-head classifier
│   ├── scanner.py        #   shared call-site helpers (prompt/output/memory)
│   ├── capability_matcher.py  # tiered least-privilege tool binding
│   ├── embedder.py       #   lazy ONNX sentence embedder (Tier 1b)
│   └── models/           #   *.onnx + tokenizers + labels + calibration.json
├── layers/
│   ├── layer1/           # request intelligence stages
│   ├── layer2/           # governance validators
│   └── layer5/           # telemetry consumer
├── policy/
│   ├── nl_policy.py      # natural-language policy engine
│   ├── policy_judge.py   # judge ladder + caches
│   └── compliance.py     # response compliance validator
├── runtime/
│   ├── kernel/           # orchestration + HITL enforcer
│   ├── nodes/            # planner & executor
│   ├── managers/         # registry, executor, retry, timeout, budget…
│   └── hooks/            # lifecycle hooks (policy enforcement lives here)
├── memory/               # memory vault + poisoning gates
├── observability/        # audit stores (local JSON / cloud)
├── governance/           # information-flow control (taint)
├── providers.py          # 7 LLM providers + offline fallback
├── adapters/             # LangGraph / CrewAI
└── testing/              # Streamlit demo console + benchmarks
```

---

<a id="roadmap"></a>
## Roadmap

- 🧠 Next-gen brain artifacts (fine-tuned router embedder, cross-encoder judge v2, MicroBrain v3 backbone sweep)
- 💱 Currency-aware policy limits (FX-normalized thresholds)
- 🧰 Governed-tool proxy for foreign agent frameworks
- 📜 SOC-2-ready audit-trail pack

---

## Links

- 📦 PyPI — <https://pypi.org/project/aegis-security-sdk/>
- 🌐 Dashboard — <https://aegis-sdk-pi.vercel.app/>

## License

MIT © Aegis contributors
