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.
- brutor/runtime_hooks/__init__.py +46 -0
- brutor/runtime_hooks/_delegation.py +92 -0
- brutor/runtime_hooks/_env.py +39 -0
- brutor/runtime_hooks/_http.py +174 -0
- brutor/runtime_hooks/_jcs.py +123 -0
- brutor/runtime_hooks/_verdict.py +148 -0
- brutor/runtime_hooks/adapters/__init__.py +16 -0
- brutor/runtime_hooks/adapters/agent_framework.py +118 -0
- brutor/runtime_hooks/adapters/claude_agent_sdk.py +352 -0
- brutor/runtime_hooks/adapters/langgraph.py +623 -0
- brutor/runtime_hooks/adapters/openai_agents.py +450 -0
- brutor/runtime_hooks/bundle.py +294 -0
- brutor/runtime_hooks/errors.py +92 -0
- brutor/runtime_hooks/interceptor.py +495 -0
- brutor/runtime_hooks/minimise.py +105 -0
- brutor/runtime_hooks/py.typed +0 -0
- brutor/runtime_hooks/resolver.py +175 -0
- brutor/runtime_hooks/session.py +566 -0
- brutor/runtime_hooks/transform.py +184 -0
- brutor_runtime_hooks-0.2.0.dist-info/METADATA +172 -0
- brutor_runtime_hooks-0.2.0.dist-info/RECORD +24 -0
- brutor_runtime_hooks-0.2.0.dist-info/WHEEL +4 -0
- brutor_runtime_hooks-0.2.0.dist-info/licenses/LICENSE +52 -0
- brutor_runtime_hooks-0.2.0.dist-info/licenses/NOTICE +23 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""BrutorApprovalResolver: the Agent Hooks approval seam, answered by Brutor's approval queue.
|
|
5
|
+
|
|
6
|
+
A Decision API deny with reason ``approval_required`` carries ``approval = {id, poll,
|
|
7
|
+
expires_at}``: the hold is in the same queue as the gateway's (the Approvals screen). The
|
|
8
|
+
resolver polls ``GET /v1/approvals/<id>/poll`` with the agent's own credential until a person
|
|
9
|
+
decides. On an approval it sends the held context again, byte for byte, with the one-time
|
|
10
|
+
``X-Approval-Token``; the gateway's new verdict is the resolution. A rejection is a ``reject`` with
|
|
11
|
+
a deny. Anything else (expired, the token already redeemed, an error, ``max_wait`` passed) is
|
|
12
|
+
``unresolved``, which a host turns into a deny. The poll location must be the gateway's own poll
|
|
13
|
+
route for that approval id: no other URL is ever called with the agent's credential.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import asyncio
|
|
19
|
+
import logging
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Callable, Mapping
|
|
24
|
+
from datetime import datetime
|
|
25
|
+
from typing import Any, Final, Literal
|
|
26
|
+
|
|
27
|
+
from brutor.runtime_hooks import errors
|
|
28
|
+
from brutor.runtime_hooks._verdict import permits
|
|
29
|
+
from brutor.runtime_hooks.interceptor import BrutorInterceptor
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger("brutor.runtime_hooks")
|
|
32
|
+
_APPROVAL_ID = re.compile(r"^[A-Za-z0-9_-]{1,128}$")
|
|
33
|
+
_POLL_CALL_TIMEOUT = 10.0
|
|
34
|
+
PENDING: Final = "pending"
|
|
35
|
+
Decided = tuple[str, str | None] # (decision, approval token)
|
|
36
|
+
REJECTED = {"decision": "deny", "reason": "approval_rejected", "message": "The approval was rejected"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _wire(value: Any) -> Any:
|
|
40
|
+
to_wire = getattr(value, "to_wire", None)
|
|
41
|
+
return to_wire() if callable(to_wire) else value
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _field(request: Any, name: str) -> Any:
|
|
45
|
+
if isinstance(request, Mapping):
|
|
46
|
+
return request.get(name)
|
|
47
|
+
return getattr(request, name, None)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class BrutorApprovalResolver:
|
|
51
|
+
"""Resolves Brutor holds for an Agent Hooks host (``resolve(request) -> resolution``).
|
|
52
|
+
|
|
53
|
+
``request`` is an Agent Hooks ``ApprovalRequest`` or a mapping with the same members
|
|
54
|
+
(``context_identity``, ``interception_point``, ``verdict``, ``context``); the resolution is
|
|
55
|
+
``{"outcome": "approve" | "reject" | "unresolved", "context_identity": <echoed>, "verdict"?}``.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
interceptor: BrutorInterceptor,
|
|
61
|
+
poll_interval: float = 2.0,
|
|
62
|
+
max_wait: float = 300.0,
|
|
63
|
+
clock: Callable[[], float] | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
for name, value in (("poll_interval", poll_interval), ("max_wait", max_wait)):
|
|
66
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
|
|
67
|
+
raise ValueError(f"{name} must be a positive number of seconds")
|
|
68
|
+
self.interceptor = interceptor
|
|
69
|
+
self.poll_interval = float(poll_interval)
|
|
70
|
+
self.max_wait = float(max_wait)
|
|
71
|
+
self._clock: Callable[[], float] = clock or time.time # epoch seconds; a test seam, the real clock by default
|
|
72
|
+
|
|
73
|
+
async def resolve(self, request: Any, /) -> dict[str, Any]:
|
|
74
|
+
"""Wait (up to ``max_wait``, never past the hold's expiry) for a person to decide."""
|
|
75
|
+
resolution = await self._settle(request, wait=True)
|
|
76
|
+
# Waiting always ends in a resolution; None is only ever a one-look answer.
|
|
77
|
+
return resolution or {"outcome": "unresolved", "context_identity": _field(request, "context_identity")}
|
|
78
|
+
|
|
79
|
+
async def check(self, request: Any, /) -> dict[str, Any] | None:
|
|
80
|
+
"""One look at the hold: the resolution once a person decided, None while it is still pending.
|
|
81
|
+
|
|
82
|
+
A host that cannot wait in place (a graph that interrupts, to be resumed later) calls this
|
|
83
|
+
when it is resumed; a hold that expired or is gone is ``unresolved``.
|
|
84
|
+
"""
|
|
85
|
+
return await self._settle(request, wait=False)
|
|
86
|
+
|
|
87
|
+
async def _settle(self, request: Any, *, wait: bool) -> dict[str, Any] | None:
|
|
88
|
+
identity = _field(request, "context_identity")
|
|
89
|
+
verdict = _wire(_field(request, "verdict"))
|
|
90
|
+
context = _field(request, "context")
|
|
91
|
+
unresolved: dict[str, Any] = {"outcome": "unresolved", "context_identity": identity}
|
|
92
|
+
approval = verdict.get("approval") if isinstance(verdict, Mapping) else None
|
|
93
|
+
path = _poll_path(approval)
|
|
94
|
+
if path is None or not isinstance(approval, Mapping) or not isinstance(context, Mapping):
|
|
95
|
+
logger.debug("a hold without the gateway's poll route: unresolved")
|
|
96
|
+
return unresolved
|
|
97
|
+
decided: Decided | None
|
|
98
|
+
if wait:
|
|
99
|
+
decided = await self._wait(path, time.monotonic() + min(self.max_wait, _until(approval, self._clock())))
|
|
100
|
+
else:
|
|
101
|
+
look = await self._look(path, time.monotonic() + _POLL_CALL_TIMEOUT)
|
|
102
|
+
if look == PENDING:
|
|
103
|
+
return None
|
|
104
|
+
decided = look
|
|
105
|
+
if decided is None:
|
|
106
|
+
return unresolved
|
|
107
|
+
decision, approval_token = decided
|
|
108
|
+
if decision == "rejected":
|
|
109
|
+
return {"outcome": "reject", "context_identity": identity, "verdict": dict(REJECTED)}
|
|
110
|
+
if decision != "approved" or not approval_token:
|
|
111
|
+
return unresolved
|
|
112
|
+
try:
|
|
113
|
+
lifted = await self.interceptor._lift(context, approval_token)
|
|
114
|
+
except errors.DecisionUnavailable as e:
|
|
115
|
+
logger.debug("the approved context could not be evaluated again: %s", e.code)
|
|
116
|
+
return unresolved
|
|
117
|
+
outcome = "approve" if permits(lifted) else "reject" # an allow, or a transform the host applies
|
|
118
|
+
return {"outcome": outcome, "context_identity": identity, "verdict": lifted}
|
|
119
|
+
|
|
120
|
+
async def _look(self, path: str, deadline: float) -> Decided | Literal["pending"] | None:
|
|
121
|
+
"""One poll: (decision, approval token) once decided, None when expired or gone, else "pending"."""
|
|
122
|
+
try:
|
|
123
|
+
status, body = await self.interceptor._poll(path, deadline)
|
|
124
|
+
except errors.DecisionUnavailable as e:
|
|
125
|
+
logger.debug("the approval poll failed: %s", e.code)
|
|
126
|
+
return PENDING
|
|
127
|
+
if status == 404:
|
|
128
|
+
return None
|
|
129
|
+
if status == 200 and isinstance(body, Mapping):
|
|
130
|
+
decision = body.get("decision")
|
|
131
|
+
if decision in ("approved", "rejected"):
|
|
132
|
+
token = body.get("approval_token")
|
|
133
|
+
return str(decision), token if isinstance(token, str) else None
|
|
134
|
+
if decision == "expired":
|
|
135
|
+
return None
|
|
136
|
+
return PENDING
|
|
137
|
+
|
|
138
|
+
async def _wait(self, path: str, deadline: float) -> tuple[str, str | None] | None:
|
|
139
|
+
"""(decision, approval token) once a person decided, or None (expired, gone, too long)."""
|
|
140
|
+
while True:
|
|
141
|
+
now = time.monotonic()
|
|
142
|
+
if now >= deadline:
|
|
143
|
+
return None
|
|
144
|
+
look = await self._look(path, min(deadline, now + _POLL_CALL_TIMEOUT))
|
|
145
|
+
if look != PENDING:
|
|
146
|
+
return look
|
|
147
|
+
await asyncio.sleep(max(0.0, min(self.poll_interval, deadline - time.monotonic())))
|
|
148
|
+
|
|
149
|
+
def __repr__(self) -> str:
|
|
150
|
+
return f"BrutorApprovalResolver(poll_interval={self.poll_interval!r}, max_wait={self.max_wait!r})"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _poll_path(approval: Any) -> str | None:
|
|
154
|
+
"""The gateway's poll route for the hold's approval id, or None when the block names anything else."""
|
|
155
|
+
if not isinstance(approval, Mapping):
|
|
156
|
+
return None
|
|
157
|
+
approval_id, poll = approval.get("id"), approval.get("poll")
|
|
158
|
+
if not isinstance(approval_id, str) or not _APPROVAL_ID.match(approval_id):
|
|
159
|
+
return None
|
|
160
|
+
path = f"/v1/approvals/{approval_id}/poll"
|
|
161
|
+
return path if poll == path else None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _until(approval: Mapping[str, Any], now: float | None = None) -> float:
|
|
165
|
+
"""Seconds until the hold expires (infinite when it names no valid time)."""
|
|
166
|
+
expires = approval.get("expires_at")
|
|
167
|
+
if not isinstance(expires, str):
|
|
168
|
+
return math.inf
|
|
169
|
+
try:
|
|
170
|
+
moment = datetime.fromisoformat(expires.replace("Z", "+00:00"))
|
|
171
|
+
except ValueError:
|
|
172
|
+
return math.inf
|
|
173
|
+
if moment.tzinfo is None:
|
|
174
|
+
return math.inf
|
|
175
|
+
return max(0.0, moment.timestamp() - (time.time() if now is None else now)) + 5.0
|