-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathdemo.py
More file actions
253 lines (200 loc) Β· 10.1 KB
/
demo.py
File metadata and controls
253 lines (200 loc) Β· 10.1 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
#!/usr/bin/env python3
"""
π‘οΈ Agent OS β 30-Second Demo
Run this to see kernel-level AI agent governance in action.
pip install agent-os-kernel
python demo.py
"""
import asyncio
import sys
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Colors for terminal output
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
def banner():
print(f"""
{CYAN}{BOLD}ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π‘οΈ Agent OS β Kernel-Level Governance for AI Agents β
β β
β The LLM doesn't decide whether to comply with safety rules. β
β The kernel does. β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ{RESET}
""")
async def demo_stateless_kernel():
"""Demo 1: StatelessKernel blocks dangerous actions deterministically."""
from agent_os import StatelessKernel, ExecutionContext
print(f"{BOLD}{'β' * 62}{RESET}")
print(f"{BOLD} DEMO 1: Stateless Kernel β Policy Enforcement{RESET}")
print(f"{BOLD}{'β' * 62}{RESET}\n")
kernel = StatelessKernel()
ctx = ExecutionContext(agent_id="demo-agent", policies=["read_only", "no_pii"])
# --- Allowed action ---
print(f" {BLUE}βΆ Agent requests:{RESET} database_query β SELECT name FROM users")
result = await kernel.execute(
action="database_query",
params={"query": "SELECT name FROM users WHERE id = 1"},
context=ctx,
)
if result.success:
print(f" {GREEN}β ALLOWED{RESET} β read-only query passes\n")
else:
print(f" {RED}β BLOCKED{RESET} β {result.error}\n")
# --- Blocked: write action ---
print(f" {BLUE}βΆ Agent requests:{RESET} file_write β /etc/passwd")
result = await kernel.execute(
action="file_write",
params={"path": "/etc/passwd", "content": "hacked"},
context=ctx,
)
if result.success:
print(f" {GREEN}β ALLOWED{RESET}\n")
else:
print(f" {RED}β BLOCKED β signal={result.signal}{RESET}")
print(f" {DIM} Reason: {result.error[:80]}{RESET}\n")
# --- Blocked: PII in params ---
print(f" {BLUE}βΆ Agent requests:{RESET} database_query β SELECT * ... password ...")
result = await kernel.execute(
action="database_query",
params={"query": "SELECT password FROM users"},
context=ctx,
)
if result.success:
print(f" {GREEN}β ALLOWED{RESET}\n")
else:
print(f" {RED}β BLOCKED β signal={result.signal}{RESET}")
print(f" {DIM} Reason: {result.error[:80]}{RESET}\n")
# --- Blocked: requires approval ---
ctx2 = ExecutionContext(agent_id="demo-agent", policies=["strict"])
print(f" {BLUE}βΆ Agent requests:{RESET} send_email (strict policy, no approval)")
result = await kernel.execute(
action="send_email",
params={"to": "ceo@company.com", "body": "Hi"},
context=ctx2,
)
if result.success:
print(f" {GREEN}β ALLOWED{RESET}\n")
else:
print(f" {RED}β BLOCKED β signal={result.signal}{RESET}")
print(f" {DIM} Reason: {result.error[:80]}{RESET}\n")
async def demo_semantic_policy():
"""Demo 2: Semantic Policy Engine catches intent, not just keywords."""
from agent_os import SemanticPolicyEngine, IntentCategory
print(f"{BOLD}{'β' * 62}{RESET}")
print(f"{BOLD} DEMO 2: Semantic Policy Engine β Intent Classification{RESET}")
print(f"{BOLD}{'β' * 62}{RESET}\n")
engine = SemanticPolicyEngine()
tests = [
("database_query", {"query": "SELECT name FROM users WHERE id=1"}, "Safe read"),
("database_query", {"query": "DROP TABLE users"}, "Destructive SQL"),
("shell", {"cmd": "pg_dump production > /tmp/dump.sql"}, "Data exfiltration"),
("shell", {"cmd": "rm -rf /"}, "System destruction"),
("python", {"code": "eval(user_input)"}, "Code injection"),
("shell", {"cmd": "chmod 777 /etc/shadow"}, "Privilege escalation"),
]
for action, params, label in tests:
r = engine.classify(action, params)
val = list(params.values())[0]
is_bad = r.is_dangerous
icon = f"{RED}π«" if is_bad else f"{GREEN}β
"
cat = r.category.value.replace("_", " ").title()
conf = f"{r.confidence:.0%}"
print(f" {icon} {label:22}{RESET} β {cat:24} β conf={conf}")
print()
async def demo_mute_agent():
"""Demo 3: Face/Hands pattern β reasoning separated from execution."""
from agent_os import face_agent, mute_agent, pipe, ExecutionPlan, ActionStep
print(f"{BOLD}{'β' * 62}{RESET}")
print(f"{BOLD} DEMO 3: Mute Agent β Face/Hands Privilege Separation{RESET}")
print(f"{BOLD}{'β' * 62}{RESET}\n")
@face_agent()
async def planner(task: str) -> ExecutionPlan:
"""Reasons and plans β never executes."""
return ExecutionPlan(steps=[
ActionStep(action="db.read", params={"query": f"SELECT * FROM docs WHERE topic='{task}'"}),
ActionStep(action="file.write", params={"path": "/tmp/report.md", "content": "..."}),
])
@mute_agent(capabilities={"db.read", "file.write"})
async def executor(step):
"""Executes β never reasons. Cannot call LLMs."""
return {"status": "executed", "action": step.action}
print(f" {MAGENTA}Face agent{RESET} plans the work (can reason, cannot execute)")
print(f" {YELLOW}Mute agent{RESET} does the work (can execute, cannot reason)\n")
result = await pipe(planner, executor, "quarterly revenue")
print(f" Pipeline result: {GREEN}{'SUCCESS' if result.success else 'FAILED'}{RESET}")
print(f" Steps executed: {len(result.step_results)}")
for i, sr in enumerate(result.step_results):
print(f" {i+1}. {sr.action} β {GREEN}β{RESET}")
print(f"\n {DIM}The mute agent CANNOT call an LLM, talk to the user,")
print(f" or execute actions outside its capability set.{RESET}\n")
# Show capability violation
@face_agent()
async def evil_planner(task: str) -> ExecutionPlan:
return ExecutionPlan(steps=[
ActionStep(action="db.read", params={"query": "SELECT 1"}),
ActionStep(action="send_email", params={"to": "hacker@evil.com"}), # Not in capabilities!
])
result2 = await pipe(evil_planner, executor, "hack the system")
print(f" {RED}Capability violation caught:{RESET}")
print(f" {DIM} send_email not in {'{'}db.read, file.write{'}'} β pipeline blocked{RESET}\n")
async def demo_context_budget():
"""Demo 4: Context Budget Scheduler β token budget as a kernel primitive."""
from agent_os import ContextScheduler, ContextPriority, BudgetExceeded, AgentSignal
print(f"{BOLD}{'β' * 62}{RESET}")
print(f"{BOLD} DEMO 4: Context Budget Scheduler β Token Governance{RESET}")
print(f"{BOLD}{'β' * 62}{RESET}\n")
scheduler = ContextScheduler(total_budget=8000, lookup_ratio=0.90)
warnings = []
scheduler.on_signal(AgentSignal.SIGWARN, lambda aid, sig: warnings.append(aid))
# Allocate for two agents
w1 = scheduler.allocate("agent-analyst", "quarterly report", priority=ContextPriority.HIGH)
w2 = scheduler.allocate("agent-intern", "format tables", priority=ContextPriority.LOW)
print(f" {CYAN}Agent-Analyst{RESET}: {w1.total} tokens (lookup={w1.lookup_budget}, reasoning={w1.reasoning_budget})")
print(f" {CYAN}Agent-Intern{RESET}: {w2.total} tokens (lookup={w2.lookup_budget}, reasoning={w2.reasoning_budget})")
print(f" {DIM} 90/10 split enforced: {w1.lookup_ratio:.0%} lookup / {w1.reasoning_ratio:.0%} reasoning{RESET}\n")
# Use some budget
scheduler.record_usage("agent-analyst", lookup_tokens=1000, reasoning_tokens=100)
rec = scheduler.get_usage("agent-analyst")
print(f" After usage: {rec.total_used}/{w1.total} tokens ({rec.utilization:.0%} utilized)")
print(f" Remaining: {rec.remaining} tokens\n")
# Exceed budget
print(f" {YELLOW}Agent-Intern tries to use 10Γ its budget...{RESET}")
try:
scheduler.record_usage("agent-intern", lookup_tokens=w2.total * 10)
except BudgetExceeded as e:
print(f" {RED}π₯ SIGSTOP β {e}{RESET}\n")
report = scheduler.get_health_report()
print(f" {DIM}Pool: {report['available']}/{report['total_budget']} available, {report['active_agents']} active agents{RESET}\n")
async def main():
banner()
try:
await demo_stateless_kernel()
except ImportError as e:
print(f" {DIM}Skipped: {e}{RESET}\n")
try:
await demo_semantic_policy()
except ImportError as e:
print(f" {DIM}Skipped (install from source for latest): {e}{RESET}\n")
try:
await demo_mute_agent()
except ImportError as e:
print(f" {DIM}Skipped (install from source for latest): {e}{RESET}\n")
try:
await demo_context_budget()
except ImportError as e:
print(f" {DIM}Skipped (install from source for latest): {e}{RESET}\n")
print(f"{CYAN}{BOLD}{'β' * 62}{RESET}")
print(f"{CYAN}{BOLD} β Like what you see?{RESET}")
print(f" {BOLD}GitHub:{RESET} https://github.com/imran-siddique/agent-os")
print(f" {BOLD}Mesh:{RESET} https://github.com/imran-siddique/agent-mesh")
print(f" {BOLD}Install:{RESET} pip install agent-os-kernel")
print(f"{CYAN}{BOLD}{'β' * 62}{RESET}\n")
if __name__ == "__main__":
asyncio.run(main())