|
| 1 | +"""autogen-keeperhub-demo — 2-agent AutoGen conversation gated by SBO3L. |
| 2 | +
|
| 3 | +Demonstrates the AutoGen-specific composition shape: |
| 4 | +
|
| 5 | + 1. **Planner** decides what work needs doing (3 sequential research tasks). |
| 6 | + 2. **Executor** holds the SBO3L → KeeperHub tool and runs each task |
| 7 | + by calling `sbo3l_keeperhub_payment_request(aprp_json=...)` against |
| 8 | + the SBO3L daemon. Each call returns either a signed PolicyReceipt + |
| 9 | + KH execution_ref (allow) or a deny envelope with branch-on code. |
| 10 | +
|
| 11 | +The conversation is hardcoded (no OpenAI API key required) — every |
| 12 | +"reasoning" turn is a plain Python statement so the wire path |
| 13 | +(planner-message → executor-tool-call → SBO3L decide → KH execute) |
| 14 | +stays visible without an LLM in the loop. The same code shape works |
| 15 | +unchanged when you swap the planner for a real `AssistantAgent` with |
| 16 | +`model_client=OpenAIChatCompletionClient(...)`. |
| 17 | +
|
| 18 | +Run: |
| 19 | + python agent.py |
| 20 | +
|
| 21 | +Expected output: |
| 22 | + - 3 ALLOW envelopes with kh_execution_ref populated |
| 23 | + - One audit log dump linking each conversation turn → SBO3L |
| 24 | + audit_event_id → KH execution_ref |
| 25 | +""" |
| 26 | + |
| 27 | +from __future__ import annotations |
| 28 | + |
| 29 | +import json |
| 30 | +import os |
| 31 | +import sys |
| 32 | +import uuid |
| 33 | +from dataclasses import dataclass, field |
| 34 | +from datetime import datetime, timedelta, timezone |
| 35 | +from typing import Any |
| 36 | + |
| 37 | +from sbo3l_autogen_keeperhub import sbo3l_autogen_keeperhub_tool |
| 38 | +from sbo3l_sdk import SBO3LClientSync |
| 39 | + |
| 40 | + |
| 41 | +@dataclass |
| 42 | +class _MockAgent: |
| 43 | + """Minimal duck-typed stand-in for autogen.ConversableAgent. |
| 44 | +
|
| 45 | + AutoGen 0.2.x's `ConversableAgent.register_function(function_map=...)` |
| 46 | + surface — the only piece we need to demo the SBO3L registration |
| 47 | + pattern without requiring the real package (which carries an |
| 48 | + OpenAI/Anthropic API key requirement once a real LLM client is |
| 49 | + wired up). The mock dispatches `function_call` exactly the way the |
| 50 | + real ConversableAgent does: looks up by name, calls with kwargs. |
| 51 | + """ |
| 52 | + |
| 53 | + name: str |
| 54 | + function_map: dict[str, Any] = field(default_factory=dict) |
| 55 | + |
| 56 | + def register_function(self, function_map: dict[str, Any]) -> None: |
| 57 | + self.function_map.update(function_map) |
| 58 | + |
| 59 | + def call_tool(self, tool_name: str, **kwargs: Any) -> str: |
| 60 | + if tool_name not in self.function_map: |
| 61 | + raise KeyError(f"agent {self.name!r} has no tool {tool_name!r}") |
| 62 | + # The function_map callable on the legacy ConversableAgent path |
| 63 | + # is registered with a single `aprp_json: str` positional arg. |
| 64 | + # AutoGen marshals the LLM's tool-call JSON into kwargs; we |
| 65 | + # mirror that here. |
| 66 | + if "aprp_json" in kwargs: |
| 67 | + return str(self.function_map[tool_name](kwargs["aprp_json"])) |
| 68 | + # Convenience: if caller passed a dict APRP, JSON-stringify it. |
| 69 | + if "aprp" in kwargs: |
| 70 | + return str(self.function_map[tool_name](json.dumps(kwargs["aprp"]))) |
| 71 | + raise TypeError( |
| 72 | + f"call_tool({tool_name!r}) expected 'aprp_json' or 'aprp' kwarg, " |
| 73 | + f"got {sorted(kwargs)}" |
| 74 | + ) |
| 75 | + |
| 76 | + |
| 77 | +def _aprp(task: str) -> dict[str, Any]: |
| 78 | + return { |
| 79 | + # research-agent-01 is the only agent_id registered in the bundled |
| 80 | + # reference policy. Demos that hardcode a different id are denied |
| 81 | + # before policy evaluation (auth.agent_not_found). Use SBO3L_POLICY |
| 82 | + # to load a custom policy if you want a different label here. |
| 83 | + "agent_id": "research-agent-01", |
| 84 | + "task_id": f"autogen-{task}-{uuid.uuid4().hex[:8]}", |
| 85 | + "intent": "purchase_api_call", |
| 86 | + "amount": {"value": "0.05", "currency": "USD"}, |
| 87 | + "token": "USDC", |
| 88 | + "destination": { |
| 89 | + "type": "x402_endpoint", |
| 90 | + "url": f"https://api.example.com/v1/{task}", |
| 91 | + "method": "POST", |
| 92 | + "expected_recipient": "0x1111111111111111111111111111111111111111", |
| 93 | + }, |
| 94 | + "payment_protocol": "x402", |
| 95 | + "chain": "base", |
| 96 | + "provider_url": "https://api.example.com", |
| 97 | + "expiry": (datetime.now(timezone.utc) + timedelta(minutes=5)).isoformat(), |
| 98 | + "nonce": str(uuid.uuid4()), |
| 99 | + "risk_class": "low", |
| 100 | + } |
| 101 | + |
| 102 | + |
| 103 | +def main() -> int: |
| 104 | + endpoint = os.environ.get("SBO3L_ENDPOINT", "http://localhost:8730") |
| 105 | + print(f"daemon: {endpoint}") |
| 106 | + |
| 107 | + # Real AutoGen would be: |
| 108 | + # from autogen import ConversableAgent |
| 109 | + # executor = ConversableAgent(name="executor", llm_config=False) |
| 110 | + # We use the duck-typed _MockAgent so the demo runs end-to-end |
| 111 | + # without an LLM API key. The SBO3L registration step + tool |
| 112 | + # dispatch shape is identical between mock + real. |
| 113 | + executor = _MockAgent(name="executor") |
| 114 | + |
| 115 | + with SBO3LClientSync(endpoint) as client: |
| 116 | + descriptor = sbo3l_autogen_keeperhub_tool(client=client) |
| 117 | + executor.register_function(function_map={descriptor.name: descriptor.func}) |
| 118 | + |
| 119 | + # The "planner" — in a real demo this is an AssistantAgent |
| 120 | + # producing tool-calls from natural-language reasoning. Here |
| 121 | + # it's a hardcoded plan so the audit log captures the same |
| 122 | + # event shape without an LLM. |
| 123 | + plan = ["search", "rerank", "summarize"] |
| 124 | + print(f"\nplanner: 3-step research plan: {plan}") |
| 125 | + |
| 126 | + audit_log: list[dict[str, Any]] = [] |
| 127 | + for step, task in enumerate(plan, 1): |
| 128 | + print(f"\n--- conversation turn {step}: planner -> executor: run {task!r} ---") |
| 129 | + envelope_str = executor.call_tool( |
| 130 | + descriptor.name, |
| 131 | + aprp_json=json.dumps(_aprp(task)), |
| 132 | + ) |
| 133 | + envelope = json.loads(envelope_str) |
| 134 | + print(f" decision: {envelope.get('decision')}") |
| 135 | + print(f" kh_execution_ref: {envelope.get('kh_execution_ref')}") |
| 136 | + print(f" audit_event_id: {envelope.get('audit_event_id')}") |
| 137 | + if envelope.get("deny_code"): |
| 138 | + print(f" deny_code: {envelope['deny_code']}") |
| 139 | + |
| 140 | + audit_log.append( |
| 141 | + { |
| 142 | + "turn": step, |
| 143 | + "task": task, |
| 144 | + "decision": envelope.get("decision"), |
| 145 | + "audit_event_id": envelope.get("audit_event_id"), |
| 146 | + "kh_execution_ref": envelope.get("kh_execution_ref"), |
| 147 | + } |
| 148 | + ) |
| 149 | + |
| 150 | + print("\n=== audit log: turn -> SBO3L decision -> KH execution_ref ===") |
| 151 | + for row in audit_log: |
| 152 | + print( |
| 153 | + f" turn={row['turn']:>1} task={row['task']:<10} " |
| 154 | + f"decision={row['decision']:<6} audit={row['audit_event_id']} " |
| 155 | + f"kh={row['kh_execution_ref']}" |
| 156 | + ) |
| 157 | + |
| 158 | + failures = [r for r in audit_log if r["decision"] != "allow"] |
| 159 | + if failures: |
| 160 | + print(f"\nfailed turns: {len(failures)}/{len(audit_log)}") |
| 161 | + return 1 |
| 162 | + print(f"\nall {len(audit_log)} turns allowed + executed via KH") |
| 163 | + return 0 |
| 164 | + |
| 165 | + |
| 166 | +if __name__ == "__main__": |
| 167 | + sys.exit(main()) |
0 commit comments