agentx-security-sdk 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.
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentx-security-sdk
3
+ Version: 0.1.0
4
+ Summary: The self-healing exception handler for autonomous AI agents.
5
+ Home-page: https://github.com/vdalal/semantic-gateway
6
+ Author: AgentX Team
7
+ Author-email: founders@agentx.com
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: requests>=2.25.0
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ # Semantic Gateway 🛡️
27
+
28
+ Semantic Gateway is a production-grade security layer and semantic firewall designed specifically for autonomous AI agents. It intercepts, evaluates, and conditionally blocks agent-driven actions based on intent, policy violation, and neuro-symbolic evaluation, enabling a safe "human-in-the-loop" environment for AI-driven enterprise systems.
29
+
30
+ ## 🚀 The Architecture (Split-Plane)
31
+
32
+ Semantic Gateway relies on a decoupled, hybrid-cloud architecture to ensure maximum performance and security.
33
+
34
+ * **The Control Plane (Dashboard):** A Next.js application (deployed via Vercel) that allows human reviewers to monitor intercepted agent traffic, review chains of thought, and approve or deny parked requests.
35
+ * **The Data Plane (Semantic Firewall):** A Python FastAPI middleware (the "Wedge") that intercepts raw HTTP/SQL payloads *before* they hit the database.
36
+ * **The Shared Brain:** Supabase acts as the central state manager. Both the Control Plane and Data Plane synchronize via Supabase, decoupling the network architecture and allowing asynchronous state polling.
37
+ * **The Evaluator:** Google's Gemini 2.5 Flash is used to translate an agent's Chain of Thought (CoT) into a zero-knowledge taxonomy to evaluate intent against YAML-defined enterprise policies.
38
+
39
+ ## ✨ Key Features
40
+
41
+ * **Fast Pass Heuristic Traps:** Instantly intercepts structurally dangerous queries (e.g., `DROP TABLE`, `DELETE`) with minimal latency.
42
+ * **Asynchronous Polling Loop:** Employs a robust `428 Precondition Required` negotiation. Blocked agents are "parked," receiving a receipt ID, and asynchronously poll the gateway until a human resolves the incident.
43
+ * **Zero-Knowledge Intent Extraction:** Prevents malicious prompt injection by translating raw agent logic into a strict schema before policy evaluation.
44
+ * **Dynamic YAML Policies:** Easily define what specific frontend/backend intents should be blocked or isolated from destructive database writes.
45
+
46
+ ## 🛠️ Getting Started
47
+
48
+ ### Prerequisites
49
+ * Python 3.10+
50
+ * Node.js 18+
51
+ * [Supabase](https://supabase.com) Account
52
+ * [Google AI Studio](https://aistudio.google.com/) API Key (Gemini)
53
+
54
+ ### 1. Environment Variables
55
+ Create a `.env` file in the root directory. **Ensure this file is in your `.gitignore` to protect your IP and keys.**
56
+
57
+ ```env
58
+ SUPABASE_URL=your_supabase_url
59
+ SUPABASE_KEY=your_supabase_service_role_key
60
+ GEMINI_API_KEY=your_gemini_api_key
61
+
62
+ 2. Run the Semantic Firewall (Local)
63
+ Start the FastAPI server via Uvicorn. This acts as the Wedge intercepting traffic.
64
+
65
+
66
+ cd backend
67
+ pip install fastapi uvicorn requests pyyaml supabase pydantic google-genai python-dotenv
68
+ uvicorn main:app --reload
69
+
70
+ 3. Run the Control Plane Dashboard (Vercel/Local)
71
+ Start your Next.js application to view the intercepted incidents.
72
+
73
+
74
+ cd ui
75
+ npm install
76
+ npm run dev
77
+
78
+ 4. Run the Agent Simulation
79
+ Simulate a rogue agent attempting a destructive action (DROP TABLE). Watch the firewall intercept it and route it to your dashboard.
80
+
81
+ python backend/main.py
82
+
83
+
84
+ 🔒 Security Posture
85
+ Secret Management: API keys are never checked into version control. Production variables are managed securely via the Vercel Dashboard.
86
+
87
+ History Scrubbing: This repository has been scrubbed of legacy keys using git-filter-repo.
88
+
89
+ Private IP: Repository is private to protect proprietary evaluation prompts and architecture.
90
+
91
+ 📈 Roadmap
92
+ Trust Boundary Shift: Move the neuro-symbolic evaluation entirely behind the Data Plane to prevent agent manipulation.
93
+
94
+ Dynamic Policy Engine: Shift YAML configurations directly into Supabase for instant Control Plane sync.
95
+
96
+ Dockerization: Containerize the Data Plane for deployment to AWS ECS / Render for persistent, low-latency edge interception.
97
+
98
+ Multi-Tenancy: Implement Supabase Row Level Security (RLS) for multi-org deployments.
@@ -0,0 +1,29 @@
1
+ /zero-knowledge-gateway (The Root Folder)
2
+
3
+ ├── /backend (Our Python Data Plane)
4
+ │ ├── main.py (The FastAPI middleware & Supabase logic)
5
+ │ ├── semantic-firewall.yaml
6
+ │ └── requirements.txt
7
+
8
+ ├── /dashboard (Our Next.js Control Plane)
9
+ │ ├── /app (React pages & Tarpit UI)
10
+ │ ├── /components (shadcn/ui buttons and tables)
11
+ │ ├── tailwind.config.js
12
+ │ └── package.json
13
+
14
+ ├── .env (Shared environment variables!)
15
+ └── README.md
16
+
17
+
18
+ QUICK RECAP
19
+ The Wedge (Data Plane): A fast, dumb Python interceptor that catches bad SQL without slowing down normal traffic.
20
+
21
+ The Intelligence Layer: An out-of-band Gemini integration that forces autonomous agents to explain themselves and standardizes their stochastic text into rigid JSON.
22
+
23
+ The Anchor: A deterministic YAML policy engine that makes the final safety decision without relying on AI.
24
+
25
+ The State Manager: A Supabase database that parks the request.
26
+
27
+ The Control Plane: A Next.js web dashboard where a human can review the interrogation and pull the plug.
28
+
29
+ This is a complete MVP. Solved the "rogue agent" problem in a way that actually scales.
@@ -0,0 +1,4 @@
1
+ from .decorators import agentx_protect
2
+ from .client import AgentXClient
3
+
4
+ __all__ = ["agentx_protect", "AgentXClient"]
@@ -0,0 +1,24 @@
1
+ import os
2
+ import requests
3
+
4
+ class AgentXClient:
5
+ def __init__(self, api_key: str = None, gateway_url: str = "http://localhost:8000"):
6
+ # In the future, api_key authenticates them to our cloud.
7
+ # For now, it connects to their local Sidecar Gateway.
8
+ self.api_key = api_key or os.environ.get("AGENTX_API_KEY")
9
+ self.gateway_url = gateway_url
10
+
11
+ def evaluate_intent(self, agent_id: str, query: str, chain_of_thought: str, receipt_id: str = None):
12
+ payload = {
13
+ "agent_id": agent_id,
14
+ "original_query": query,
15
+ "chain_of_thought": chain_of_thought,
16
+ "receipt_id": receipt_id
17
+ }
18
+ try:
19
+ response = requests.post(f"{self.gateway_url}/v1/evaluate_intent", json=payload)
20
+ response.raise_for_status()
21
+ return response.json()
22
+ except requests.exceptions.RequestException as e:
23
+ # If our gateway is down, we Fail Closed to protect the system.
24
+ return {"status": "ERROR", "message": f"AgentX Gateway unreachable: {str(e)}"}
@@ -0,0 +1,96 @@
1
+ import functools
2
+ import json
3
+ import atexit
4
+ import time
5
+ from .client import AgentXClient
6
+
7
+ _client = AgentXClient()
8
+
9
+ # --- 1. THE ROI TRACKER ---
10
+ _session_stats = {
11
+ "start_time": time.time(),
12
+ "total_calls": 0,
13
+ "intercepts": 0,
14
+ "critical_blocks": 0
15
+ }
16
+
17
+ def _print_roi_summary():
18
+ """Fires automatically when the developer's script ends or crashes."""
19
+ duration = round(time.time() - _session_stats["start_time"], 2)
20
+
21
+ # Heuristic: Every intercept prevents the agent from burning ~1,500 tokens
22
+ # going down a rabbit hole, plus saves the developer ~5 mins of debugging.
23
+ tokens_saved = _session_stats["intercepts"] * 1500
24
+ dollars_saved = (tokens_saved / 1000) * 0.015 # Approx GPT-4o cost
25
+
26
+ print("\n" + "═"*50)
27
+ print(" 🛡️ AgentX Session Summary")
28
+ print("═"*50)
29
+ print(f" ⏱️ Uptime: {duration} seconds")
30
+ print(f" 🛠️ Tools Monitored: {_session_stats['total_calls']}")
31
+ print(f" 🛑 Socratic Intercepts: {_session_stats['intercepts']}")
32
+ print(f" 💥 Catastrophic Blocks: {_session_stats['critical_blocks']}")
33
+ print("─"*50)
34
+ print(f" 💰 Est. Tokens Saved: ~{tokens_saved} (${dollars_saved:.4f})")
35
+ print(f" ⏳ Developer Time Saved: ~{_session_stats['intercepts'] * 5} minutes")
36
+ print("═"*50 + "\n")
37
+
38
+ # Register the hook to run on exit
39
+ atexit.register(_print_roi_summary)
40
+ # --------------------------
41
+
42
+
43
+ def agentx_protect(agent_id: str, extract_query_func=None, extract_cot_func=None):
44
+ def decorator(func):
45
+ @functools.wraps(func)
46
+ def wrapper(*args, **kwargs):
47
+ # Track the call
48
+ _session_stats["total_calls"] += 1
49
+
50
+ query = extract_query_func(*args, **kwargs) if extract_query_func else str(args)
51
+ chain_of_thought = extract_cot_func(*args, **kwargs) if extract_cot_func else "Implicit tool call"
52
+ receipt_id = kwargs.get("receipt_id", None)
53
+
54
+ print(f"\n🛡️ [AgentX SDK] Intercepting tool call to '{func.__name__}'...")
55
+
56
+ eval_res = _client.evaluate_intent(
57
+ agent_id=agent_id,
58
+ query=query,
59
+ chain_of_thought=chain_of_thought,
60
+ receipt_id=receipt_id
61
+ )
62
+
63
+ status = eval_res.get("status")
64
+
65
+ if status in ["APPROVED", "COMPLIED"]:
66
+ print(f"✅ [AgentX SDK] Intent safe. Executing '{func.__name__}'.")
67
+ return func(*args, **kwargs)
68
+
69
+ elif status == "CHALLENGED":
70
+ # Track the intercept
71
+ _session_stats["intercepts"] += 1
72
+
73
+ challenge = eval_res.get('socratic_prompt', '')
74
+ policy_triggered = eval_res.get('policy_triggered', 'Unknown Policy')
75
+
76
+ # --- THE NEW DETERMINISTIC CHECK ---
77
+ # We specifically track our highest-severity policy for the ROI dashboard
78
+ # Your engine is returning "Database Isolation", so we check for that!
79
+ if policy_triggered in ["Mass Destructive Intent", "Database Isolation"]:
80
+ _session_stats["critical_blocks"] += 1
81
+ # -----------------------------------
82
+
83
+ new_receipt = eval_res.get('receipt_id')
84
+ print(f"🛑 [AgentX SDK] Policy '{policy_triggered}' violated. Returning challenge to Agent.")
85
+
86
+ return json.dumps({
87
+ "error": "AgentX Policy Violation",
88
+ "challenge": challenge,
89
+ "receipt_id": new_receipt,
90
+ "instruction": "Revise your action to comply with the challenge and try again. Pass the receipt_id."
91
+ })
92
+ else:
93
+ return f"AgentX System Error: {eval_res.get('message')}"
94
+
95
+ return wrapper
96
+ return decorator
@@ -0,0 +1,98 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentx-security-sdk
3
+ Version: 0.1.0
4
+ Summary: The self-healing exception handler for autonomous AI agents.
5
+ Home-page: https://github.com/vdalal/semantic-gateway
6
+ Author: AgentX Team
7
+ Author-email: founders@agentx.com
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.8
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: requests>=2.25.0
16
+ Dynamic: author
17
+ Dynamic: author-email
18
+ Dynamic: classifier
19
+ Dynamic: description
20
+ Dynamic: description-content-type
21
+ Dynamic: home-page
22
+ Dynamic: requires-dist
23
+ Dynamic: requires-python
24
+ Dynamic: summary
25
+
26
+ # Semantic Gateway 🛡️
27
+
28
+ Semantic Gateway is a production-grade security layer and semantic firewall designed specifically for autonomous AI agents. It intercepts, evaluates, and conditionally blocks agent-driven actions based on intent, policy violation, and neuro-symbolic evaluation, enabling a safe "human-in-the-loop" environment for AI-driven enterprise systems.
29
+
30
+ ## 🚀 The Architecture (Split-Plane)
31
+
32
+ Semantic Gateway relies on a decoupled, hybrid-cloud architecture to ensure maximum performance and security.
33
+
34
+ * **The Control Plane (Dashboard):** A Next.js application (deployed via Vercel) that allows human reviewers to monitor intercepted agent traffic, review chains of thought, and approve or deny parked requests.
35
+ * **The Data Plane (Semantic Firewall):** A Python FastAPI middleware (the "Wedge") that intercepts raw HTTP/SQL payloads *before* they hit the database.
36
+ * **The Shared Brain:** Supabase acts as the central state manager. Both the Control Plane and Data Plane synchronize via Supabase, decoupling the network architecture and allowing asynchronous state polling.
37
+ * **The Evaluator:** Google's Gemini 2.5 Flash is used to translate an agent's Chain of Thought (CoT) into a zero-knowledge taxonomy to evaluate intent against YAML-defined enterprise policies.
38
+
39
+ ## ✨ Key Features
40
+
41
+ * **Fast Pass Heuristic Traps:** Instantly intercepts structurally dangerous queries (e.g., `DROP TABLE`, `DELETE`) with minimal latency.
42
+ * **Asynchronous Polling Loop:** Employs a robust `428 Precondition Required` negotiation. Blocked agents are "parked," receiving a receipt ID, and asynchronously poll the gateway until a human resolves the incident.
43
+ * **Zero-Knowledge Intent Extraction:** Prevents malicious prompt injection by translating raw agent logic into a strict schema before policy evaluation.
44
+ * **Dynamic YAML Policies:** Easily define what specific frontend/backend intents should be blocked or isolated from destructive database writes.
45
+
46
+ ## 🛠️ Getting Started
47
+
48
+ ### Prerequisites
49
+ * Python 3.10+
50
+ * Node.js 18+
51
+ * [Supabase](https://supabase.com) Account
52
+ * [Google AI Studio](https://aistudio.google.com/) API Key (Gemini)
53
+
54
+ ### 1. Environment Variables
55
+ Create a `.env` file in the root directory. **Ensure this file is in your `.gitignore` to protect your IP and keys.**
56
+
57
+ ```env
58
+ SUPABASE_URL=your_supabase_url
59
+ SUPABASE_KEY=your_supabase_service_role_key
60
+ GEMINI_API_KEY=your_gemini_api_key
61
+
62
+ 2. Run the Semantic Firewall (Local)
63
+ Start the FastAPI server via Uvicorn. This acts as the Wedge intercepting traffic.
64
+
65
+
66
+ cd backend
67
+ pip install fastapi uvicorn requests pyyaml supabase pydantic google-genai python-dotenv
68
+ uvicorn main:app --reload
69
+
70
+ 3. Run the Control Plane Dashboard (Vercel/Local)
71
+ Start your Next.js application to view the intercepted incidents.
72
+
73
+
74
+ cd ui
75
+ npm install
76
+ npm run dev
77
+
78
+ 4. Run the Agent Simulation
79
+ Simulate a rogue agent attempting a destructive action (DROP TABLE). Watch the firewall intercept it and route it to your dashboard.
80
+
81
+ python backend/main.py
82
+
83
+
84
+ 🔒 Security Posture
85
+ Secret Management: API keys are never checked into version control. Production variables are managed securely via the Vercel Dashboard.
86
+
87
+ History Scrubbing: This repository has been scrubbed of legacy keys using git-filter-repo.
88
+
89
+ Private IP: Repository is private to protect proprietary evaluation prompts and architecture.
90
+
91
+ 📈 Roadmap
92
+ Trust Boundary Shift: Move the neuro-symbolic evaluation entirely behind the Data Plane to prevent agent manipulation.
93
+
94
+ Dynamic Policy Engine: Shift YAML configurations directly into Supabase for instant Control Plane sync.
95
+
96
+ Dockerization: Containerize the Data Plane for deployment to AWS ECS / Render for persistent, low-latency edge interception.
97
+
98
+ Multi-Tenancy: Implement Supabase Row Level Security (RLS) for multi-org deployments.
@@ -0,0 +1,10 @@
1
+ README.txt
2
+ setup.py
3
+ agentx_sdk/__init__.py
4
+ agentx_sdk/client.py
5
+ agentx_sdk/decorators.py
6
+ agentx_security_sdk.egg-info/PKG-INFO
7
+ agentx_security_sdk.egg-info/SOURCES.txt
8
+ agentx_security_sdk.egg-info/dependency_links.txt
9
+ agentx_security_sdk.egg-info/requires.txt
10
+ agentx_security_sdk.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ requests>=2.25.0
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,31 @@
1
+ import os
2
+ from setuptools import setup, find_packages
3
+
4
+ # Safely read README.md if it exists, otherwise use a default string
5
+ long_description = "The self-healing exception handler for autonomous AI agents."
6
+ if os.path.exists("README.md"):
7
+ with open("README.md", "r", encoding="utf-8") as fh:
8
+ long_description = fh.read()
9
+
10
+ setup(
11
+ name="agentx-security-sdk",
12
+ version="0.1.0",
13
+ author="AgentX Team",
14
+ author_email="founders@agentx.com",
15
+ description="The self-healing exception handler for autonomous AI agents.",
16
+ long_description=long_description,
17
+ long_description_content_type="text/markdown",
18
+ url="https://github.com/vdalal/semantic-gateway",
19
+ packages=find_packages(include=["agentx_sdk", "agentx_sdk.*"]),
20
+ install_requires=[
21
+ "requests>=2.25.0",
22
+ ],
23
+ classifiers=[
24
+ "Development Status :: 3 - Alpha",
25
+ "Intended Audience :: Developers",
26
+ "Programming Language :: Python :: 3",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Operating System :: OS Independent",
29
+ ],
30
+ python_requires=">=3.8",
31
+ )