Metadata-Version: 2.4
Name: vault-for-agents
Version: 6.0.0
Summary: Secure credential management for AI agents
Author-email: Prithvi Putta <prithvi@agentvault.dev>
Maintainer-email: Prithvi Putta <prithvi@agentvault.dev>
License: MIT
Project-URL: Homepage, https://github.com/cyberbloke9/agent-vault
Project-URL: Documentation, https://agent-vault.dev/docs
Project-URL: Repository, https://github.com/cyberbloke9/agent-vault
Project-URL: Issues, https://github.com/cyberbloke9/agent-vault/issues
Project-URL: Changelog, https://github.com/cyberbloke9/agent-vault/blob/master/CHANGELOG.md
Keywords: ai,agents,credentials,security,vault,secrets,llm,langchain,openai,anthropic,encryption,iam
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=41.0.0
Requires-Dist: keyring>=24.0.0
Requires-Dist: click>=8.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: httpx>=0.24.0
Requires-Dist: aiohttp>=3.8.0
Requires-Dist: openai>=1.0.0
Requires-Dist: anthropic>=0.18.0
Requires-Dist: google-generativeai>=0.3.0
Requires-Dist: langchain-core>=0.1.0
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: typing-extensions>=4.5.0
Requires-Dist: prometheus-client>=0.17.0
Requires-Dist: PyJWT>=2.8.0
Requires-Dist: cryptography>=41.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# Agent Vault

