forked from microsoft/agent-governance-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel_v1_demo.py
More file actions
275 lines (217 loc) · 9.63 KB
/
kernel_v1_demo.py
File metadata and controls
275 lines (217 loc) · 9.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
Demo: Agent Control Plane v1.0 - The "Kernel" Release
This demo showcases the three main features:
1. Async Support for non-blocking agent operations
2. ABAC (Attribute-Based Access Control) with conditional permissions
3. Flight Recorder for audit logging
Example scenario: A financial agent with context-aware permissions
"""
import asyncio
from agent_control_plane import (
AgentKernel,
PolicyEngine,
Condition,
ConditionalPermission,
FlightRecorder,
)
def print_section(title):
"""Print a formatted section header"""
print("\n" + "=" * 80)
print(f" {title}")
print("=" * 80)
async def demo_async_support():
"""Demo 1: Async Support"""
print_section("DEMO 1: Async Support")
policy = PolicyEngine()
policy.add_constraint(role="agent-1", allowed_tools=["read_data", "analyze"])
policy.add_constraint(role="agent-2", allowed_tools=["write_report"])
kernel = AgentKernel(policy_engine=policy)
# Multiple agents can operate concurrently
print("\n🚀 Testing concurrent agent operations...")
results = await asyncio.gather(
kernel.intercept_tool_execution_async("agent-1", "read_data", {}),
kernel.intercept_tool_execution_async("agent-2", "write_report", {}),
kernel.intercept_tool_execution_async("agent-1", "analyze", {}),
)
for i, result in enumerate(results, 1):
status = "✅ ALLOWED" if result.get("allowed") else "❌ BLOCKED"
print(f" Operation {i}: {status}")
def demo_abac_conditions():
"""Demo 2: ABAC with Conditional Permissions"""
print_section("DEMO 2: ABAC (Attribute-Based Access Control)")
policy = PolicyEngine()
# Setup: Finance agent can refund IF:
# 1. User is verified, AND
# 2. Amount is under $1000
conditions = [Condition("user_status", "eq", "verified"), Condition("args.amount", "lt", 1000)]
permission = ConditionalPermission("refund_user", conditions, require_all=True)
policy.add_conditional_permission("finance-agent", permission)
kernel = AgentKernel(policy_engine=policy)
print("\n📋 Policy Rule:")
print(" 'refund_user' allowed IF user_status=='verified' AND amount<1000")
# Test Case 1: Verified user, low amount (SHOULD ALLOW)
print("\n🧪 Test 1: Verified user, $500 refund")
policy.set_agent_context("finance-agent", {"user_status": "verified"})
result = kernel.intercept_tool_execution("finance-agent", "refund_user", {"amount": 500})
print(f" Result: {'✅ ALLOWED' if result is None else '❌ BLOCKED'}")
# Test Case 2: Verified user, high amount (SHOULD BLOCK)
print("\n🧪 Test 2: Verified user, $1500 refund")
policy.set_agent_context("finance-agent", {"user_status": "verified"})
result = kernel.intercept_tool_execution("finance-agent", "refund_user", {"amount": 1500})
print(f" Result: {'✅ ALLOWED' if result is None else '❌ BLOCKED'}")
if result:
print(f" Reason: {result.get('error', 'Unknown')}")
# Test Case 3: Unverified user, low amount (SHOULD BLOCK)
print("\n🧪 Test 3: Unverified user, $500 refund")
policy.set_agent_context("finance-agent", {"user_status": "unverified"})
result = kernel.intercept_tool_execution("finance-agent", "refund_user", {"amount": 500})
print(f" Result: {'✅ ALLOWED' if result is None else '❌ BLOCKED'}")
if result:
print(f" Reason: {result.get('error', 'Unknown')}")
def demo_flight_recorder():
"""Demo 3: Flight Recorder (Black Box Audit Logging)"""
print_section("DEMO 3: Flight Recorder (Audit Logging)")
# Create flight recorder
recorder = FlightRecorder("demo_flight_recorder.db")
policy = PolicyEngine()
policy.add_constraint(role="audit-agent", allowed_tools=["read_file", "write_file"])
# Protect system paths
policy.protected_paths = ["/etc/", "/sys/"]
kernel = AgentKernel(policy_engine=policy, audit_logger=recorder)
print("\n📝 Recording agent actions to flight_recorder.db...")
# Action 1: Allowed read
print("\n Action 1: Read /data/report.txt")
kernel.intercept_tool_execution(
"audit-agent",
"read_file",
{"path": "/data/report.txt"},
input_prompt="User: Please read the report",
)
print(" ✅ Logged as ALLOWED")
# Action 2: Blocked write (protected path)
print("\n Action 2: Write /etc/passwd")
kernel.intercept_tool_execution(
"audit-agent",
"write_file",
{"path": "/etc/passwd"},
input_prompt="User: Update system file",
)
print(" ❌ Logged as BLOCKED")
# Action 3: Blocked (unauthorized tool)
print("\n Action 3: Delete file (unauthorized)")
kernel.intercept_tool_execution(
"audit-agent",
"delete_file",
{"path": "/data/temp.txt"},
input_prompt="User: Clean up temp files",
)
print(" ❌ Logged as BLOCKED")
# Query the logs
print("\n📊 Flight Recorder Statistics:")
stats = recorder.get_statistics()
print(f" Total actions: {stats['total_actions']}")
print(f" Allowed: {stats['by_verdict'].get('allowed', 0)}")
print(f" Blocked: {stats['by_verdict'].get('blocked', 0)}")
# Show detailed logs
print("\n📋 Detailed Audit Log:")
logs = recorder.query_logs(limit=10)
for log in logs:
verdict = log["policy_verdict"].upper()
icon = "✅" if verdict == "ALLOWED" else "❌"
print(f" {icon} {log['tool_name']} - {verdict}")
if log["violation_reason"]:
print(f" Reason: {log['violation_reason']}")
# Cleanup
recorder.close()
import os
if os.path.exists("demo_flight_recorder.db"):
os.remove("demo_flight_recorder.db")
print("\n🧹 Cleaned up demo database")
def demo_real_world_scenario():
"""Demo 4: Real-world scenario combining all features"""
print_section("DEMO 4: Real-World Scenario - E-commerce Agent")
print("\n🏪 Scenario: E-commerce customer service agent with context-aware permissions")
print(" - Can process refunds up to $1000 for verified customers")
print(" - Can only access customer data, not system files")
print(" - All actions are logged for compliance")
# Setup
recorder = FlightRecorder("ecommerce_audit.db")
policy = PolicyEngine()
# Define conditional permissions
refund_conditions = [
Condition("customer_verified", "eq", True),
Condition("args.amount", "lte", 1000),
]
refund_permission = ConditionalPermission("process_refund", refund_conditions)
policy.add_conditional_permission("cs-agent", refund_permission)
# Also allow basic operations
policy.add_constraint("cs-agent", ["lookup_order", "process_refund"])
kernel = AgentKernel(policy_engine=policy, audit_logger=recorder)
# Scenario: Customer service interactions
print("\n📞 Customer Service Interactions:")
# Interaction 1: Lookup order (always allowed)
print("\n 1. CS Agent: Looking up order #12345...")
result = kernel.intercept_tool_execution(
"cs-agent",
"lookup_order",
{"order_id": "12345"},
input_prompt="Customer: What's the status of my order #12345?",
)
print(f" {'✅ SUCCESS' if result is None else '❌ FAILED'}")
# Interaction 2: Process small refund for verified customer
print("\n 2. CS Agent: Processing $50 refund for verified customer...")
policy.set_agent_context("cs-agent", {"customer_verified": True})
result = kernel.intercept_tool_execution(
"cs-agent",
"process_refund",
{"order_id": "12345", "amount": 50},
input_prompt="Customer: I'd like a refund for this order",
)
print(f" {'✅ APPROVED - Refund processed' if result is None else '❌ DENIED'}")
# Interaction 3: Try to process large refund (should require approval)
print("\n 3. CS Agent: Processing $1500 refund for verified customer...")
result = kernel.intercept_tool_execution(
"cs-agent",
"process_refund",
{"order_id": "67890", "amount": 1500},
input_prompt="Customer: I need a refund for this expensive item",
)
print(f" {'✅ APPROVED' if result is None else '❌ DENIED - Amount exceeds limit'}")
# Show audit trail
print("\n📊 Compliance Audit Trail:")
stats = recorder.get_statistics()
print(f" Total transactions: {stats['total_actions']}")
print(f" Approved: {stats['by_verdict'].get('allowed', 0)}")
print(f" Blocked: {stats['by_verdict'].get('blocked', 0)}")
# Cleanup
recorder.close()
import os
if os.path.exists("ecommerce_audit.db"):
os.remove("ecommerce_audit.db")
def main():
"""Run all demos"""
print("\n" + "█" * 80)
print("█" + " " * 78 + "█")
print("█" + " Agent Control Plane v1.0 - The 'Kernel' Release".center(78) + "█")
print("█" + " Production-Ready AI Agent Governance".center(78) + "█")
print("█" + " " * 78 + "█")
print("█" * 80)
# Run async demo
asyncio.run(demo_async_support())
# Run ABAC demo
demo_abac_conditions()
# Run Flight Recorder demo
demo_flight_recorder()
# Run real-world scenario
demo_real_world_scenario()
print_section("Demo Complete! 🎉")
print("\nKey Takeaways:")
print(" ✅ Async support enables concurrent agent operations")
print(" ✅ ABAC provides context-aware, fine-grained access control")
print(" ✅ Flight Recorder ensures complete audit trail for compliance")
print(" ✅ All features work together seamlessly in production scenarios")
print("\n" + "█" * 80 + "\n")
if __name__ == "__main__":
main()