maigp-agno 1.0.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,56 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .venv/
8
+ .eggs/
9
+
10
+ # Node
11
+ node_modules/
12
+ dist/
13
+
14
+ # Go
15
+ bin/
16
+
17
+ # Rust
18
+ target/
19
+
20
+ # .NET
21
+ bin/
22
+ obj/
23
+
24
+ # Java
25
+ *.class
26
+ out/
27
+
28
+ # IDE
29
+ .idea/
30
+ .vscode/
31
+ .kiro/
32
+ *.swp
33
+
34
+ # OS
35
+ .DS_Store
36
+ Thumbs.db
37
+
38
+ # Secrets (never commit)
39
+ .env
40
+ *.pem
41
+ *.key
42
+ *.pdf
43
+ BACKLOG/
44
+ patent/
45
+ docs/.archive/
46
+ review/
47
+
48
+ # Generated navigable spec split — derived from the monoliths by
49
+ # specification/tools/spec_split.py; the manifest + monoliths are the
50
+ # source of truth, not this output. Same convention as Mars (spec/*/*/).
51
+ specification/*/*/
52
+ specification/split-index.md
53
+
54
+ # Local rendering/preview site — self-contained, not part of the
55
+ # published specification, never pushed.
56
+ site/
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.5
2
+ Name: maigp-agno
3
+ Version: 1.0.0
4
+ Summary: MAIGP governance adapter for the Agno agent framework: blocks model calls and tool calls the authority does not allow
5
+ Requires-Python: >=3.11
6
+ Requires-Dist: agno<4,>=3.0.11
7
+ Requires-Dist: maigp-agent-core>=1.4.0
8
+ Requires-Dist: maigp-client>=5.10.0
9
+ Provides-Extra: agency
10
+ Requires-Dist: maigp-agent-core[agency]>=1.3.0; extra == 'agency'
11
+ Provides-Extra: dev
12
+ Requires-Dist: httpx>=0.25.0; extra == 'dev'
13
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
14
+ Requires-Dist: pytest>=8; extra == 'dev'
15
+ Requires-Dist: respx>=0.21; extra == 'dev'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # maigp-agno
19
+
20
+ MAIGP governance for [Agno](https://github.com/agno-agi/agno) (the agent framework formerly called phidata).
21
+
22
+ Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI
23
+ systems. Every governed call is checked with the governance authority before it runs and recorded after it
24
+ ran. This adapter makes that check able to stop an Agno agent: a model call or tool call the authority does
25
+ not allow never reaches the model provider or the tool function.
26
+
27
+ ## What it does
28
+
29
+ | Agno call | Before it runs | If not allowed | After it ran |
30
+ |---|---|---|---|
31
+ | Model call (every provider round trip, sync, async and streaming) | MAIGP **CHECK** | The provider is never contacted. Agno ends the run: `RunOutput.status == RunStatus.error`, the reason is in `content`. | **RECORD** with tokens, duration, status |
32
+ | Tool call (every tool of the agent) | MAIGP **TOOL_REQUEST** with the SHA-256 of the tool input and the hash of the tool definition (name, description, parameter schema) | The tool function is never called. Agno records a failed tool call (`tool_call_error` is True) and the model reads the reason as the tool result. The run continues. | **RECORD** with `output_ref` = SHA-256 of the result and the tool definition hash |
33
+
34
+ Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` lets a call run. `DENY`, `RATE_LIMITED`, `UNCHECKED`, a missing or
35
+ unknown decision, an unreachable authority, any error while asking, and a check slower than `check_timeout`
36
+ (default 10 seconds) all stop the call. This holds in ENFORCE and in REPORT mode.
37
+
38
+ ## Install
39
+
40
+ ```bash
41
+ pip install maigp-agno
42
+ ```
43
+
44
+ This installs `maigp-client`, `maigp-agent-core` and `agno>=3.0.11,<4`. It needs Python 3.11 or newer.
45
+
46
+ ## Quick start
47
+
48
+ ```python
49
+ from agno.agent import Agent
50
+ from agno.run.base import RunStatus
51
+ from agno.models.openai import OpenAIChat
52
+ from agno.tools import tool
53
+
54
+ from maigp_agno import MaigpAgno, MaigpGovernance
55
+
56
+
57
+ @tool
58
+ def transfer_funds(account: str, amount: int) -> str:
59
+ """Move money between accounts."""
60
+ return f"moved {amount} to {account}"
61
+
62
+
63
+ gov = MaigpGovernance(
64
+ gov_url="https://gov.example.com", # an empty gov_url is refused: it would allow everything
65
+ app_id="payments-agent",
66
+ hmac_secret="change-me",
67
+ )
68
+ maigp = MaigpAgno(gov, use_case="payments")
69
+
70
+ agent = Agent(
71
+ name="payments",
72
+ model=maigp.governed_model(OpenAIChat(id="gpt-4o")), # CHECK before every model call
73
+ tools=[transfer_funds],
74
+ tool_hooks=[maigp.tool_hook], # TOOL_REQUEST before every tool call
75
+ )
76
+
77
+ run = agent.run("Move 5 to acct-9")
78
+ if run.status == RunStatus.error:
79
+ print("blocked or failed:", run.content)
80
+ else:
81
+ print(run.content)
82
+ ```
83
+
84
+ `agent.arun(...)` and streaming (`stream=True`) are governed the same way.
85
+
86
+ ## API
87
+
88
+ - `MaigpAgno(governance, *, use_case="", check_timeout=10.0, tool_version="1.0.0")`
89
+ - `.tool_hook`: pass as `tool_hooks=[maigp.tool_hook]` to `Agent` or `Team`.
90
+ - `.governed_model(model)`: returns a copy of an Agno `Model` that CHECKs before each provider call.
91
+ The copy is an instance of a subclass of the model's own class, so every provider option and Agno
92
+ feature keeps working. The model you pass in is not changed.
93
+ - `governed_model(model, governance, **kwargs)`: shortcut that builds a `MaigpAgno` for you.
94
+ - `MaigpGovernance`: the `maigp-agent-core` `AgentGovernance` (re-exported for convenience).
95
+ - `MaigpModelBlocked` (an Agno `AgnoError`): raised inside the model call when it is blocked. Carries
96
+ `.decision` and `.reason`.
97
+ - `MaigpToolBlocked` (an Agno `AgentRunException`): raised inside the tool hook when a tool call is blocked.
98
+ Carries `.decision` and `.reason`.
99
+
100
+ ## How blocking works
101
+
102
+ Agno has two supported extension points that can stop a call. This adapter uses exactly these and patches
103
+ nothing.
104
+
105
+ **Tools: `tool_hooks`.** Agno builds a chain of hooks around every tool function (`Agent(tool_hooks=[...])`,
106
+ documented in Agno's tool hooks). Each hook is handed `func`, the next step of the chain. A hook that does
107
+ not call `func` stops the tool. `maigp.tool_hook` sends TOOL_REQUEST first and calls `func` only for an
108
+ allowing decision. Otherwise it raises `MaigpToolBlocked`, which Agno turns into a failed tool result. The
109
+ hook works in both Agno chains: in `agent.run` it is a plain function, in `agent.arun` it returns a coroutine
110
+ that Agno awaits (the adapter picks the right one by looking at the `func` Agno passes in).
111
+
112
+ **Models: a `Model` subclass.** Agno has no hook that runs per model call: `pre_hooks` and `post_hooks` run
113
+ once per run, so a run with several tool rounds would be checked only once. Every provider round trip goes
114
+ through the four abstract methods of `agno.models.base.Model`: `invoke`, `ainvoke`, `invoke_stream` and
115
+ `ainvoke_stream`. `governed_model` returns a subclass of your model's class that sends CHECK before calling
116
+ the real method and raises `MaigpModelBlocked` instead of calling it when the call is not allowed. It also
117
+ sees the tool definitions Agno hands the model (through the public `response` methods) so that the tool
118
+ definition hash is the one the model was shown.
119
+
120
+ ## Fail-closed behaviour
121
+
122
+ | Situation | Model call | Tool call |
123
+ |---|---|---|
124
+ | ALLOW, ALLOW_WITH_CONSTRAINTS | runs | runs |
125
+ | DENY, RATE_LIMITED | blocked | blocked |
126
+ | UNCHECKED, no decision, unknown decision text | blocked | blocked |
127
+ | Authority unreachable, HTTP error, bad body | blocked | blocked |
128
+ | Check slower than `check_timeout` | blocked | blocked |
129
+ | Any exception in the check path | blocked | blocked |
130
+ | Client disabled (empty `gov_url`) | `MaigpAgno(...)` raises `RuntimeError` | same |
131
+ | AIAP agency gate refuses (opt-in) | blocked | blocked |
132
+
133
+ A blocked model call ends the run with `RunStatus.error`. A blocked tool call is a failed tool call the model
134
+ can read; the run continues, so the model may try another tool, and that tool is checked in turn. A blocked
135
+ call is never recorded as run. A RECORD that fails is logged and does not fail the run.
136
+
137
+ Agno retries (`Agent(retries=...)`, `Model(retries=...)`) repeat the check on every attempt.
138
+
139
+ ## Configuration
140
+
141
+ - `use_case`: use case sent on CHECK and RECORD. Default: the agent's `name` for tools, `"agno-agent"` for
142
+ models and unnamed agents. Set it explicitly to make the two agree.
143
+ - `check_timeout`: seconds each CHECK, TOOL_REQUEST, agency request and RECORD may take. Default 10.
144
+ - `tool_version`: `tool_version` sent in TOOL_REQUEST. Default `"1.0.0"`.
145
+ - Mode (`ENFORCE` or `REPORT`), agent identity, tool policies and the AIAP agency gate are set on the
146
+ `MaigpGovernance` (see `maigp-agent-core`). With an `AgencyGate` configured, every allowed model and tool
147
+ call also needs an agency grant, and a refusal blocks the call in every mode.
148
+
149
+ ## Limitations
150
+
151
+ - **Decision cache.** `maigp-client` caches a CHECK decision per (use case, model) for the `ttl_seconds` the
152
+ authority returned (300 when it returns none). Within that time a later model call is answered from the
153
+ cache and the authority is not asked again. Have the authority return a short `ttl_seconds` if every
154
+ model call must be decided afresh. Tool requests are never cached.
155
+ - **Constraints.** `ALLOW_WITH_CONSTRAINTS` lets the call run. The adapter does not interpret the
156
+ constraints; they are returned by the authority and are not applied to the call.
157
+ - **Agno version.** Tested against agno 3.0.11, 3.1.0, 3.1.6, 3.1.12, 3.2.0 and 3.2.1. Releases
158
+ before 3.0.11 (3.0.0 to 3.0.10, and 2.9.0) do not await a sync hook that returns a coroutine in `arun`;
159
+ with those the async tool test fails because the tool is never run, so the adapter requires 3.0.11 or
160
+ newer. Older 2.x releases were not tested and are not supported.
161
+ - **Where to put the hook.** Agent-level `tool_hooks` replace any hooks set on a single tool or toolkit.
162
+ Put `maigp.tool_hook` last in the list so that it checks the call that really runs. Do not wrap it in an
163
+ `async def`: Agno skips async hooks in a synchronous `agent.run`, and a skipped hook governs nothing.
164
+ - **What is not covered.** Tools the model provider runs itself (Agno "builtin tools" passed as dicts, for
165
+ example a provider's web search), tool calls made by code outside Agno's tool chain, and model calls made
166
+ by something other than the governed model (for example a separate Agno `Team` member or a
167
+ `FallbackModel` inner model you did not wrap). Wrap every model and give every agent or team the hook.
168
+ A `Team`'s `tool_hooks` apply to the team's own tools, not to its members' tools.
169
+ - **Streaming.** CHECK happens before the first chunk. RECORD is sent when the stream ends or fails. A tool
170
+ that returns a generator is checked before it starts and recorded without `output_ref`, because there is no
171
+ single result to hash.
172
+ - **Tool definition hash.** It is sent when the definition can be found (the governed model saw it, or it is
173
+ in `agent.tools`). When it cannot be found the field is omitted and never replaced by a placeholder; an
174
+ authority that pins an approved hash for the tool then denies the call.
175
+ - **One adapter per application.** The governance client's HTTP connection is bound to a private event loop
176
+ the adapter runs on a background thread. Do not also use the same `MaigpGovernance` from your own event loop.
177
+ - **Tests.** The tests run a real Agno `Agent` with a scripted model and answer the authority with `respx`. They
178
+ do not call any model API.
@@ -0,0 +1,161 @@
1
+ # maigp-agno
2
+
3
+ MAIGP governance for [Agno](https://github.com/agno-agi/agno) (the agent framework formerly called phidata).
4
+
5
+ Part of **MAIGP**, the Mediated AI Governance Protocol: a runtime consent, scope and evidence layer for AI
6
+ systems. Every governed call is checked with the governance authority before it runs and recorded after it
7
+ ran. This adapter makes that check able to stop an Agno agent: a model call or tool call the authority does
8
+ not allow never reaches the model provider or the tool function.
9
+
10
+ ## What it does
11
+
12
+ | Agno call | Before it runs | If not allowed | After it ran |
13
+ |---|---|---|---|
14
+ | Model call (every provider round trip, sync, async and streaming) | MAIGP **CHECK** | The provider is never contacted. Agno ends the run: `RunOutput.status == RunStatus.error`, the reason is in `content`. | **RECORD** with tokens, duration, status |
15
+ | Tool call (every tool of the agent) | MAIGP **TOOL_REQUEST** with the SHA-256 of the tool input and the hash of the tool definition (name, description, parameter schema) | The tool function is never called. Agno records a failed tool call (`tool_call_error` is True) and the model reads the reason as the tool result. The run continues. | **RECORD** with `output_ref` = SHA-256 of the result and the tool definition hash |
16
+
17
+ Only `ALLOW` and `ALLOW_WITH_CONSTRAINTS` lets a call run. `DENY`, `RATE_LIMITED`, `UNCHECKED`, a missing or
18
+ unknown decision, an unreachable authority, any error while asking, and a check slower than `check_timeout`
19
+ (default 10 seconds) all stop the call. This holds in ENFORCE and in REPORT mode.
20
+
21
+ ## Install
22
+
23
+ ```bash
24
+ pip install maigp-agno
25
+ ```
26
+
27
+ This installs `maigp-client`, `maigp-agent-core` and `agno>=3.0.11,<4`. It needs Python 3.11 or newer.
28
+
29
+ ## Quick start
30
+
31
+ ```python
32
+ from agno.agent import Agent
33
+ from agno.run.base import RunStatus
34
+ from agno.models.openai import OpenAIChat
35
+ from agno.tools import tool
36
+
37
+ from maigp_agno import MaigpAgno, MaigpGovernance
38
+
39
+
40
+ @tool
41
+ def transfer_funds(account: str, amount: int) -> str:
42
+ """Move money between accounts."""
43
+ return f"moved {amount} to {account}"
44
+
45
+
46
+ gov = MaigpGovernance(
47
+ gov_url="https://gov.example.com", # an empty gov_url is refused: it would allow everything
48
+ app_id="payments-agent",
49
+ hmac_secret="change-me",
50
+ )
51
+ maigp = MaigpAgno(gov, use_case="payments")
52
+
53
+ agent = Agent(
54
+ name="payments",
55
+ model=maigp.governed_model(OpenAIChat(id="gpt-4o")), # CHECK before every model call
56
+ tools=[transfer_funds],
57
+ tool_hooks=[maigp.tool_hook], # TOOL_REQUEST before every tool call
58
+ )
59
+
60
+ run = agent.run("Move 5 to acct-9")
61
+ if run.status == RunStatus.error:
62
+ print("blocked or failed:", run.content)
63
+ else:
64
+ print(run.content)
65
+ ```
66
+
67
+ `agent.arun(...)` and streaming (`stream=True`) are governed the same way.
68
+
69
+ ## API
70
+
71
+ - `MaigpAgno(governance, *, use_case="", check_timeout=10.0, tool_version="1.0.0")`
72
+ - `.tool_hook`: pass as `tool_hooks=[maigp.tool_hook]` to `Agent` or `Team`.
73
+ - `.governed_model(model)`: returns a copy of an Agno `Model` that CHECKs before each provider call.
74
+ The copy is an instance of a subclass of the model's own class, so every provider option and Agno
75
+ feature keeps working. The model you pass in is not changed.
76
+ - `governed_model(model, governance, **kwargs)`: shortcut that builds a `MaigpAgno` for you.
77
+ - `MaigpGovernance`: the `maigp-agent-core` `AgentGovernance` (re-exported for convenience).
78
+ - `MaigpModelBlocked` (an Agno `AgnoError`): raised inside the model call when it is blocked. Carries
79
+ `.decision` and `.reason`.
80
+ - `MaigpToolBlocked` (an Agno `AgentRunException`): raised inside the tool hook when a tool call is blocked.
81
+ Carries `.decision` and `.reason`.
82
+
83
+ ## How blocking works
84
+
85
+ Agno has two supported extension points that can stop a call. This adapter uses exactly these and patches
86
+ nothing.
87
+
88
+ **Tools: `tool_hooks`.** Agno builds a chain of hooks around every tool function (`Agent(tool_hooks=[...])`,
89
+ documented in Agno's tool hooks). Each hook is handed `func`, the next step of the chain. A hook that does
90
+ not call `func` stops the tool. `maigp.tool_hook` sends TOOL_REQUEST first and calls `func` only for an
91
+ allowing decision. Otherwise it raises `MaigpToolBlocked`, which Agno turns into a failed tool result. The
92
+ hook works in both Agno chains: in `agent.run` it is a plain function, in `agent.arun` it returns a coroutine
93
+ that Agno awaits (the adapter picks the right one by looking at the `func` Agno passes in).
94
+
95
+ **Models: a `Model` subclass.** Agno has no hook that runs per model call: `pre_hooks` and `post_hooks` run
96
+ once per run, so a run with several tool rounds would be checked only once. Every provider round trip goes
97
+ through the four abstract methods of `agno.models.base.Model`: `invoke`, `ainvoke`, `invoke_stream` and
98
+ `ainvoke_stream`. `governed_model` returns a subclass of your model's class that sends CHECK before calling
99
+ the real method and raises `MaigpModelBlocked` instead of calling it when the call is not allowed. It also
100
+ sees the tool definitions Agno hands the model (through the public `response` methods) so that the tool
101
+ definition hash is the one the model was shown.
102
+
103
+ ## Fail-closed behaviour
104
+
105
+ | Situation | Model call | Tool call |
106
+ |---|---|---|
107
+ | ALLOW, ALLOW_WITH_CONSTRAINTS | runs | runs |
108
+ | DENY, RATE_LIMITED | blocked | blocked |
109
+ | UNCHECKED, no decision, unknown decision text | blocked | blocked |
110
+ | Authority unreachable, HTTP error, bad body | blocked | blocked |
111
+ | Check slower than `check_timeout` | blocked | blocked |
112
+ | Any exception in the check path | blocked | blocked |
113
+ | Client disabled (empty `gov_url`) | `MaigpAgno(...)` raises `RuntimeError` | same |
114
+ | AIAP agency gate refuses (opt-in) | blocked | blocked |
115
+
116
+ A blocked model call ends the run with `RunStatus.error`. A blocked tool call is a failed tool call the model
117
+ can read; the run continues, so the model may try another tool, and that tool is checked in turn. A blocked
118
+ call is never recorded as run. A RECORD that fails is logged and does not fail the run.
119
+
120
+ Agno retries (`Agent(retries=...)`, `Model(retries=...)`) repeat the check on every attempt.
121
+
122
+ ## Configuration
123
+
124
+ - `use_case`: use case sent on CHECK and RECORD. Default: the agent's `name` for tools, `"agno-agent"` for
125
+ models and unnamed agents. Set it explicitly to make the two agree.
126
+ - `check_timeout`: seconds each CHECK, TOOL_REQUEST, agency request and RECORD may take. Default 10.
127
+ - `tool_version`: `tool_version` sent in TOOL_REQUEST. Default `"1.0.0"`.
128
+ - Mode (`ENFORCE` or `REPORT`), agent identity, tool policies and the AIAP agency gate are set on the
129
+ `MaigpGovernance` (see `maigp-agent-core`). With an `AgencyGate` configured, every allowed model and tool
130
+ call also needs an agency grant, and a refusal blocks the call in every mode.
131
+
132
+ ## Limitations
133
+
134
+ - **Decision cache.** `maigp-client` caches a CHECK decision per (use case, model) for the `ttl_seconds` the
135
+ authority returned (300 when it returns none). Within that time a later model call is answered from the
136
+ cache and the authority is not asked again. Have the authority return a short `ttl_seconds` if every
137
+ model call must be decided afresh. Tool requests are never cached.
138
+ - **Constraints.** `ALLOW_WITH_CONSTRAINTS` lets the call run. The adapter does not interpret the
139
+ constraints; they are returned by the authority and are not applied to the call.
140
+ - **Agno version.** Tested against agno 3.0.11, 3.1.0, 3.1.6, 3.1.12, 3.2.0 and 3.2.1. Releases
141
+ before 3.0.11 (3.0.0 to 3.0.10, and 2.9.0) do not await a sync hook that returns a coroutine in `arun`;
142
+ with those the async tool test fails because the tool is never run, so the adapter requires 3.0.11 or
143
+ newer. Older 2.x releases were not tested and are not supported.
144
+ - **Where to put the hook.** Agent-level `tool_hooks` replace any hooks set on a single tool or toolkit.
145
+ Put `maigp.tool_hook` last in the list so that it checks the call that really runs. Do not wrap it in an
146
+ `async def`: Agno skips async hooks in a synchronous `agent.run`, and a skipped hook governs nothing.
147
+ - **What is not covered.** Tools the model provider runs itself (Agno "builtin tools" passed as dicts, for
148
+ example a provider's web search), tool calls made by code outside Agno's tool chain, and model calls made
149
+ by something other than the governed model (for example a separate Agno `Team` member or a
150
+ `FallbackModel` inner model you did not wrap). Wrap every model and give every agent or team the hook.
151
+ A `Team`'s `tool_hooks` apply to the team's own tools, not to its members' tools.
152
+ - **Streaming.** CHECK happens before the first chunk. RECORD is sent when the stream ends or fails. A tool
153
+ that returns a generator is checked before it starts and recorded without `output_ref`, because there is no
154
+ single result to hash.
155
+ - **Tool definition hash.** It is sent when the definition can be found (the governed model saw it, or it is
156
+ in `agent.tools`). When it cannot be found the field is omitted and never replaced by a placeholder; an
157
+ authority that pins an approved hash for the tool then denies the call.
158
+ - **One adapter per application.** The governance client's HTTP connection is bound to a private event loop
159
+ the adapter runs on a background thread. Do not also use the same `MaigpGovernance` from your own event loop.
160
+ - **Tests.** The tests run a real Agno `Agent` with a scripted model and answer the authority with `respx`. They
161
+ do not call any model API.
@@ -0,0 +1,14 @@
1
+ """MAIGP-Agno: governance adapter for the Agno agent framework.
2
+
3
+ maigp = MaigpAgno(MaigpGovernance(gov_url=..., app_id=..., hmac_secret=...))
4
+ agent = Agent(model=maigp.governed_model(OpenAIChat(id="gpt-4o")), tools=[...],
5
+ tool_hooks=[maigp.tool_hook])
6
+ """
7
+
8
+ __version__ = "1.0.0"
9
+
10
+ from maigp_agent_core import AgentGovernance as MaigpGovernance
11
+
12
+ from .adapter import MaigpAgno, MaigpModelBlocked, MaigpToolBlocked, governed_model
13
+
14
+ __all__ = ["MaigpAgno", "MaigpGovernance", "MaigpModelBlocked", "MaigpToolBlocked", "governed_model"]
@@ -0,0 +1,57 @@
1
+ """One private event loop on a daemon thread, so the governance client is always used from the same loop.
2
+
3
+ ``MaigpClient`` owns an ``httpx.AsyncClient`` that must not hop between event loops, while Agno runs
4
+ tools both from plain threads (``agent.run``) and from the caller's loop (``agent.arun``). Every
5
+ CHECK / TOOL_REQUEST / RECORD therefore runs on this one loop; sync callers block on a future, async
6
+ callers await a wrapped future. A timeout cancels the in-flight call.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import concurrent.futures
13
+ import threading
14
+ from typing import Any, Awaitable, Callable
15
+
16
+
17
+ class GovernanceRunner:
18
+ def __init__(self) -> None:
19
+ self._lock = threading.Lock()
20
+ self._loop: asyncio.AbstractEventLoop | None = None
21
+
22
+ def _ensure_loop(self) -> asyncio.AbstractEventLoop:
23
+ with self._lock:
24
+ if self._loop is None or self._loop.is_closed():
25
+ loop = asyncio.new_event_loop()
26
+ ready = threading.Event()
27
+
28
+ def _run() -> None:
29
+ asyncio.set_event_loop(loop)
30
+ loop.call_soon(ready.set)
31
+ loop.run_forever()
32
+
33
+ threading.Thread(target=_run, name="maigp-agno-governance", daemon=True).start()
34
+ ready.wait()
35
+ self._loop = loop
36
+ return self._loop
37
+
38
+ def _submit(self, factory: Callable[[], Awaitable[Any]]) -> concurrent.futures.Future:
39
+ async def _wrapped() -> Any:
40
+ return await factory()
41
+ return asyncio.run_coroutine_threadsafe(_wrapped(), self._ensure_loop())
42
+
43
+ def run_sync(self, factory: Callable[[], Awaitable[Any]], timeout: float) -> Any:
44
+ fut = self._submit(factory)
45
+ try:
46
+ return fut.result(timeout=timeout)
47
+ except concurrent.futures.TimeoutError:
48
+ fut.cancel()
49
+ raise TimeoutError(f"timed out after {timeout:g}s") from None
50
+
51
+ async def run_async(self, factory: Callable[[], Awaitable[Any]], timeout: float) -> Any:
52
+ fut = self._submit(factory)
53
+ try:
54
+ return await asyncio.wait_for(asyncio.wrap_future(fut), timeout=timeout)
55
+ except asyncio.TimeoutError:
56
+ fut.cancel()
57
+ raise TimeoutError(f"timed out after {timeout:g}s") from None