![Python CI](https://github.com/cyberbloke9/agent-vault/actions/workflows/python-ci.yml/badge.svg)
![Frontend CI](https://github.com/cyberbloke9/agent-vault/actions/workflows/frontend-ci.yml/badge.svg)
![SDK CI](https://github.com/cyberbloke9/agent-vault/actions/workflows/sdk-ci.yml/badge.svg)

## Identity and Access Management for AI Agents

Agent Vault is a Python library that provides enterprise-grade identity management, access control, and compliance monitoring for AI agents. As AI systems become more autonomous and interconnected, organizations need a way to know which agents are accessing their systems, what they are allowed to do, and whether their behavior is normal.

This library answers the fundamental question: "Who is this AI agent, and should it have access?"

---

## Table of Contents

1. [The Problem](#the-problem)
2. [What Agent Vault Does](#what-agent-vault-does)
3. [Architecture Overview](#architecture-overview)
4. [Core Components](#core-components)
5. [Installation](#installation)
6. [Quick Start](#quick-start)
7. [Detailed Examples](#detailed-examples)
8. [API Reference](#api-reference)
9. [Security Model](#security-model)
10. [Compliance and Auditing](#compliance-and-auditing)
11. [V5 Enterprise Features](#v5-enterprise-features)
12. [Web Dashboard](#web-dashboard)
13. [Post-Quantum Cryptography](#post-quantum-cryptography-pqc)
14. [ClawdBot Integration](#clawdbot-integration)
15. [Native SDKs](#native-sdks)
16. [CI/CD Pipelines](#cicd-pipelines)
17. [Future Plans](#future-plans)
18. [Contributing](#contributing)

---

## The Problem

Modern software systems increasingly rely on AI agents that operate autonomously. These agents:

- Access APIs and databases on behalf of users
- Make decisions without human oversight
- Communicate with other AI agents
- Handle sensitive credentials and data

Without proper identity management, organizations face critical questions:

1. How do we know which AI agent is making a request?
2. How do we control what each agent can access?
3. How do we detect if an agent is behaving abnormally?
4. How do we audit agent activity for compliance?
5. How do we establish trust between agents from different systems?

Traditional identity solutions (OAuth, SAML, API keys) were designed for humans and applications, not for autonomous AI agents that may spawn sub-agents, delegate tasks, or operate across organizational boundaries.

---

## What Agent Vault Does

Agent Vault provides a complete identity and access management solution specifically designed for AI agents:

```
+------------------------------------------------------------------+
|                         AGENT VAULT                               |
+------------------------------------------------------------------+
|                                                                   |
|  IDENTITY          ACCESS CONTROL       COMPLIANCE                |
|  --------          --------------       ----------                |
|  - Registration    - Capabilities       - SOC2 Logging            |
|  - Verification    - Scoped Access      - Behavior Tracking       |
|  - Fingerprints    - Trust Chains       - Anomaly Detection       |
|                                                                   |
+------------------------------------------------------------------+
|                                                                   |
|  SECURE STORAGE                                                   |
|  --------------                                                   |
|  - Encrypted Credentials (AES-256)                                |
|  - OS Keychain Integration                                        |
|  - Rate Limiting and Time Windows                                 |
|                                                                   |
+------------------------------------------------------------------+
```

### Key Capabilities

**Agent Identity**
- Unique agent identifiers with cryptographic fingerprints
- Identity verification using API keys, certificates, or shared secrets
- Agent registration with metadata (name, owner, purpose)

**Access Control**
- Capability-based permissions (read, write, admin, secrets access)
- Scoped credentials (which agent can access which secret)
- Trust chains for agent-to-agent delegation

**Compliance**
- SOC2-compliant audit logging
- Behavior fingerprinting to establish baselines
- Anomaly detection for suspicious activity
- Export to SIEM systems (Splunk, QRadar, ArcSight)

**Secure Storage**
- AES-256 encryption for all stored secrets
- Integration with OS keychains (macOS Keychain, Windows Credential Manager)
- Automatic secret expiration and rotation support

---

## Architecture Overview

```
+------------------+     +------------------+     +------------------+
|                  |     |                  |     |                  |
|   AI Agent A     |     |   AI Agent B     |     |   AI Agent C     |
|                  |     |                  |     |                  |
+--------+---------+     +--------+---------+     +--------+---------+
         |                        |                        |
         |                        |                        |
         v                        v                        v
+--------+------------------------+------------------------+---------+
|                                                                    |
|                          AGENT VAULT API                           |
|                                                                    |
+----+----------------+----------------+----------------+-------------+
     |                |                |                |
     v                v                v                v
+----+----+     +-----+-----+    +-----+-----+    +-----+-----+
|         |     |           |    |           |    |           |
| Identity|     |Governance |    |Compliance |    |  Storage  |
| Module  |     |  Module   |    |  Module   |    |  Module   |
|         |     |           |    |           |    |           |
+---------+     +-----------+    +-----------+    +-----------+
     |                |                |                |
     v                v                v                v
+----+----------------+----------------+----------------+-------------+
|                                                                    |
|                        ENCRYPTED BACKEND                           |
|                                                                    |
|   +------------+    +------------+    +------------+               |
|   |  Keychain  |    |   File     |    |  Memory    |               |
|   |  Backend   |    |  Backend   |    |  Backend   |               |
|   +------------+    +------------+    +------------+               |
|                                                                    |
+--------------------------------------------------------------------+
```

### Module Descriptions

**Identity Module**
Handles agent registration, unique ID generation, and identity verification. Each agent receives a UUID and a cryptographic fingerprint based on its properties.

**Governance Module**
Manages access control through capabilities, permission checking, rate limiting, and trust relationships between agents.

**Compliance Module**
Provides SOC2-compliant audit logging, tracks agent behavior patterns, detects anomalies, and generates compliance reports.

**Storage Module**
Encrypts and stores credentials using AES-256. Supports multiple backends including OS keychains and encrypted files.

---

## Core Components

### 1. Agent Identity

Every AI agent in the system has a unique identity:

```
+------------------------------------------+
|              AGENT IDENTITY              |
+------------------------------------------+
| ID: agent-f7a8b9c0-1234-5678-9abc-def0   |
| Name: "Data Processing Agent"            |
| Owner: "analytics-team"                  |
| Created: 2026-01-24T10:30:00Z            |
+------------------------------------------+
| Fingerprint: a1b2c3d4e5f6...             |
| API Key Hash: 9f8e7d6c5b4a...            |
| Status: ACTIVE                           |
+------------------------------------------+
| Capabilities:                            |
|   - secrets.read                         |
|   - secrets.write                        |
+------------------------------------------+
```

### 2. Capability System

Capabilities define what an agent is allowed to do:

```
CAPABILITY HIERARCHY
====================

                    +-------------+
                    |    admin    |
                    +------+------+
                           |
          +----------------+----------------+
          |                                 |
    +-----+-----+                     +-----+-----+
    |  secrets  |                     |  agents   |
    +-----+-----+                     +-----+-----+
          |                                 |
    +-----+-----+                     +-----+-----+
    |           |                     |           |
+---+---+   +---+---+             +---+---+   +---+---+
| read  |   | write |             | read  |   | write |
+-------+   +-------+             +-------+   +-------+
```

### 3. Credential Scoping

Fine-grained control over which agents can access which secrets:

```
SCOPED ACCESS MATRIX
====================

                    Secrets
              +-----+-----+-----+-----+
              | api | db  | ssh | aws |
              | key | pwd | key | creds|
Agents        +-----+-----+-----+-----+
--------------+-----+-----+-----+-----+
Agent A       |  R  |  -  |  -  |  -  |
Agent B       |  R  | R/W |  -  |  -  |
Agent C       |  R  |  R  |  R  | R/W |
Admin Agent   | R/W | R/W | R/W | R/W |
--------------+-----+-----+-----+-----+

R = Read, W = Write, - = No Access
```

### 4. Trust Chains

Agents can establish trust relationships with other agents:

```
TRUST CHAIN EXAMPLE
===================

  +---------+                +---------+                +---------+
  | Agent A |----trusts----->| Agent B |----trusts----->| Agent C |
  +---------+   (FULL)       +---------+   (STANDARD)   +---------+
       |                          |
       |                          +--can delegate to B's trustees
       |
       +--trusts B directly
       +--trusts C transitively (via B)
       +--effective trust level: STANDARD (minimum along chain)
```

### 5. Anomaly Detection

The system monitors agent behavior and detects anomalies:

```
BEHAVIOR MONITORING
===================

Normal Pattern (Baseline):
- Access hours: 9 AM - 6 PM
- Resources: api_key, db_connection
- Rate: 10 requests/minute
- Failure rate: 2%

Detected Anomalies:
+------------------+----------+----------------------------------+
| Type             | Severity | Description                      |
+------------------+----------+----------------------------------+
| AFTER_HOURS      | 0.4      | Access at 3:00 AM                |
| BURST_ACCESS     | 0.7      | 50 requests in 10 seconds        |
| NEW_RESOURCE     | 0.3      | First access to ssh_key          |
| HIGH_FAILURE     | 0.6      | 25% failure rate                 |
+------------------+----------+----------------------------------+
```

---

## Installation

### From GitHub

```bash
pip install git+https://github.com/cyberbloke9/agent-vault.git
```

### From Source

```bash
git clone https://github.com/cyberbloke9/agent-vault.git
cd agent-vault
pip install -e .
```

### Requirements

- Python 3.9 or higher
- cryptography library
- keyring library (for OS keychain integration)
- click (for CLI)

---

## Quick Start

### 1. Initialize the Vault

```python
from agent_vault import Vault, initialize

# Initialize with a master password
initialize(password="your-secure-password")
vault = Vault.get_instance()
```

### 2. Register an Agent

```python
from agent_vault.governance import AgentRegistry, Agent

registry = AgentRegistry()

# Register a new agent
agent = registry.register(
    name="Data Processor",
    owner="analytics-team",
    capabilities=["secrets.read"]
)

print(f"Agent ID: {agent.id}")
print(f"API Key: {agent.api_key}")
```

### 3. Store and Retrieve Secrets

```python
# Store a secret
vault.set("api_key", "sk-1234567890")

# Set the agent context
vault.set_agent_context(agent.id)

# Retrieve the secret (will be audited)
api_key = vault.get("api_key")
```

### 4. Verify Agent Identity

```python
from agent_vault.governance import create_verifier, VerificationMethod

verifier = create_verifier(VerificationMethod.API_KEY, registry)

result = verifier.verify(agent.id, agent.api_key)
if result.verified:
    print("Agent identity confirmed")
```

---

## Detailed Examples

### Example 1: Multi-Agent System with Scoped Access

This example shows how to set up multiple agents with different access levels:

```python
from agent_vault import Vault, initialize
from agent_vault.governance import (
    AgentRegistry,
    ScopeRegistry,
    ScopedVault,
    ScopePermission,
)

# Initialize
initialize(password="master-password")
vault = Vault.get_instance()

# Create registries
agents = AgentRegistry()
scopes = ScopeRegistry()

# Register agents with different roles
reader_agent = agents.register(name="Reader", capabilities=["secrets.read"])
writer_agent = agents.register(name="Writer", capabilities=["secrets.read", "secrets.write"])
admin_agent = agents.register(name="Admin", capabilities=["admin"])

# Store secrets
vault.set("database_url", "postgres://...")
vault.set("api_key", "sk-...")
vault.set("ssh_private_key", "-----BEGIN RSA...")

# Grant scoped access
scopes.grant(reader_agent.id, "api_*", ScopePermission.READ)
scopes.grant(writer_agent.id, "database_*", ScopePermission.WRITE)
scopes.grant(admin_agent.id, "*", ScopePermission.ADMIN)

# Create scoped vault for each agent
reader_vault = ScopedVault(vault, scopes, agent_id=reader_agent.id)
writer_vault = ScopedVault(vault, scopes, agent_id=writer_agent.id)

# Reader can read api_key but not database_url
api_key = reader_vault.get("api_key")  # Works
db_url = reader_vault.get("database_url")  # Returns None (no access)

# Writer can read and write database_url
writer_vault.set("database_url", "postgres://new-url...")  # Works
```

### Example 2: Trust Chain Between Agents

This example demonstrates how agents can establish and verify trust:

```python
from agent_vault.governance import (
    TrustRegistry,
    TrustLevel,
    TrustVisualizer,
)

trust = TrustRegistry()

# Agent A trusts Agent B fully, with delegation rights
trust.establish(
    trustor_id="agent-a",
    trustee_id="agent-b",
    level=TrustLevel.FULL,
    can_delegate=True,
    max_delegation_depth=2,
    reason="Approved by security team"
)

# Agent B trusts Agent C
trust.establish(
    trustor_id="agent-b",
    trustee_id="agent-c",
    level=TrustLevel.STANDARD,
    can_delegate=True
)

# Agent C trusts Agent D
trust.establish(
    trustor_id="agent-c",
    trustee_id="agent-d",
    level=TrustLevel.LIMITED
)

# Verify transitive trust: Does A trust D?
result = trust.verify_trust("agent-a", "agent-d", TrustLevel.LIMITED)
print(f"A trusts D: {result.trusted}")
print(f"Trust chain: {result.summary}")

# Visualize the trust network
viz = TrustVisualizer(trust)
print(viz.to_ascii())
```

Output:
```
A trusts D: True
Trust chain: Agent agent-a trusts agent-d at level limited (via 3 hop(s))

Trust Relationships
========================================

agent-a
  +-- agent-b [full] (can delegate)
agent-b
  +-- agent-c [standard] (can delegate)
agent-c
  +-- agent-d [limited]
```

### Example 3: Behavior Monitoring and Anomaly Detection

This example shows how to track agent behavior and detect anomalies:

```python
from agent_vault.compliance import (
    BehaviorTracker,
    AnomalyDetector,
    AnomalyConfig,
)
from datetime import datetime, timezone

# Create tracker and detector
tracker = BehaviorTracker()
config = AnomalyConfig(
    business_hours_start=9,
    business_hours_end=18,
    burst_threshold=20,
    rate_limit_per_minute=60
)
detector = AnomalyDetector(tracker, config)

# Simulate normal agent behavior (builds baseline)
for i in range(100):
    tracker.record_access(
        agent_id="agent-123",
        resource="api_key",
        operation="read"
    )

# Check agent's behavior fingerprint
fingerprint = tracker.get_fingerprint("agent-123")
print(f"Total accesses: {fingerprint.total_accesses}")
print(f"Peak hours: {fingerprint.get_peak_hours()}")
print(f"Top resources: {fingerprint.get_top_resources()}")

# Detect anomaly: access at 3 AM
late_night = datetime.now(timezone.utc).replace(hour=3)
anomalies = detector.analyze_access(
    agent_id="agent-123",
    resource="api_key",
    operation="read",
    timestamp=late_night
)

for anomaly in anomalies:
    print(f"Anomaly: {anomaly.anomaly_type.value}")
    print(f"Severity: {anomaly.severity}")
    print(f"Description: {anomaly.description}")
```

### Example 4: Compliance Reporting

Generate SOC2-compliant reports:

```python
from agent_vault.compliance import (
    ComplianceReporter,
    BehaviorTracker,
    AnomalyDetector,
    ReportPeriod,
    ReportFormat,
)

# Set up components
tracker = BehaviorTracker()
detector = AnomalyDetector(tracker)
reporter = ComplianceReporter(tracker, detector)

# Generate daily compliance report
report = reporter.generate_report(period=ReportPeriod.DAILY)

# Output as markdown
markdown = report.to_markdown()
print(markdown)

# Or export as JSON for automation
json_report = report.to_json()
```

### Example 5: SIEM Integration

Export audit logs to security information systems:

```python
from agent_vault.compliance import (
    AuditExporter,
    ExportFormat,
    create_soc2_event,
    SOC2EventType,
)

# Create events
events = [
    create_soc2_event(
        event_type=SOC2EventType.DATA_READ,
        actor_id="agent-123",
        target_resource="api_key",
        success=True
    ),
    create_soc2_event(
        event_type=SOC2EventType.ACCESS_DENIED,
        actor_id="agent-456",
        target_resource="ssh_key",
        success=False,
        error_code="SCOPE_DENIED"
    )
]

exporter = AuditExporter(events)

# Export to different formats
json_logs = exporter.export_to_string(ExportFormat.JSONL)
cef_logs = exporter.export_to_string(ExportFormat.CEF)   # For Splunk/ArcSight
leef_logs = exporter.export_to_string(ExportFormat.LEEF)  # For QRadar
csv_logs = exporter.export_to_string(ExportFormat.CSV)

# Write to file
exporter.export_to_file("/var/log/agent-vault/audit.log", ExportFormat.JSONL)
```

---

## API Reference

### Vault Class

```python
class Vault:
    def set(name: str, value: str) -> None
    def get(name: str, default: str = None) -> str
    def delete(name: str) -> bool
    def list() -> List[str]
    def exists(name: str) -> bool
    def set_agent_context(agent_id: str) -> None
```

### AgentRegistry Class

```python
class AgentRegistry:
    def register(name: str, owner: str = None, capabilities: List[str] = None) -> Agent
    def get(agent_id: str) -> Agent
    def verify(agent_id: str, api_key: str) -> bool
    def suspend(agent_id: str, reason: str) -> None
    def revoke(agent_id: str) -> None
    def list_active() -> List[Agent]
```

### TrustRegistry Class

```python
class TrustRegistry:
    def establish(trustor_id: str, trustee_id: str, level: TrustLevel, ...) -> TrustRelationship
    def revoke(trustor_id: str, trustee_id: str) -> bool
    def verify_trust(source_id: str, target_id: str, required_level: TrustLevel) -> TrustVerificationResult
    def find_trust_chain(source_id: str, target_id: str) -> TrustChain
    def delegate_trust(original_trustor_id: str, delegator_id: str, new_trustee_id: str) -> TrustRelationship
```

### ScopeRegistry Class

```python
class ScopeRegistry:
    def grant(agent_id: str, secret_pattern: str, permission: ScopePermission) -> CredentialScope
    def revoke(agent_id: str, secret_pattern: str) -> bool
    def check_access(agent_id: str, secret_name: str, permission: ScopePermission) -> ScopeCheckResult
```

### AnomalyDetector Class

```python
class AnomalyDetector:
    def analyze_access(agent_id: str, resource: str, operation: str, ...) -> List[AnomalyResult]
    def get_anomalies(agent_id: str = None, since: datetime = None) -> List[AnomalyResult]
    def get_critical_anomalies() -> List[AnomalyResult]
    def check_behavior_drift(agent_id: str) -> AnomalyResult
```

---

## Security Model

### Encryption

All secrets are encrypted using AES-256 via the Fernet specification:
- AES-128-CBC encryption
- HMAC-SHA256 for authentication
- Key derivation using PBKDF2 with 100,000 iterations

### Key Storage

Master keys are stored securely:
1. OS Keychain (preferred): macOS Keychain, Windows Credential Manager, Linux Secret Service
2. Encrypted file fallback: ~/.agent-vault/key (encrypted with user password)

### Agent Authentication

Agents can be authenticated using:
- API Keys (SHA-256 hashed)
- Shared secrets
- Certificate fingerprints (for enterprise deployments)

### Access Control

Multi-layer access control:
1. Agent must be registered and active
2. Agent must have required capability
3. Agent must have scope for specific secret
4. Access must be within rate limits and time windows

---

## Compliance and Auditing

### SOC2 Alignment

Agent Vault is designed to support SOC2 compliance:

| Trust Criteria | How Agent Vault Helps |
|---------------|----------------------|
| CC6.1 - Logical Access | Agent registration, capability-based access |
| CC6.2 - Access Controls | Scoped permissions, rate limiting |
| CC6.3 - Access Removal | Agent revocation, trust expiration |
| CC7.1 - System Monitoring | Behavior tracking, anomaly detection |
| CC7.2 - Anomaly Response | Alerting, compliance reporting |

### Audit Log Format

Every event includes:
- Event ID (UUID)
- Timestamp (ISO 8601 with timezone)
- Actor ID and name
- Target resource
- Operation type
- Success/failure with error details
- Correlation ID for request tracing
- Integrity hash (SHA-256)

### SIEM Integration

Export formats supported:
- JSON Lines (JSONL) - Universal log format
- CSV - Spreadsheet analysis
- CEF - Common Event Format (Splunk, ArcSight)
- LEEF - Log Event Extended Format (IBM QRadar)
- RFC 5424 Syslog

---

## Future Plans

### Version 5.2 (Next)

**AI Agent Mesh**
- Service mesh integration for agent-to-agent communication
- Zero-trust networking with mutual TLS
- Distributed agent coordination protocols

**Policy Engine**
- Declarative access policies (OPA/Rego)
- Policy versioning and rollback
- Real-time policy simulation and testing

**Enhanced Compliance**
- GDPR data residency controls
- HIPAA compliance certification
- FedRAMP authorization support

### Version 6.0 (Future)

**Observability Platform**
- Real-time dashboards with Grafana
- Prometheus metrics integration
- OpenTelemetry tracing support

**Edge Deployment**
- Lightweight vault for IoT devices
- Edge-to-cloud secret synchronization
- Offline operation with eventual consistency

**Advanced Security**
- Zero-knowledge proofs for secret verification
- Homomorphic encryption for computation on encrypted data

---

## Project Statistics

```
Version: 5.1.2
Release Date: 2026-02-01
Test Coverage: 1,500+ tests passing
Lines of Code: Approximately 65,000

Milestone Progress:
- Milestone 1 (v1): Keychain for AI Agents - COMPLETE
- Milestone 2 (v2): Know Your Agent - COMPLETE
- Milestone 3 (v3): Federation & Intelligence - COMPLETE
- Milestone 4 (v4): Universal AI Integration - COMPLETE
- Milestone 5 (v5): Enterprise Platform - 75% (12/16 phases)

Core Modules:
- Core Vault: 5 components (backends, encryption, storage)
- Governance: 12 components (identity, capabilities, trust)
- Compliance: 6 components (audit, behavior, reporting)
- CLI: Full command-line interface
- Teams: Collaboration, RBAC, secret sharing

Enterprise Modules (Complete):
- Multi-Tenant: Organization isolation with quotas
- SSO/OIDC: Okta, Azure AD, Google Workspace integration
- API Gateway: Rate limiting, auth middleware
- High Availability: Raft consensus, replication, failover
- HSM Production: PKCS#11, CloudHSM support
- Team Collaboration: RBAC, invitations, secret sharing
- Web Dashboard: Full-featured React/Next.js application

Developer Tools:
- SDKs: Go, TypeScript, Rust (native clients)
- IDE Extensions: VS Code, JetBrains plugins
- Infrastructure: Terraform provider, GitHub Actions
- Documentation: OpenAPI 3.0, changelog, versioning

Dashboard Pages:
- /dashboard - Overview and stats
- /dashboard/secrets - Secret management (CRUD, search, grid/table)
- /dashboard/agents - Agent registry with status indicators
- /dashboard/teams - Team collaboration with invitations
- /dashboard/billing - Subscription management
- /dashboard/onboarding - Getting started wizard
- /dashboard/audit - Audit log viewer with filtering
- /dashboard/settings - Configuration with PQC demo

API Endpoints: 70+ REST endpoints
Frontend Components: 20+ React pages/components
Tests: 58 team tests + 21 API tests + 1400+ core tests
```

---

## V5 Enterprise Features

### Multi-Tenant Architecture (Phase 30)
- Complete tenant isolation with separate encryption keys
- Organization-level quotas and limits
- Cross-tenant secret sharing with permissions

### SSO/OIDC Integration (Phase 31)
- Enterprise single sign-on support
- Integration with Okta, Azure AD, Google Workspace
- SAML 2.0 and OpenID Connect protocols

### Kubernetes Operator (Phase 32)
- Custom Resource Definitions (CRDs) for native K8s integration
- Helm chart for production deployment
- Automatic secret sync between vault and K8s secrets
- Support for AgentVault, AgentVaultSecret, AgentVaultAgent CRDs

### High Availability (Phase 33)
- Raft-based leader election with pre-vote
- Write-ahead log replication
- Automatic failover with rollback capability
- Health monitoring with liveness/readiness probes

### Team Collaboration (Phase 41)
- Teams with role-based access control
- Custom roles with permission overrides
- Secret sharing between team members
- Invitation system with email notifications

### Hosted Infrastructure (Phase 42)
- Multi-region deployment (6 AWS regions)
- Auto-scaling with policy-based decisions
- Blue-green and canary deployment strategies
- Resource provisioning and management

### Billing & Subscriptions (Phase 43)
- 4 pricing tiers: Free, Starter ($29), Professional ($99), Enterprise ($499)
- Trial periods and plan changes
- Invoice generation and payment processing
- Usage tracking and limit enforcement

### Onboarding & Growth (Phase 44)
- 7-step guided onboarding wizard
- 15+ built-in secret templates (PostgreSQL, AWS, OpenAI, etc.)
- Multi-language quickstart guides
- Growth analytics with funnels and cohorts
- In-app notifications with preferences

### Launch & Documentation (Phase 45)
- OpenAPI 3.0 specification generation
- Keep a Changelog format documentation
- Semantic versioning with compatibility checks
- LTS (Long-Term Support) version tracking

---

## Native SDKs

Agent Vault provides native client libraries for popular programming languages.

### Go SDK

Full-featured Go client with idiomatic error handling and context support.

```go
import "github.com/cyberbloke9/agent-vault/sdk/go/agentvault"

client, _ := agentvault.NewClient(
    agentvault.WithAPIKey("your-api-key"),
    agentvault.WithTimeout(30 * time.Second),
)

// Create a secret
secret, _ := client.Secrets().Create(ctx, &agentvault.CreateSecretInput{
    Name:  "api-key",
    Value: "sk-1234567890",
})

// List with pagination
result, _ := client.Secrets().List(ctx, &agentvault.ListSecretsOptions{
    PageSize: 10,
})
```

**Features:**
- Context-aware with cancellation support
- Configurable retry with exponential backoff
- Automatic pagination helpers
- Type-safe error handling (`errors.Is(err, agentvault.ErrNotFound)`)

### TypeScript SDK

Modern async/await client with full TypeScript types.

```typescript
import { AgentVaultClient } from '@agent-vault/sdk';

const client = new AgentVaultClient({
    apiKey: 'your-api-key',
    baseUrl: 'http://localhost:8000',
});

// Create a secret
const secret = await client.secrets.create({
    name: 'api-key',
    value: 'sk-1234567890',
});

// List secrets with filtering
const secrets = await client.secrets.list({
    vaultId: 'my-vault',
    pageSize: 20,
});
```

**Features:**
- Full TypeScript definitions
- Automatic request/response validation
- Promise-based async API
- Tree-shakeable ESM build

### Rust SDK

Async-first Rust client using tokio and serde.

```rust
use agentvault::{Client, CreateSecretInput};

#[tokio::main]
async fn main() -> agentvault::Result<()> {
    let client = Client::builder()
        .api_key("your-api-key")
        .timeout(Duration::from_secs(30))
        .build()?;

    // Create a secret
    let secret = client.secrets().create(&CreateSecretInput {
        name: "api-key".to_string(),
        value: "sk-1234567890".to_string(),
        ..Default::default()
    }).await?;

    // Error handling
    match client.secrets().get("non-existent").await {
        Err(e) if e.is_not_found() => println!("Secret not found"),
        Err(e) => return Err(e),
        Ok(s) => println!("Found: {}", s.name),
    }

    Ok(())
}
```

**Features:**
- Async with tokio runtime
- Builder pattern for configuration
- `thiserror`-based error handling
- Full serde serialization

### Web Dashboard (Phase 46)
- Full-featured React/Next.js dashboard
- Real-time secret management UI
- Team collaboration interface
- Billing and subscription management
- Onboarding wizard with templates
- Responsive design with dark theme

---

## Web Dashboard

Agent Vault includes a complete web dashboard for visual management of your vault.

### Dashboard Features

```
+------------------------------------------------------------------+
|                    AGENT VAULT DASHBOARD                          |
+------------------------------------------------------------------+
|                                                                   |
|  CORE FEATURES              ENTERPRISE FEATURES                   |
|  -------------              -------------------                   |
|  - Secrets CRUD             - Team management                     |
|  - Agent management         - Role-based access                   |
|  - Audit log viewer         - Invitation system                   |
|  - Settings config          - Secret sharing                      |
|                                                                   |
|  BILLING & GROWTH           ONBOARDING                            |
|  ---------------            ----------                            |
|  - Plan selection           - Setup checklist                     |
|  - Usage metrics            - Secret templates                    |
|  - Payment methods          - Quickstart guides                   |
|  - Invoice history          - Progress tracking                   |
|                                                                   |
+------------------------------------------------------------------+
```

### Running the Dashboard

**Prerequisites:**
- Node.js 18+ (for frontend)
- Python 3.9+ (for backend API)

**1. Start the Backend API:**
```bash
cd agent_vault
python -m agent_vault.dashboard.app
# API running at http://127.0.0.1:8000
```

**2. Start the Frontend:**
```bash
cd agent_vault/dashboard/web
npm install
npm run dev
# Dashboard running at http://localhost:3000
```

**3. Login:**
- If `AGENT_VAULT_PASSWORD` is not set, any non-empty password works
- For production, set: `export AGENT_VAULT_PASSWORD=your-secure-password`

### Dashboard API Endpoints

| Module | Endpoints | Description |
|--------|-----------|-------------|
| **Auth** | `/api/auth/login`, `/verify` | JWT authentication |
| **Secrets** | `/api/secrets/*` | CRUD operations |
| **Agents** | `/api/agents/*` | Agent management |
| **Audit** | `/api/audit/*` | Audit log access |
| **Billing** | `/api/billing/*` | Plans, subscriptions, payments |
| **Teams** | `/api/teams/*` | Team collaboration |
| **Onboarding** | `/api/onboarding/*` | Setup wizard, templates |
| **Docs** | `/api/docs/*` | API reference, changelog |

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `AGENT_VAULT_PASSWORD` | (none) | Master vault password |
| `AGENT_VAULT_JWT_SECRET` | (auto) | JWT signing key |
| `AGENT_VAULT_HOST` | `127.0.0.1` | API bind address |
| `AGENT_VAULT_PORT` | `8000` | API port |
| `AGENT_VAULT_DEBUG` | `false` | Enable debug mode |
| `AGENT_VAULT_CORS_ORIGINS` | (localhost) | Additional CORS origins |
| `NEXT_PUBLIC_API_URL` | `http://localhost:8000` | Frontend API URL |

---

## CI/CD Pipelines

Agent Vault includes comprehensive CI/CD pipelines for automated testing and builds.

### Pipeline Overview

| Pipeline | Triggers | Tests |
|----------|----------|-------|
| **Python CI** | `agent_vault/**`, `tests/**`, `pyproject.toml` | Python 3.9-3.12, pytest, ruff, black |
| **Frontend CI** | `agent_vault/dashboard/web/**`, `demo/frontend/**` | TypeScript, ESLint, Next.js build, Vite build |
| **SDK CI** | `sdk/**` | Go (lint, test, build), TypeScript, Rust (clippy, test) |

### Running Locally

```bash
# Python tests
pip install -e ".[dev]"
pytest tests/ -v

# Frontend tests
cd agent_vault/dashboard/web
npm install && npm run lint && npm run build

# Go SDK
cd sdk/go
go test -v ./...

# TypeScript SDK
cd sdk/typescript
npm install && npm test

# Rust SDK
cd sdk/rust
cargo test --all-features
```

---

## Contributing

Contributions are welcome. Please:

1. Fork the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

---

## License

MIT License - See LICENSE file for details.

---

## Support

- GitHub Issues: https://github.com/cyberbloke9/agent-vault/issues
- Documentation: This README and inline code documentation

---

---

## ClawdBot Integration

Agent Vault integrates with ClawdBot, a personal AI assistant running on Telegram, to demonstrate real-world agent identity management.

### Live Integration

```
+------------------+     +------------------+     +------------------+
|                  |     |                  |     |                  |
|   ClawdBot       |---->|   Agent Vault    |---->|   Dashboard      |
|   (@Pmp9bot)     |     |   Bridge         |     |   (React)        |
|                  |     |                  |     |                  |
+------------------+     +------------------+     +------------------+
     Telegram              Port 8000              Port 5173
```

### Running the Integration

**1. Start ClawdBot Gateway:**
```bash
cd clawdbot
npm start -- gateway run --port 18789 --bind loopback
```

**2. Start Agent Vault Bridge:**
```bash
cd agent_vault
python clawdbot_bridge.py
# Bridge running at http://localhost:8000
```

**3. Start Dashboard:**
```bash
cd agent_vault/demo/frontend
npm run dev
# Dashboard at http://localhost:5173
```

### Bridge Features

- **Real-time Log Watching**: Monitors ClawdBot log files for activity
- **Agent Registration**: ClawdBot registered as `clawdbot-telegram-001`
- **WebSocket Streaming**: Live metrics (CPU, memory, requests/sec)
- **Event Parsing**: Converts log entries to audit events
- **Trust Network**: Visualizes agent trust relationships

### Registered Agent

```json
{
  "id": "clawdbot-telegram-001",
  "name": "ClawdBot (@Pmp9bot)",
  "owner": "prithvi-putta",
  "status": "ACTIVE",
  "capabilities": ["telegram.send", "telegram.receive", "secrets.read", "agent.spawn"],
  "trust_level": "FULL"
}
```

---

## Post-Quantum Cryptography (PQC)

Agent Vault v5.1 includes NIST FIPS 203/204 compliant post-quantum cryptographic algorithms.

### Supported Algorithms

| Algorithm | Type | Security Level | Use Case |
|-----------|------|----------------|----------|
| **ML-KEM-768** | Key Encapsulation | NIST Level 3 (AES-192) | Secure key exchange, secret wrapping |
| **ML-DSA-65** | Digital Signature | NIST Level 3 (AES-192) | Agent authentication, message signing |
| **SLH-DSA-SHAKE-128f** | Hash-based Signature | NIST Level 1 | Long-term signatures |

### PQC in Dashboard

The **Settings** page (`/dashboard/settings`) includes an interactive PQC demo:

```
+------------------------------------------------------------------+
|                    POST-QUANTUM CRYPTOGRAPHY                      |
|                    NIST FIPS 203/204 Compliant                    |
+------------------------------------------------------------------+
|                                                                   |
|  +---------------------------+  +---------------------------+     |
|  |  ML-DSA (Dilithium)       |  |  ML-KEM (Kyber)           |     |
|  |  Digital Signatures       |  |  Key Encapsulation        |     |
|  |                           |  |                           |     |
|  |  [Generate Signature]     |  |  [Key Encapsulation]      |     |
|  |                           |  |                           |     |
|  |  Algorithm: ML-DSA-65     |  |  Algorithm: ML-KEM-768    |     |
|  |  Signature: 3293 bytes    |  |  Ciphertext: 1088 bytes   |     |
|  |  Time: 0.56 ms            |  |  Shared Secret: 32 bytes  |     |
|  |  Security: NIST Level 3   |  |  Time: 0.12 ms            |     |
|  +---------------------------+  +---------------------------+     |
|                                                                   |
|  Quantum-Ready - Protected against future quantum attacks         |
+------------------------------------------------------------------+
```

### PQC API Endpoints

| Endpoint | Method | Auth Required | Description |
|----------|--------|---------------|-------------|
| `/api/pqc/sign` | POST | Yes (JWT) | Generate ML-DSA signature |
| `/api/pqc/kem` | POST | Yes (JWT) | Perform ML-KEM key encapsulation |
| `/pqc/sign` | POST | No | Demo endpoint (no auth) |
| `/pqc/kem` | POST | No | Demo endpoint (no auth) |

### Usage Example

```python
import requests

# Authenticated request (for dashboard)
response = requests.post(
    "http://localhost:8000/api/pqc/sign",
    headers={"Authorization": f"Bearer {token}"},
    json={
        "algorithm": "ML-DSA-65",
        "operation": "sign",
        "input_data": "Message to sign"
    }
)

# Demo request (no auth required)
response = requests.post(
    "http://localhost:8000/pqc/sign",
    json={
        "algorithm": "ML-DSA-65",
        "operation": "sign"
    }
)
```

---

## Demo Server

Agent Vault includes a standalone demo server with real-time visualizations.

### Running the Demo

**1. Start Demo API:**
```bash
cd agent_vault/demo
python -m uvicorn api.server:app --port 8001
```

**2. Start Demo Frontend:**
```bash
cd agent_vault/demo/frontend
npm install
npm run dev
```

**3. Open Dashboard:**
Navigate to `http://localhost:5173` for the demo dashboard with:
- Real-time agent metrics
- Activity charts
- Anomaly detection panel
- Trust network visualization
- PQC demo
- Compliance gauges

---

## Quick Reference

### Start Everything

```bash
# Terminal 1: Main Dashboard Backend
cd agent_vault && python -m agent_vault.dashboard.app
# API at http://localhost:8000

# Terminal 2: Main Dashboard Frontend
cd agent_vault/agent_vault/dashboard/web && npm run dev
# Dashboard at http://localhost:3000

# Login with any password (or set AGENT_VAULT_PASSWORD)
```

### Key Files

| Component | Location | Description |
|-----------|----------|-------------|
| Core Library | `agent_vault/` | Python vault, governance, compliance modules |
| Dashboard Backend | `agent_vault/dashboard/` | FastAPI routes and services |
| Dashboard Frontend | `agent_vault/dashboard/web/` | Next.js React application |
| Demo Server | `demo/` | Standalone demo with visualizations |
| Go SDK | `sdk/go/` | Native Go client library |
| TypeScript SDK | `sdk/typescript/` | Native TypeScript/Node.js client |
| Rust SDK | `sdk/rust/` | Native Rust async client |
| CI/CD Workflows | `.github/workflows/` | GitHub Actions pipelines |
| PQC Routes | `agent_vault/dashboard/routes/pqc.py` | Post-quantum crypto endpoints |
| Demo Routes | `agent_vault/dashboard/routes/demo_compat.py` | ClawdBot-compatible API |

---

## Project Structure

```
agent_vault/
├── agent_vault/               # Core Python library
│   ├── core/                  # Vault, encryption, storage backends
│   ├── governance/            # Identity, capabilities, trust
│   ├── compliance/            # Audit, behavior, reporting
│   └── dashboard/             # FastAPI backend + Next.js frontend
│       ├── routes/            # API endpoints (secrets, agents, pqc, etc.)
│       ├── services/          # Business logic
│       └── web/               # React/Next.js dashboard
├── sdk/                       # Native client SDKs
│   ├── go/                    # Go SDK
│   ├── typescript/            # TypeScript SDK
│   └── rust/                  # Rust SDK
├── demo/                      # Standalone demo application
├── tests/                     # Test suite
├── terraform/                 # Infrastructure as code
├── ide/                       # IDE extensions (JetBrains)
└── .github/workflows/         # CI/CD pipelines
```

---

Last Updated: 2026-02-01
Version: 5.1.2 (Milestone 5 - 75% complete)
