brutor-runtime-hooks 0.2.0__py3-none-any.whl

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,450 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """The OpenAI Agents SDK (Python): a governed ``Runner``.
5
+
6
+ from brutor.runtime_hooks.adapters.openai_agents import BrutorRunner
7
+
8
+ result = await BrutorRunner(interceptor, on_deny="reject").run(agent, "Write the letter for APP-1042")
9
+
10
+ ``BrutorRunner.run`` is the Agent Hooks host. It sends ``agent_startup`` with every tool of the
11
+ agent and of every agent reachable by handoff (a deny raises ``HookDenied`` and the SDK's runner is
12
+ never called), then runs governed copies of those agents (the caller's agents are never changed):
13
+
14
+ - an input guardrail (``run_in_parallel=False``, so it blocks before the model is called) on the
15
+ starting agent sends ``input``; a deny trips it (``InputGuardrailTripwireTriggered``);
16
+ - a tool input guardrail on every function tool and every local MCP server's tools sends
17
+ ``pre_tool_call``; a deny answers ``reject_content(message)`` (the model is told, the tool does
18
+ not run) or, with ``on_deny="raise"``, trips (``ToolInputGuardrailTripwireTriggered``). A hold
19
+ waits for Brutor's approver inside the guardrail. Tools that need the SDK's own approval are
20
+ judged before that approval is asked for (``pre_approval_tool_input_guardrails``);
21
+ - a tool output guardrail sends ``post_tool_call``; a deny replaces the output the model sees;
22
+ - an output guardrail on every agent sends ``output`` for the final answer; a deny trips it
23
+ (``OutputGuardrailTripwireTriggered``);
24
+ - ``agent_shutdown`` is sent when the run ends (``completed``, ``error`` or ``cancelled``); a run
25
+ that stops for the SDK's own approvals stays open and ``run(agent, result.to_state())``
26
+ continues it on the same session.
27
+
28
+ The SDK's guardrails see function tools and local MCP tools only, so hosted tools, the built-in
29
+ execution tools and agents used as tools (``Agent.as_tool()``) are refused when the agent is
30
+ wrapped (``UncoveredTools``) unless they are named in ``allow_uncovered``. Model calls are not
31
+ hooks of this SDK: point the agents' model client at the gateway to govern them.
32
+
33
+ A ``transform`` (the gateway redacted or rewrote the value) cannot be carried by a guardrail: it
34
+ fails closed as the deny ``host_error:transform_invalid`` ("redaction required"), handled like any
35
+ other deny at that point (``TRANSFORMS``).
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import asyncio
41
+ import copy
42
+ import dataclasses
43
+ import json
44
+ import weakref
45
+ from collections.abc import Mapping, Sequence
46
+ from typing import Any, TypeGuard, cast
47
+
48
+ from agents import (
49
+ Agent,
50
+ FunctionTool,
51
+ GuardrailFunctionOutput,
52
+ Handoff,
53
+ InputGuardrail,
54
+ OutputGuardrail,
55
+ RunConfig,
56
+ Runner,
57
+ RunResult,
58
+ ToolGuardrailFunctionOutput,
59
+ ToolInputGuardrail,
60
+ ToolInputGuardrailData,
61
+ ToolOutputGuardrail,
62
+ ToolOutputGuardrailData,
63
+ )
64
+ from agents.run_config import ToolExecutionConfig
65
+ from agents.run_context import RunContextWrapper
66
+
67
+ from brutor.runtime_hooks._jcs import args_hash
68
+ from brutor.runtime_hooks.errors import HookDenied, UncoveredTools
69
+ from brutor.runtime_hooks.interceptor import BrutorInterceptor
70
+ from brutor.runtime_hooks.resolver import BrutorApprovalResolver
71
+ from brutor.runtime_hooks.session import HookOutcome, HookSession
72
+ from brutor.runtime_hooks.transform import cannot_carry
73
+
74
+ COVERS = ("agent_startup", "input", "pre_tool_call", "post_tool_call", "output", "agent_shutdown")
75
+ NOT_COVERED = ("pre_model_call", "post_model_call")
76
+ FRAMEWORK = "openai_agents"
77
+ ON_DENY = ("reject", "raise")
78
+ ON_APPROVAL = ("block",)
79
+ # What becomes of a transform: the SDK's guardrails can trip or reject, never rewrite, so a transform
80
+ # fails closed at every point (a deny ``host_error:transform_invalid``, "redaction required").
81
+ TRANSFORMS = {
82
+ "input": "fail_closed",
83
+ "output": "fail_closed",
84
+ "pre_tool_call": "fail_closed",
85
+ "post_tool_call": "fail_closed",
86
+ }
87
+ UNCOVERED_WHY = "hosted tools, built-in execution tools and agents used as tools bypass tool guardrails"
88
+
89
+
90
+ def _enforced(outcome: HookOutcome) -> dict[str, Any]:
91
+ """The verdict a guardrail enforces: a transform, which it cannot carry, is a deny."""
92
+ return cannot_carry() if outcome.transformed else outcome.verdict
93
+
94
+
95
+ def deny_message(verdict: Mapping[str, Any]) -> str:
96
+ """The text the model is given for a deny: the gateway's sentence, else its reason."""
97
+ message = verdict.get("message")
98
+ if isinstance(message, str) and message:
99
+ return message
100
+ reason = str(verdict.get("reason") or "denied")
101
+ return reason if reason.startswith("host_error:") else f"Denied by Brutor: {reason}"
102
+
103
+
104
+ def _tool_name(tool: Any) -> str:
105
+ name = getattr(tool, "name", None)
106
+ return name if isinstance(name, str) and name else type(tool).__name__
107
+
108
+
109
+ def _is_covered(tool: Any) -> TypeGuard[FunctionTool]:
110
+ """A function tool the runner calls itself (not an agent run as a tool): its guardrails run."""
111
+ return isinstance(tool, FunctionTool) and not getattr(tool, "_is_agent_tool", False)
112
+
113
+
114
+ def _json_value(value: Any) -> Any:
115
+ """A tool output, an input or a final output as JSON: as it is when it already is JSON."""
116
+ model_dump = getattr(value, "model_dump", None)
117
+ if callable(model_dump):
118
+ value = model_dump(mode="json")
119
+ elif dataclasses.is_dataclass(value) and not isinstance(value, type):
120
+ value = dataclasses.asdict(value)
121
+ try:
122
+ return json.loads(json.dumps(value, ensure_ascii=False, allow_nan=False))
123
+ except (TypeError, ValueError):
124
+ return str(value)
125
+
126
+
127
+ def _args(raw: str) -> dict[str, Any] | None:
128
+ """The tool call's arguments as the model sent them, when they are a JSON object."""
129
+ try:
130
+ parsed = json.loads(raw or "{}")
131
+ except ValueError:
132
+ return None
133
+ return parsed if isinstance(parsed, dict) else None
134
+
135
+
136
+ class _GovernedMCPServer:
137
+ """A local MCP server whose tools carry Brutor's tool guardrails; the caller's server is unchanged.
138
+
139
+ Every attribute is the wrapped server's except the two guardrail lists, which are the
140
+ server's own followed by Brutor's.
141
+ """
142
+
143
+ def __init__(self, server: Any, pre: ToolInputGuardrail[Any], post: ToolOutputGuardrail[Any]) -> None:
144
+ object.__setattr__(self, "_server", server)
145
+ object.__setattr__(self, "tool_input_guardrails", [*(server.tool_input_guardrails or []), pre])
146
+ object.__setattr__(self, "tool_output_guardrails", [*(server.tool_output_guardrails or []), post])
147
+
148
+ def __getattr__(self, name: str) -> Any:
149
+ return getattr(object.__getattribute__(self, "_server"), name)
150
+
151
+ def __setattr__(self, name: str, value: Any) -> None:
152
+ setattr(object.__getattribute__(self, "_server"), name, value)
153
+
154
+
155
+ class BrutorRunner:
156
+ """Runs OpenAI Agents SDK agents with Brutor governing their tools, input and final output.
157
+
158
+ ``on_deny`` (``"reject"`` or ``"raise"``) is how a denied tool call ends: the model is told, or
159
+ the run stops. Holds wait for Brutor's approver in place (``on_approval="block"``, through
160
+ ``resolver``, by default a ``BrutorApprovalResolver``). ``agent_id`` names the agent to the
161
+ gateway (default: the starting agent's name). ``delegation`` is for an agent reached as a
162
+ delegate: the ``x-brutor-delegation-*`` headers it received (``delegation_from_headers``).
163
+ """
164
+
165
+ def __init__(
166
+ self,
167
+ interceptor: BrutorInterceptor,
168
+ *,
169
+ on_deny: str = "reject",
170
+ on_approval: str = "block",
171
+ resolver: Any = None,
172
+ allow_uncovered: Sequence[str] = (),
173
+ agent_id: str | None = None,
174
+ agent_name: str | None = None,
175
+ agent_version: str | None = None,
176
+ session_id: str | None = None,
177
+ delegation: Mapping[str, str] | None = None,
178
+ runner: Any = Runner,
179
+ ) -> None:
180
+ if on_deny not in ON_DENY:
181
+ raise ValueError("on_deny must be 'reject' or 'raise'")
182
+ if on_approval not in ON_APPROVAL:
183
+ raise ValueError("on_approval must be 'block': a hold waits for Brutor's approver in the guardrail")
184
+ self.interceptor = interceptor
185
+ self.on_deny = on_deny
186
+ self.on_approval = on_approval
187
+ self.resolver = resolver if resolver is not None else BrutorApprovalResolver(interceptor)
188
+ self.allow_uncovered = list(allow_uncovered)
189
+ self.agent_id = agent_id
190
+ self.agent_name = agent_name
191
+ self.agent_version = agent_version
192
+ self.session_id = session_id
193
+ self.delegation = delegation
194
+ self._runner = runner
195
+ self.hooks: HookSession | None = None
196
+ self._governed: dict[int, Agent[Any]] = {}
197
+ self._keep: list[Any] = [] # the originals, so the ids above stay theirs
198
+ self._verdicts: dict[tuple[str, str], dict[str, Any]] = {}
199
+ self._registered: list[str] = []
200
+ self._uncovered: list[str] = []
201
+ self._input_guardrail = InputGuardrail(
202
+ guardrail_function=self._on_input, name="brutor_input", run_in_parallel=False
203
+ )
204
+ self._output_guardrail = OutputGuardrail(guardrail_function=self._on_output, name="brutor_output")
205
+ self._pre: ToolInputGuardrail[Any] = ToolInputGuardrail(
206
+ guardrail_function=self._on_pre_tool, name="brutor_pre_tool_call"
207
+ )
208
+ self._post: ToolOutputGuardrail[Any] = ToolOutputGuardrail(
209
+ guardrail_function=self._on_post_tool, name="brutor_post_tool_call"
210
+ )
211
+
212
+ # ------------------------------------------------------------------ the run
213
+
214
+ async def run(self, agent: Agent[Any], input: Any, **kwargs: Any) -> RunResult:
215
+ """``Runner.run(agent, input, **kwargs)`` under Brutor's hooks.
216
+
217
+ ``input`` may be a ``RunState`` of a run this runner left waiting for the SDK's own
218
+ approvals: the run continues on the same session.
219
+ """
220
+ governed = await self._govern_tree(agent, kwargs.get("context"))
221
+ run_config = self._run_config(kwargs.pop("run_config", None))
222
+ if self.hooks is None or not self.hooks.is_open:
223
+ await self._start(agent)
224
+ hooks = self.hooks
225
+ if hooks is None: # pragma: no cover - _start sets it or raises
226
+ raise RuntimeError("no session")
227
+ try:
228
+ result = await self._runner.run(governed, input, run_config=run_config, **kwargs)
229
+ except asyncio.CancelledError:
230
+ await self._close("cancelled")
231
+ raise
232
+ except BaseException:
233
+ await self._close("error")
234
+ raise
235
+ if not getattr(result, "interruptions", None):
236
+ await self._close("completed")
237
+ return cast(RunResult, result)
238
+
239
+ async def _start(self, agent: Agent[Any]) -> None:
240
+ self._verdicts.clear()
241
+ hooks = HookSession(
242
+ self.interceptor,
243
+ agent_id=self.agent_id or agent.name,
244
+ framework=FRAMEWORK,
245
+ tools=self._registered,
246
+ resolver=self.resolver,
247
+ session_id=self.session_id,
248
+ agent_name=self.agent_name,
249
+ agent_version=self.agent_version,
250
+ delegation=self.delegation,
251
+ )
252
+ await hooks.__aenter__() # raises HookDenied: the SDK's runner is never called
253
+ self.hooks = hooks
254
+ if self._uncovered:
255
+ self.interceptor._local_warning(
256
+ hooks.session_id,
257
+ "agent_startup",
258
+ "uncovered_tools",
259
+ "these tools run without hooks: " + ", ".join(self._uncovered),
260
+ tools=list(self._uncovered),
261
+ )
262
+
263
+ async def _close(self, reason: str) -> None:
264
+ """``agent_shutdown`` with ``reason`` (``completed``, ``error`` or ``cancelled``)."""
265
+ hooks, self.hooks = self.hooks, None
266
+ if hooks is not None and hooks.is_open:
267
+ ended: type[BaseException] | None = {
268
+ "cancelled": asyncio.CancelledError,
269
+ "error": RuntimeError,
270
+ }.get(reason)
271
+ await hooks.__aexit__(ended, None, None)
272
+
273
+ def _run_config(self, given: Any) -> RunConfig:
274
+ config = given if isinstance(given, RunConfig) else RunConfig(**(given or {}))
275
+ execution = config.tool_execution or ToolExecutionConfig()
276
+ # Judged before the SDK asks its own approval: Brutor's deny comes first.
277
+ execution = dataclasses.replace(execution, pre_approval_tool_input_guardrails=True)
278
+ return dataclasses.replace(config, tool_execution=execution)
279
+
280
+ # ------------------------------------------------------------------ the governed copies
281
+
282
+ async def _govern_tree(self, start: Agent[Any], context: Any) -> Agent[Any]:
283
+ if id(start) in self._governed:
284
+ return self._governed[id(start)]
285
+ agents: list[Agent[Any]] = []
286
+ uncovered: list[str] = []
287
+ registered: list[str] = []
288
+ pending: list[Agent[Any]] = [start]
289
+ seen: set[int] = set()
290
+ while pending:
291
+ current = pending.pop(0)
292
+ if id(current) in seen:
293
+ continue
294
+ seen.add(id(current))
295
+ agents.append(current)
296
+ for tool in current.tools:
297
+ name = _tool_name(tool)
298
+ registered.append(name)
299
+ if not _is_covered(tool):
300
+ uncovered.append(name)
301
+ if current.mcp_servers:
302
+ for tool in await current.get_mcp_tools(RunContextWrapper(context=context)):
303
+ registered.append(_tool_name(tool))
304
+ for target in current.handoffs:
305
+ if isinstance(target, Agent):
306
+ pending.append(target)
307
+ continue
308
+ ref = getattr(target, "_agent_ref", None)
309
+ resolved = ref() if isinstance(ref, weakref.ReferenceType) else None
310
+ if isinstance(resolved, Agent):
311
+ pending.append(resolved)
312
+ # A handoff whose agent is only known when it is called is governed then.
313
+ refused = [name for name in dict.fromkeys(uncovered) if name not in self.allow_uncovered]
314
+ if refused:
315
+ raise UncoveredTools(refused, UNCOVERED_WHY)
316
+ self._uncovered = list(dict.fromkeys(uncovered))
317
+ self._registered = list(dict.fromkeys(registered))
318
+ clones = {id(a): self._clone(a, is_start=a is start) for a in agents}
319
+ for original in agents:
320
+ clone = clones[id(original)]
321
+ clone.handoffs = [self._handoff(h, clones) for h in original.handoffs]
322
+ self._governed[id(original)] = clone
323
+ self._keep.append(original)
324
+ return clones[id(start)]
325
+
326
+ def _clone(self, agent: Agent[Any], *, is_start: bool) -> Agent[Any]:
327
+ tools: list[Any] = [
328
+ dataclasses.replace(
329
+ tool,
330
+ tool_input_guardrails=[*(tool.tool_input_guardrails or []), self._pre],
331
+ tool_output_guardrails=[*(tool.tool_output_guardrails or []), self._post],
332
+ )
333
+ if _is_covered(tool)
334
+ else tool
335
+ for tool in agent.tools
336
+ ]
337
+ servers = [cast(Any, _GovernedMCPServer(s, self._pre, self._post)) for s in agent.mcp_servers]
338
+ inputs = [*agent.input_guardrails, self._input_guardrail] if is_start else list(agent.input_guardrails)
339
+ return agent.clone(
340
+ tools=tools,
341
+ mcp_servers=servers,
342
+ input_guardrails=inputs,
343
+ output_guardrails=[*agent.output_guardrails, self._output_guardrail],
344
+ )
345
+
346
+ def _handoff(self, target: Any, clones: dict[int, Agent[Any]]) -> Any:
347
+ if isinstance(target, Agent):
348
+ return clones[id(target)]
349
+ original = target.on_invoke_handoff
350
+
351
+ async def invoke(context: RunContextWrapper[Any], arguments: str) -> Agent[Any]:
352
+ chosen = await original(context, arguments)
353
+ return await self._governed_for(chosen)
354
+
355
+ governed = dataclasses.replace(target, on_invoke_handoff=invoke)
356
+ ref = getattr(target, "_agent_ref", None)
357
+ resolved = ref() if isinstance(ref, weakref.ReferenceType) else None
358
+ if isinstance(resolved, Agent) and id(resolved) in clones:
359
+ governed._agent_ref = weakref.ref(clones[id(resolved)])
360
+ return governed
361
+
362
+ async def _governed_for(self, agent: Agent[Any]) -> Agent[Any]:
363
+ """The governed copy of an agent a handoff chose (one known only when it was called)."""
364
+ known = self._governed.get(id(agent))
365
+ if known is not None:
366
+ return known
367
+ refused = [
368
+ _tool_name(t) for t in agent.tools if not _is_covered(t) and _tool_name(t) not in self.allow_uncovered
369
+ ]
370
+ if refused:
371
+ raise UncoveredTools(refused, UNCOVERED_WHY)
372
+ clone = self._clone(agent, is_start=False)
373
+ self._governed[id(agent)] = clone # before its handoffs: a cycle comes back to this copy
374
+ self._keep.append(agent)
375
+ handoffs: list[Agent[Any] | Handoff[Any, Any]] = []
376
+ for target in agent.handoffs:
377
+ if isinstance(target, Agent):
378
+ handoffs.append(await self._governed_for(target))
379
+ else:
380
+ handoffs.append(self._handoff(target, {}))
381
+ clone.handoffs = handoffs
382
+ return clone
383
+
384
+ # ------------------------------------------------------------------ the guardrails
385
+
386
+ def _session(self) -> HookSession:
387
+ if self.hooks is None or not self.hooks.is_open:
388
+ raise HookDenied({"decision": "deny", "reason": "host_error:context_invalid"})
389
+ return self.hooks
390
+
391
+ async def _on_input(self, _ctx: RunContextWrapper[Any], _agent: Agent[Any], given: Any) -> GuardrailFunctionOutput:
392
+ verdict = _enforced(await self._session().input(_json_value(given), role="user"))
393
+ return GuardrailFunctionOutput(
394
+ output_info=_info(verdict), tripwire_triggered=verdict.get("decision") != "allow"
395
+ )
396
+
397
+ async def _on_output(
398
+ self, _ctx: RunContextWrapper[Any], _agent: Agent[Any], output: Any
399
+ ) -> GuardrailFunctionOutput:
400
+ verdict = _enforced(await self._session().output(_json_value(output)))
401
+ return GuardrailFunctionOutput(
402
+ output_info=_info(verdict), tripwire_triggered=verdict.get("decision") != "allow"
403
+ )
404
+
405
+ async def _on_pre_tool(self, data: ToolInputGuardrailData) -> ToolGuardrailFunctionOutput:
406
+ ctx = data.context
407
+ args = _args(ctx.tool_arguments)
408
+ if args is None:
409
+ verdict: dict[str, Any] = {
410
+ "decision": "deny",
411
+ "reason": "host_error:context_invalid",
412
+ "message": "The tool call's arguments are not a JSON object",
413
+ }
414
+ else:
415
+ # The SDK runs these guardrails again after its own approval: one decision per call.
416
+ key = (ctx.tool_call_id, args_hash(args))
417
+ cached = self._verdicts.get(key)
418
+ if cached is None:
419
+ cached = _enforced(await self._session().pre_tool_call(ctx.tool_call_id, ctx.tool_name, args))
420
+ self._verdicts[key] = cached
421
+ verdict = cached
422
+ return self._tool_answer(verdict)
423
+
424
+ async def _on_post_tool(self, data: ToolOutputGuardrailData) -> ToolGuardrailFunctionOutput:
425
+ ctx = data.context
426
+ verdict = _enforced(
427
+ await self._session().post_tool_call(
428
+ ctx.tool_call_id, ctx.tool_name, _args(ctx.tool_arguments) or {}, _json_value(data.output)
429
+ )
430
+ )
431
+ if verdict.get("decision") == "allow":
432
+ return ToolGuardrailFunctionOutput.allow()
433
+ return ToolGuardrailFunctionOutput.reject_content(
434
+ f"Brutor withheld this tool result: {deny_message(verdict)}", output_info=_info(verdict)
435
+ )
436
+
437
+ def _tool_answer(self, verdict: Mapping[str, Any]) -> ToolGuardrailFunctionOutput:
438
+ if verdict.get("decision") == "allow":
439
+ return ToolGuardrailFunctionOutput.allow()
440
+ if self.on_deny == "raise":
441
+ return ToolGuardrailFunctionOutput.raise_exception(output_info=_info(verdict))
442
+ return ToolGuardrailFunctionOutput.reject_content(deny_message(verdict), output_info=_info(verdict))
443
+
444
+ def __repr__(self) -> str:
445
+ return f"BrutorRunner(on_deny={self.on_deny!r}, on_approval={self.on_approval!r})"
446
+
447
+
448
+ def _info(verdict: Mapping[str, Any]) -> dict[str, Any]:
449
+ """What a tripwire carries: the decision, reason and message (never the approval block)."""
450
+ return {k: copy.deepcopy(verdict[k]) for k in ("decision", "reason", "message") if k in verdict}