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,118 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """Microsoft Agent Framework: Brutor as the interceptor of the framework's own Agent Hooks host.
5
+
6
+ from brutor.runtime_hooks.adapters.agent_framework import brutor_middleware
7
+
8
+ agent = ChatAgent(chat_client=..., tools=[...], middleware=[brutor_middleware(interceptor)])
9
+
10
+ The framework is the host: it builds the contexts of all eight interception points, owns their
11
+ sequence and applies the verdicts (``agent_framework.create_agent_hooks_middleware``, an
12
+ experimental API, which is why the extra pins ``agent-framework-core`` exactly). The bundle goes
13
+ first in ``middleware`` and is the only Agent Hooks bundle of the agent. Holds are resolved by
14
+ ``BrutorApprovalResolver`` unless another resolver is given. A ``transform`` the gateway answers is
15
+ applied by the framework's host (``TRANSFORMS``); one it cannot apply is its
16
+ ``host_error:transform_invalid`` deny.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Mapping
22
+ from typing import Any, cast
23
+
24
+ from agent_framework import create_agent_hooks_middleware
25
+ from agent_hooks import ApprovalOutcome, ApprovalResolution, Verdict
26
+
27
+ from brutor.runtime_hooks._delegation import check_delegation
28
+ from brutor.runtime_hooks.interceptor import POINTS, BrutorInterceptor
29
+ from brutor.runtime_hooks.resolver import BrutorApprovalResolver
30
+
31
+ COVERS = POINTS
32
+ # What becomes of a transform at each point: the framework's Agent Hooks host applies it to the
33
+ # target itself (the arguments the function receives, the messages sent, the result used, ...).
34
+ TRANSFORMS = {
35
+ "input": "applied",
36
+ "pre_model_call": "applied",
37
+ "post_model_call": "applied",
38
+ "pre_tool_call": "applied",
39
+ "post_tool_call": "applied",
40
+ "output": "applied",
41
+ }
42
+ # The framework bounds every interceptor call and every resolver call with one timeout; a resolver
43
+ # waits for a person, so the bound is the resolver's own wait plus this margin.
44
+ RESOLVER_MARGIN_S = 30.0
45
+
46
+
47
+ class AgentHooksResolver:
48
+ """``BrutorApprovalResolver`` with the Agent Hooks SDK's types at the seam."""
49
+
50
+ def __init__(self, resolver: Any) -> None:
51
+ self.resolver = resolver
52
+
53
+ async def resolve(self, request: Any, /) -> Any:
54
+ answer = await self.resolver.resolve(request)
55
+ if isinstance(answer, ApprovalResolution):
56
+ return answer
57
+ verdict = answer.get("verdict")
58
+ return ApprovalResolution(
59
+ outcome=ApprovalOutcome(answer["outcome"]),
60
+ context_identity=answer.get("context_identity"),
61
+ verdict=Verdict.from_wire(verdict) if verdict is not None else None,
62
+ )
63
+
64
+
65
+ class DelegateInterceptor:
66
+ """The interceptor of a delegate: the delegation it received rides on ``agent_startup`` only.
67
+
68
+ The framework builds the contexts, so the delegation is added to the ``agent_startup`` context
69
+ here, as the extension the gateway reads; every other point is passed through unchanged.
70
+ """
71
+
72
+ def __init__(self, interceptor: BrutorInterceptor, delegation: Mapping[str, str]) -> None:
73
+ self.interceptor = interceptor
74
+ self.delegation = check_delegation(delegation)
75
+
76
+ @property
77
+ def timeout(self) -> float:
78
+ return self.interceptor.timeout
79
+
80
+ async def intercept(self, context: Mapping[str, Any], /) -> Any:
81
+ if context.get("interception_point") == "agent_startup":
82
+ extensions = dict(context.get("extensions") or {})
83
+ brutor = dict(extensions.get("brutor") or {})
84
+ brutor["delegation"] = dict(self.delegation)
85
+ extensions["brutor"] = brutor
86
+ context = {**context, "extensions": extensions}
87
+ return await self.interceptor.intercept(context)
88
+
89
+ def __repr__(self) -> str:
90
+ return "DelegateInterceptor()"
91
+
92
+
93
+ def brutor_middleware(
94
+ interceptor: BrutorInterceptor,
95
+ *,
96
+ mode: str = "enforce",
97
+ resolver: Any = None,
98
+ timeout: float | None = None,
99
+ record_sink: Any = None,
100
+ delegation: Mapping[str, str] | None = None,
101
+ ) -> Any:
102
+ """The framework's Agent Hooks middleware bundle with ``interceptor`` as its only interceptor.
103
+
104
+ ``record_sink`` receives the framework's interception records (they carry no content).
105
+ ``delegation`` is for an agent reached as a delegate: the ``x-brutor-delegation-*`` headers it
106
+ received (``delegation_from_headers``); ``agent_startup`` then joins the caller's run.
107
+ """
108
+ seam = resolver if resolver is not None else BrutorApprovalResolver(interceptor)
109
+ if timeout is None:
110
+ timeout = max(interceptor.timeout, float(getattr(seam, "max_wait", 0.0)) + RESOLVER_MARGIN_S)
111
+ return create_agent_hooks_middleware(
112
+ # Both are async: the framework awaits them (its protocols are typed for the sync form).
113
+ {"brutor": cast(Any, DelegateInterceptor(interceptor, delegation) if delegation else interceptor)},
114
+ resolver=cast(Any, AgentHooksResolver(seam)),
115
+ mode=mode,
116
+ timeout=timeout,
117
+ record_sink=record_sink,
118
+ )
@@ -0,0 +1,352 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """The Claude Agent SDK (Python): a governed ``ClaudeSDKClient``.
5
+
6
+ from brutor.runtime_hooks.adapters.claude_agent_sdk import BrutorClaudeSession
7
+
8
+ async with BrutorClaudeSession(interceptor, options, agent_id="letters-agent") as client:
9
+ await client.query("Write the decision letter for APP-1042")
10
+ async for message in client.receive_response():
11
+ ...
12
+
13
+ The session is the Agent Hooks host. Entering it sends ``agent_startup`` (a deny raises
14
+ ``HookDenied`` and no client is opened); the SDK's hook callbacks map ``UserPromptSubmit`` to
15
+ ``input``, ``PreToolUse`` to ``pre_tool_call``, ``PostToolUse`` and ``PostToolUseFailure`` to
16
+ ``post_tool_call`` (a denied prompt makes the turn's stream raise ``HookDenied``); each turn's
17
+ messages are held back until the final ``ResultMessage`` has passed ``output`` (a deny raises
18
+ ``OutputDenied`` and nothing of the turn is yielded); leaving the session
19
+ sends ``agent_shutdown``. A delegate passes ``delegation=`` (the ``x-brutor-delegation-*`` headers
20
+ it received) to join its caller's run. The SDK has no model-call hooks: ``pre_model_call`` and
21
+ ``post_model_call`` are governed by pointing the SDK at the gateway (``ANTHROPIC_BASE_URL``).
22
+
23
+ A hold at ``PreToolUse`` is resolved in the callback by default (``on_approval="block"``: the
24
+ callback waits for the approver); ``on_approval="defer"`` answers ``defer`` and the turn ends, to be
25
+ resumed by the application once approved. A Brutor allow answers no permission decision at all
26
+ (``{}``), so Claude's own permission rules (``allowed_tools``, ``disallowed_tools``, the permission
27
+ mode) still apply and can only be stricter; ``allow`` is never answered, it would skip them. ``ask``
28
+ is never answered either: it would let the local user approve instead of Brutor's approver.
29
+ Every callback is registered with ``on_failure="block"``,
30
+ and a callback that cannot get a decision answers a deny itself: an interceptor failure blocks the
31
+ tool.
32
+
33
+ A ``transform`` (the gateway redacted or rewrote the value; ``TRANSFORMS``) is applied where the
34
+ SDK can carry it and fails closed where it cannot:
35
+
36
+ - ``PreToolUse``: ``updatedInput``, the transformed arguments as a new object, and no
37
+ ``permissionDecision`` (the SDK replaces the whole input; Claude's own permission rules then judge
38
+ the transformed input, so Brutor is only ever stricter);
39
+ - ``UserPromptSubmit``: the hook cannot rewrite the prompt, so the prompt is blocked
40
+ (``"redaction required"``) and the turn's stream raises ``HookDenied``;
41
+ - ``PostToolUse``: an MCP tool's result is replaced (``updatedMCPToolOutput``); a built-in tool's
42
+ answer is a block (``"redaction required"``), as for a deny: Claude is told, and the CLI keeps
43
+ the built-in result itself. The SDK's ``updatedToolOutput`` must match the built-in tool's own
44
+ output schema and silently keeps the original output when it does not, so it cannot carry a
45
+ redaction. Keep content that needs redaction out of built-in tools (route it through an MCP
46
+ tool). ``PostToolUseFailure`` cannot replace the error, so it is blocked too;
47
+ - the final answer: the turn is yielded with a copy of the ``ResultMessage`` carrying the
48
+ transformed text, and without the text and thinking of the turn's assistant messages and the
49
+ partial-message events (they hold the answer as it was before the redaction).
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import dataclasses
55
+ from collections.abc import AsyncIterator, Callable, Mapping, Sequence
56
+ from types import TracebackType
57
+ from typing import Any, cast
58
+
59
+ from claude_agent_sdk import (
60
+ AssistantMessage,
61
+ ClaudeSDKClient,
62
+ HookMatcher,
63
+ ResultMessage,
64
+ StreamEvent,
65
+ TextBlock,
66
+ ThinkingBlock,
67
+ )
68
+
69
+ from brutor.runtime_hooks.errors import HookDenied, OutputDenied
70
+ from brutor.runtime_hooks.interceptor import BrutorInterceptor
71
+ from brutor.runtime_hooks.resolver import BrutorApprovalResolver
72
+ from brutor.runtime_hooks.session import HookOutcome, HookSession
73
+ from brutor.runtime_hooks.transform import REDACTION_REQUIRED, cannot_carry
74
+
75
+ COVERS = ("agent_startup", "input", "pre_tool_call", "post_tool_call", "output", "agent_shutdown")
76
+ NOT_COVERED = ("pre_model_call", "post_model_call")
77
+ FRAMEWORK = "claude_agent_sdk"
78
+ MCP_PREFIX = "mcp__"
79
+ HOOK_TIMEOUT_MARGIN_S = 30.0
80
+ ON_APPROVAL = ("block", "defer")
81
+ # What becomes of a transform at each point the adapter sends.
82
+ TRANSFORMS = {
83
+ "pre_tool_call": "applied",
84
+ "input": "fail_closed",
85
+ "post_tool_call": "applied (MCP) / fail_closed (built-in)",
86
+ "output": "applied",
87
+ }
88
+
89
+
90
+ def _without_answer_text(message: Any) -> Any:
91
+ """``message`` without what holds the turn's answer as it was before a redaction (None: drop it)."""
92
+ if isinstance(message, StreamEvent):
93
+ return None
94
+ if isinstance(message, AssistantMessage):
95
+ kept: list[Any] = [b for b in message.content if not isinstance(b, (TextBlock, ThinkingBlock))]
96
+ return dataclasses.replace(message, content=kept) if kept else None
97
+ return message
98
+
99
+
100
+ def deny_reason(verdict: dict[str, Any]) -> str:
101
+ """The text Claude is given for a deny: the gateway's sentence, else its reason."""
102
+ message = verdict.get("message")
103
+ if isinstance(message, str) and message:
104
+ return message
105
+ reason = str(verdict.get("reason") or "denied")
106
+ return reason if reason.startswith("host_error:") else f"Denied by Brutor: {reason}"
107
+
108
+
109
+ def _liftable(verdict: dict[str, Any]) -> bool:
110
+ return verdict.get("decision") == "deny" and isinstance(verdict.get("approval"), dict)
111
+
112
+
113
+ class BrutorClaudeSession:
114
+ """A ``ClaudeSDKClient`` whose tool calls, prompts and answers Brutor governs."""
115
+
116
+ def __init__(
117
+ self,
118
+ interceptor: BrutorInterceptor,
119
+ options: Any,
120
+ *,
121
+ agent_id: str,
122
+ on_approval: str = "block",
123
+ resolver: Any = None,
124
+ mcp_tools: Sequence[str] = (),
125
+ session_id: str | None = None,
126
+ agent_name: str | None = None,
127
+ agent_version: str | None = None,
128
+ delegation: Mapping[str, str] | None = None,
129
+ client_factory: Callable[..., Any] = ClaudeSDKClient,
130
+ ) -> None:
131
+ if on_approval not in ON_APPROVAL:
132
+ raise ValueError("on_approval must be 'block' or 'defer' ('ask' would let the local user approve)")
133
+ self.interceptor = interceptor
134
+ self.on_approval = on_approval
135
+ self.resolver = resolver if resolver is not None else BrutorApprovalResolver(interceptor)
136
+ tools: list[str] = []
137
+ for name in [*(getattr(options, "allowed_tools", None) or []), *mcp_tools]:
138
+ if name not in tools:
139
+ tools.append(name)
140
+ self.hooks = HookSession(
141
+ interceptor,
142
+ agent_id=agent_id,
143
+ framework=FRAMEWORK,
144
+ tools=tools,
145
+ resolver=self.resolver if on_approval == "block" else None,
146
+ session_id=session_id,
147
+ agent_name=agent_name,
148
+ agent_version=agent_version,
149
+ delegation=delegation,
150
+ )
151
+ self.options = self._governed(options)
152
+ self._client_factory = client_factory
153
+ self._client: Any = None
154
+ self._prompt_denied: dict[str, Any] | None = None
155
+
156
+ # ------------------------------------------------------------------ the options
157
+
158
+ def _governed(self, options: Any) -> Any:
159
+ tool_timeout = (
160
+ float(getattr(self.resolver, "max_wait", 0.0)) + HOOK_TIMEOUT_MARGIN_S
161
+ if self.on_approval == "block"
162
+ else self.interceptor.timeout + HOOK_TIMEOUT_MARGIN_S
163
+ )
164
+ other_timeout = self.interceptor.timeout + HOOK_TIMEOUT_MARGIN_S
165
+ ours = {
166
+ "UserPromptSubmit": HookMatcher(
167
+ matcher=None, hooks=[cast(Any, self._on_prompt)], timeout=other_timeout, on_failure="block"
168
+ ),
169
+ "PreToolUse": HookMatcher(
170
+ matcher=None, hooks=[cast(Any, self._on_pre_tool)], timeout=tool_timeout, on_failure="block"
171
+ ),
172
+ "PostToolUse": HookMatcher(
173
+ matcher=None, hooks=[cast(Any, self._on_post_tool)], timeout=other_timeout, on_failure="block"
174
+ ),
175
+ "PostToolUseFailure": HookMatcher(
176
+ matcher=None, hooks=[cast(Any, self._on_post_tool_failure)], timeout=other_timeout, on_failure="block"
177
+ ),
178
+ }
179
+ hooks: dict[str, list[Any]] = {k: list(v) for k, v in (getattr(options, "hooks", None) or {}).items()}
180
+ for event, matcher in ours.items():
181
+ hooks.setdefault(event, []).append(matcher)
182
+ return dataclasses.replace(options, hooks=hooks)
183
+
184
+ # ------------------------------------------------------------------ the session
185
+
186
+ async def __aenter__(self) -> BrutorClaudeSession:
187
+ await self.hooks.__aenter__() # raises HookDenied on a deny: no client is opened
188
+ try:
189
+ client = self._client_factory(options=self.options)
190
+ await client.__aenter__()
191
+ except BaseException as e:
192
+ await self.hooks.__aexit__(type(e), e, e.__traceback__)
193
+ raise
194
+ self._client = client
195
+ return self
196
+
197
+ async def __aexit__(
198
+ self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
199
+ ) -> None:
200
+ try:
201
+ if self._client is not None:
202
+ await self._client.__aexit__(exc_type, exc, tb)
203
+ finally:
204
+ self._client = None
205
+ await self.hooks.__aexit__(exc_type, exc, tb)
206
+
207
+ @property
208
+ def client(self) -> Any:
209
+ if self._client is None:
210
+ raise RuntimeError("use the session inside `async with BrutorClaudeSession(...)`")
211
+ return self._client
212
+
213
+ async def query(self, *args: Any, **kwargs: Any) -> Any:
214
+ return await self.client.query(*args, **kwargs)
215
+
216
+ async def interrupt(self) -> Any:
217
+ return await self.client.interrupt()
218
+
219
+ def receive_response(self) -> AsyncIterator[Any]:
220
+ """The turn's messages, released once its final answer has passed ``output``."""
221
+ return self._guarded(self.client.receive_response())
222
+
223
+ def receive_messages(self) -> AsyncIterator[Any]:
224
+ """Every message, each turn released once its final answer has passed ``output``."""
225
+ return self._guarded(self.client.receive_messages())
226
+
227
+ def _refused_prompt(self) -> None:
228
+ verdict, self._prompt_denied = self._prompt_denied, None
229
+ if verdict is not None:
230
+ raise HookDenied(verdict)
231
+
232
+ async def _guarded(self, stream: AsyncIterator[Any]) -> AsyncIterator[Any]:
233
+ held: list[Any] = []
234
+ async for message in stream:
235
+ if self._prompt_denied is not None:
236
+ held.clear()
237
+ self._refused_prompt()
238
+ held.append(message)
239
+ if isinstance(message, ResultMessage):
240
+ text = getattr(message, "result", None)
241
+ outcome = await self.hooks.output(text if text is not None else "")
242
+ released = self._released(held, message, outcome)
243
+ held.clear()
244
+ for m in released:
245
+ yield m
246
+ # a stream that ends without a final answer releases nothing it holds
247
+ self._refused_prompt()
248
+
249
+ @staticmethod
250
+ def _released(held: list[Any], result: Any, outcome: HookOutcome) -> list[Any]:
251
+ """The turn's messages as the caller may have them, or OutputDenied."""
252
+ if not outcome.proceeds:
253
+ raise OutputDenied(outcome.verdict)
254
+ if not outcome.transformed:
255
+ return list(held)
256
+ content = outcome.target.get("content")
257
+ if not isinstance(content, str):
258
+ raise OutputDenied(cannot_carry()) # a ResultMessage's result is text
259
+ out = [m for m in (_without_answer_text(m) for m in held[:-1]) if m is not None]
260
+ return [*out, dataclasses.replace(result, result=content)]
261
+
262
+ # ------------------------------------------------------------------ the callbacks
263
+
264
+ async def _on_prompt(self, input_data: dict[str, Any], _tool_use_id: str | None, _context: Any) -> dict[str, Any]:
265
+ outcome = await self.hooks.input(input_data.get("prompt", ""), role="user")
266
+ if outcome.proceeds and not outcome.transformed:
267
+ return {}
268
+ if outcome.transformed:
269
+ # The hook cannot rewrite the prompt: a redaction it cannot carry blocks it.
270
+ self._prompt_denied = cannot_carry()
271
+ return {"decision": "block", "reason": REDACTION_REQUIRED}
272
+ self._prompt_denied = outcome.verdict # the turn's stream raises HookDenied
273
+ return {"decision": "block", "reason": deny_reason(outcome.verdict)}
274
+
275
+ async def _on_pre_tool(self, input_data: dict[str, Any], tool_use_id: str | None, _context: Any) -> dict[str, Any]:
276
+ call_id = input_data.get("tool_use_id") or tool_use_id or ""
277
+ outcome = await self.hooks.pre_tool_call(
278
+ call_id, input_data.get("tool_name", ""), input_data.get("tool_input") or {}
279
+ )
280
+ if outcome.transformed:
281
+ # updatedInput replaces the whole input, so it carries every argument (a new object).
282
+ # No permissionDecision: Claude's own permission rules judge the transformed input, so
283
+ # Brutor can only be stricter. Never "allow" (it would skip them), never "defer".
284
+ return {
285
+ "hookSpecificOutput": {
286
+ "hookEventName": "PreToolUse",
287
+ "updatedInput": dict(outcome.target),
288
+ }
289
+ }
290
+ if outcome.proceeds:
291
+ # No decision: Claude's own permission rules still apply, so Brutor can only be stricter.
292
+ # A hook's "allow" would skip them.
293
+ return {}
294
+ verdict = outcome.verdict
295
+ out: dict[str, Any] = {"hookEventName": "PreToolUse"}
296
+ if self.on_approval == "defer" and _liftable(verdict):
297
+ out["permissionDecision"] = "defer"
298
+ out["permissionDecisionReason"] = deny_reason(verdict)
299
+ else:
300
+ out["permissionDecision"] = "deny"
301
+ out["permissionDecisionReason"] = deny_reason(verdict)
302
+ return {"hookSpecificOutput": out}
303
+
304
+ async def _on_post_tool(self, input_data: dict[str, Any], tool_use_id: str | None, _context: Any) -> dict[str, Any]:
305
+ name = input_data.get("tool_name", "")
306
+ outcome = await self.hooks.post_tool_call(
307
+ input_data.get("tool_use_id") or tool_use_id or "",
308
+ name,
309
+ input_data.get("tool_input") or {},
310
+ input_data.get("tool_response"),
311
+ is_error=False,
312
+ duration_ms=input_data.get("duration_ms"),
313
+ )
314
+ return self._post_answer(outcome, name, "PostToolUse")
315
+
316
+ async def _on_post_tool_failure(
317
+ self, input_data: dict[str, Any], tool_use_id: str | None, _context: Any
318
+ ) -> dict[str, Any]:
319
+ name = input_data.get("tool_name", "")
320
+ outcome = await self.hooks.post_tool_call(
321
+ input_data.get("tool_use_id") or tool_use_id or "",
322
+ name,
323
+ input_data.get("tool_input") or {},
324
+ input_data.get("error", ""),
325
+ is_error=True,
326
+ duration_ms=input_data.get("duration_ms"),
327
+ )
328
+ return self._post_answer(outcome, name, "PostToolUseFailure")
329
+
330
+ @staticmethod
331
+ def _post_answer(outcome: HookOutcome, name: str, event: str) -> dict[str, Any]:
332
+ mcp = event == "PostToolUse" and name.startswith(MCP_PREFIX)
333
+ if outcome.transformed:
334
+ if mcp:
335
+ return {"hookSpecificOutput": {"hookEventName": "PostToolUse", "updatedMCPToolOutput": outcome.target}}
336
+ # A built-in tool's result (or a failure's error) cannot be replaced safely: blocked.
337
+ return {"decision": "block", "reason": REDACTION_REQUIRED}
338
+ if outcome.proceeds:
339
+ return {}
340
+ reason = deny_reason(outcome.verdict)
341
+ out: dict[str, Any] = {"decision": "block", "reason": reason}
342
+ if mcp:
343
+ # An MCP tool's result can be replaced before the model reads it; a built-in tool's
344
+ # only in its own output shape, so for those Claude is told and the result stands.
345
+ out["hookSpecificOutput"] = {
346
+ "hookEventName": "PostToolUse",
347
+ "updatedMCPToolOutput": [{"type": "text", "text": f"Brutor withheld this tool result: {reason}"}],
348
+ }
349
+ return out
350
+
351
+ def __repr__(self) -> str:
352
+ return f"BrutorClaudeSession(on_approval={self.on_approval!r})"