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,46 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""Runtime hooks for Brutor Agent Control: govern what an agent does inside its own process.
|
|
5
|
+
|
|
6
|
+
from brutor.runtime_hooks import BrutorInterceptor, BrutorApprovalResolver, HookSession
|
|
7
|
+
|
|
8
|
+
interceptor = BrutorInterceptor() # BRUTOR_GATEWAY_URL; a brutor.auth.WorkloadAuth credential
|
|
9
|
+
resolver = BrutorApprovalResolver(interceptor)
|
|
10
|
+
async with HookSession(interceptor, agent_id="loan-screening", framework="langgraph",
|
|
11
|
+
tools=["write_file"], resolver=resolver) as hooks:
|
|
12
|
+
outcome = await hooks.pre_tool_call(call_id, "write_file", args)
|
|
13
|
+
if outcome.proceeds:
|
|
14
|
+
result = write_file(**outcome.target) # the arguments as allowed, or as transformed
|
|
15
|
+
|
|
16
|
+
``BrutorInterceptor`` is an Agent Hooks 0.1 interceptor: any Agent Hooks host (Microsoft Agent
|
|
17
|
+
Framework, the adapters in ``brutor.runtime_hooks.adapters``) can call it. Every decision is the
|
|
18
|
+
gateway's (``POST /v1/runtime-hooks/evaluate``), with the same policies as the gateway's own
|
|
19
|
+
traffic. When the gateway gives no usable answer the interceptor raises ``DecisionUnavailable`` and
|
|
20
|
+
the host denies: it fails closed.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from brutor.runtime_hooks._delegation import delegation_from_headers
|
|
24
|
+
from brutor.runtime_hooks.bundle import ACS_MANIFEST_VERSION
|
|
25
|
+
from brutor.runtime_hooks.errors import DecisionUnavailable, HookDenied, OutputDenied, UncoveredTools
|
|
26
|
+
from brutor.runtime_hooks.interceptor import SPEC_VERSION, BrutorInterceptor
|
|
27
|
+
from brutor.runtime_hooks.resolver import BrutorApprovalResolver
|
|
28
|
+
from brutor.runtime_hooks.session import HookOutcome, HookSession, context_identity
|
|
29
|
+
|
|
30
|
+
__version__ = "0.2.0"
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"ACS_MANIFEST_VERSION",
|
|
34
|
+
"SPEC_VERSION",
|
|
35
|
+
"BrutorApprovalResolver",
|
|
36
|
+
"BrutorInterceptor",
|
|
37
|
+
"DecisionUnavailable",
|
|
38
|
+
"HookDenied",
|
|
39
|
+
"HookOutcome",
|
|
40
|
+
"HookSession",
|
|
41
|
+
"OutputDenied",
|
|
42
|
+
"UncoveredTools",
|
|
43
|
+
"__version__",
|
|
44
|
+
"context_identity",
|
|
45
|
+
"delegation_from_headers",
|
|
46
|
+
]
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""The delegation a delegate's host received, carried to ``agent_startup`` to join the caller's run.
|
|
5
|
+
|
|
6
|
+
When an agent is reached as a delegate (an A2A request from another agent through the gateway), the
|
|
7
|
+
inbound request carries the gateway-signed delegation chain in ``x-brutor-delegation-*`` headers. A
|
|
8
|
+
host that starts its session with that delegation joins the caller's run: the gateway verifies the
|
|
9
|
+
chain and answers ``agent_startup`` with a run handle for the caller's run. The session then sends
|
|
10
|
+
that handle on its own gateway calls and never the delegation headers: a call that presents the
|
|
11
|
+
chain itself is not a hooked call.
|
|
12
|
+
|
|
13
|
+
The rules are the gateway's: names lower-case and matching ``^x-brutor-delegation-[a-z-]{1,48}$``,
|
|
14
|
+
at most 8 members, each value a string of at most 4096 bytes (UTF-8).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from collections.abc import Iterable, Mapping
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
PREFIX = "x-brutor-delegation-"
|
|
24
|
+
RUN_HEADER = "X-Brutor-Run-Id"
|
|
25
|
+
MAX_MEMBERS = 8
|
|
26
|
+
MAX_VALUE_BYTES = 4096
|
|
27
|
+
_NAME = re.compile(r"^x-brutor-delegation-[a-z-]{1,48}$")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def check_delegation(delegation: Any) -> dict[str, str]:
|
|
31
|
+
"""The delegation as a plain dict of strings, or ValueError naming the rule it breaks."""
|
|
32
|
+
if not isinstance(delegation, Mapping):
|
|
33
|
+
raise ValueError("the delegation must be a mapping of x-brutor-delegation-* headers")
|
|
34
|
+
if len(delegation) > MAX_MEMBERS:
|
|
35
|
+
raise ValueError(f"the delegation has {len(delegation)} headers; at most {MAX_MEMBERS} are allowed")
|
|
36
|
+
out: dict[str, str] = {}
|
|
37
|
+
for name, value in delegation.items():
|
|
38
|
+
if not isinstance(name, str) or not _NAME.match(name):
|
|
39
|
+
raise ValueError("a delegation header name must be lower-case and match ^x-brutor-delegation-[a-z-]{1,48}$")
|
|
40
|
+
if not isinstance(value, str):
|
|
41
|
+
raise ValueError(f"the delegation header {name} must have a string value")
|
|
42
|
+
if len(value.encode("utf-8")) > MAX_VALUE_BYTES:
|
|
43
|
+
raise ValueError(f"the delegation header {name} is longer than {MAX_VALUE_BYTES} bytes")
|
|
44
|
+
out[name] = value
|
|
45
|
+
return out
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _pairs(headers: Any) -> Iterable[tuple[Any, Any]]:
|
|
49
|
+
"""Every (name, value) of a header collection, repeated names included."""
|
|
50
|
+
multi = getattr(headers, "multi_items", None)
|
|
51
|
+
if callable(multi): # httpx.Headers, Starlette Headers
|
|
52
|
+
return list(multi())
|
|
53
|
+
items = getattr(headers, "items", None)
|
|
54
|
+
if callable(items): # a dict, aiohttp's CIMultiDict (every value), Werkzeug headers
|
|
55
|
+
return list(items())
|
|
56
|
+
return list(headers) # a list of (name, value) pairs, as ASGI and WSGI servers give them
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _text(value: Any) -> Any:
|
|
60
|
+
return value.decode("latin-1") if isinstance(value, (bytes, bytearray)) else value
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def delegation_from_headers(headers: Any) -> dict[str, str]:
|
|
64
|
+
"""Exactly the ``x-brutor-delegation-*`` entries of an inbound request's headers, names lower-case.
|
|
65
|
+
|
|
66
|
+
``headers`` is a mapping, a framework's header collection (Starlette, httpx, aiohttp,
|
|
67
|
+
Werkzeug) or a list of ``(name, value)`` pairs (``str`` or ``bytes``). Every other header is
|
|
68
|
+
left out. An empty result means the request was not delegated. A name sent twice with
|
|
69
|
+
different values, or a delegation the gateway would refuse, raises ValueError.
|
|
70
|
+
"""
|
|
71
|
+
out: dict[str, str] = {}
|
|
72
|
+
for raw_name, raw_value in _pairs(headers):
|
|
73
|
+
name = _text(raw_name)
|
|
74
|
+
if not isinstance(name, str) or not name.lower().startswith(PREFIX):
|
|
75
|
+
continue
|
|
76
|
+
name = name.lower()
|
|
77
|
+
value = _text(raw_value)
|
|
78
|
+
if name in out and out[name] != value:
|
|
79
|
+
raise ValueError(f"the delegation header {name} appears twice with different values")
|
|
80
|
+
out[name] = value
|
|
81
|
+
return check_delegation(out)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def without_delegation(headers: Mapping[str, str] | None) -> dict[str, str]:
|
|
85
|
+
"""A copy of outbound headers without any delegation header or run handle (any case)."""
|
|
86
|
+
out: dict[str, str] = {}
|
|
87
|
+
for name, value in (headers or {}).items():
|
|
88
|
+
low = name.lower()
|
|
89
|
+
if low.startswith(PREFIX) or low == RUN_HEADER.lower():
|
|
90
|
+
continue
|
|
91
|
+
out[name] = value
|
|
92
|
+
return out
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""Every environment variable the SDK reads, in one place: the SDK's registry.
|
|
5
|
+
|
|
6
|
+
Every read goes through ``read``. ``env_registry.json`` beside the package's
|
|
7
|
+
``pyproject.toml`` is generated from ``VARIABLES`` (``scripts/env_registry.py``)
|
|
8
|
+
so the documentation can list them without importing the SDK; a test holds the
|
|
9
|
+
two equal. ``brutor-agent-auth`` reads its own variables through its own
|
|
10
|
+
registry. An empty value counts as unset.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
|
|
18
|
+
VARIABLES: dict[str, str] = {
|
|
19
|
+
"BRUTOR_GATEWAY_URL": "the gateway's base URL: the Decision API and the approvals poll route",
|
|
20
|
+
"BRUTOR_TENANT_ID": "sent as X-Tenant-ID",
|
|
21
|
+
"BRUTOR_RESOURCE_GROUP": "sent as X-Resource-Group",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def read(name: str) -> str | None:
|
|
26
|
+
"""The variable's value, or None when it is unset or empty."""
|
|
27
|
+
if name not in VARIABLES:
|
|
28
|
+
raise KeyError(f"{name} is not a variable of this SDK")
|
|
29
|
+
value = os.environ.get(name)
|
|
30
|
+
return value or None
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def registry_json() -> str:
|
|
34
|
+
"""The registry as the JSON document ``env_registry.json`` holds."""
|
|
35
|
+
doc = {
|
|
36
|
+
"package": "brutor-runtime-hooks",
|
|
37
|
+
"variables": [{"name": name, "description": text} for name, text in VARIABLES.items()],
|
|
38
|
+
}
|
|
39
|
+
return json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""The SDK's HTTP calls to the gateway: one async client, credentials on every request, fail closed.
|
|
5
|
+
|
|
6
|
+
Every call has a deadline (the interceptor's timeout). A ``401`` invalidates the credential once and
|
|
7
|
+
sends the identical request again; a ``409 HOOKS_IN_FLIGHT`` is sent again after its ``Retry-After``
|
|
8
|
+
when that still fits before the deadline. Anything else that carries no usable answer raises
|
|
9
|
+
``DecisionUnavailable``. Nothing here logs a header, a body or a credential.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import json
|
|
16
|
+
import logging
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Mapping
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any
|
|
21
|
+
from urllib.parse import urlsplit
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from brutor.runtime_hooks import errors
|
|
26
|
+
|
|
27
|
+
logger = logging.getLogger("brutor.runtime_hooks")
|
|
28
|
+
_IN_FLIGHT = "HOOKS_IN_FLIGHT"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class Response:
|
|
33
|
+
status: int
|
|
34
|
+
headers: httpx.Headers
|
|
35
|
+
body: Any # the parsed JSON body, or None when it is absent or not JSON
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def check_gateway_url(url: str) -> str:
|
|
39
|
+
"""The gateway's base URL without a trailing slash: http(s), a host, no credentials, query or fragment."""
|
|
40
|
+
parts = urlsplit(url)
|
|
41
|
+
if parts.scheme not in ("http", "https") or not parts.hostname:
|
|
42
|
+
raise ValueError("the gateway URL must be an http:// or https:// URL with a host")
|
|
43
|
+
if parts.username or parts.password or parts.query or parts.fragment:
|
|
44
|
+
raise ValueError("the gateway URL must not carry credentials, a query or a fragment")
|
|
45
|
+
return url.rstrip("/")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Transport:
|
|
49
|
+
"""One gateway, one credential, one async client."""
|
|
50
|
+
|
|
51
|
+
def __init__(self, gateway_url: str, auth: Any, *, tenant_id: str | None, resource_group: str | None) -> None:
|
|
52
|
+
self.gateway_url = gateway_url
|
|
53
|
+
self._auth = auth
|
|
54
|
+
self._tenant_id = tenant_id
|
|
55
|
+
self._resource_group = resource_group
|
|
56
|
+
self._workload = hasattr(auth, "httpx_auth") and hasattr(auth, "ssl_context")
|
|
57
|
+
self._client: httpx.AsyncClient | None = None
|
|
58
|
+
self.closed = False
|
|
59
|
+
|
|
60
|
+
def _get_client(self) -> httpx.AsyncClient:
|
|
61
|
+
if self.closed:
|
|
62
|
+
raise errors.DecisionUnavailable(errors.CLOSED)
|
|
63
|
+
if self._client is None:
|
|
64
|
+
kwargs: dict[str, Any] = {"follow_redirects": False, "trust_env": False}
|
|
65
|
+
if self._workload:
|
|
66
|
+
kwargs["auth"] = self._auth.httpx_auth()
|
|
67
|
+
if getattr(self._auth, "mtls", False):
|
|
68
|
+
kwargs["verify"] = self._auth.ssl_context()
|
|
69
|
+
self._client = httpx.AsyncClient(**kwargs)
|
|
70
|
+
return self._client
|
|
71
|
+
|
|
72
|
+
async def _credential_headers(self, method: str, url: str) -> dict[str, str]:
|
|
73
|
+
"""The credential's headers, fetched off the event loop (a token refresh may block)."""
|
|
74
|
+
try:
|
|
75
|
+
if self._workload:
|
|
76
|
+
# Warm the cached token in a thread; the client's auth then signs without blocking.
|
|
77
|
+
await asyncio.to_thread(self._auth.headers, method, url)
|
|
78
|
+
return {}
|
|
79
|
+
headers = await asyncio.to_thread(self._auth.headers)
|
|
80
|
+
except errors.DecisionUnavailable:
|
|
81
|
+
raise
|
|
82
|
+
except Exception as e:
|
|
83
|
+
raise errors.DecisionUnavailable(errors.CREDENTIAL, detail=type(e).__name__) from None
|
|
84
|
+
if not isinstance(headers, Mapping):
|
|
85
|
+
raise errors.DecisionUnavailable(errors.CREDENTIAL, detail="headers() did not return a mapping")
|
|
86
|
+
return {str(k): str(v) for k, v in headers.items()}
|
|
87
|
+
|
|
88
|
+
async def _invalidate(self) -> None:
|
|
89
|
+
invalidate = getattr(self._auth, "invalidate", None)
|
|
90
|
+
if callable(invalidate):
|
|
91
|
+
await asyncio.to_thread(invalidate)
|
|
92
|
+
|
|
93
|
+
async def request(
|
|
94
|
+
self,
|
|
95
|
+
method: str,
|
|
96
|
+
path: str,
|
|
97
|
+
*,
|
|
98
|
+
deadline: float,
|
|
99
|
+
body: bytes | None = None,
|
|
100
|
+
extra_headers: Mapping[str, str] | None = None,
|
|
101
|
+
) -> Response:
|
|
102
|
+
"""One call to the gateway, retried as the module says, before ``deadline`` (monotonic)."""
|
|
103
|
+
url = self.gateway_url + path
|
|
104
|
+
reauthenticated = False
|
|
105
|
+
while True:
|
|
106
|
+
headers = {"Accept": "application/json"}
|
|
107
|
+
if body is not None:
|
|
108
|
+
headers["Content-Type"] = "application/json"
|
|
109
|
+
if self._tenant_id:
|
|
110
|
+
headers["X-Tenant-ID"] = self._tenant_id
|
|
111
|
+
if self._resource_group:
|
|
112
|
+
headers["X-Resource-Group"] = self._resource_group
|
|
113
|
+
headers.update(await self._credential_headers(method, url))
|
|
114
|
+
headers.update(extra_headers or {})
|
|
115
|
+
remaining = deadline - time.monotonic()
|
|
116
|
+
if remaining <= 0:
|
|
117
|
+
raise errors.DecisionUnavailable(errors.TIMEOUT)
|
|
118
|
+
try:
|
|
119
|
+
raw = await asyncio.wait_for(
|
|
120
|
+
self._get_client().request(method, url, content=body, headers=headers, timeout=remaining),
|
|
121
|
+
timeout=remaining,
|
|
122
|
+
)
|
|
123
|
+
except (TimeoutError, httpx.TimeoutException):
|
|
124
|
+
raise errors.DecisionUnavailable(errors.TIMEOUT) from None
|
|
125
|
+
except httpx.HTTPError as e:
|
|
126
|
+
raise errors.DecisionUnavailable(errors.CONNECTION, detail=type(e).__name__) from None
|
|
127
|
+
except errors.DecisionUnavailable:
|
|
128
|
+
raise
|
|
129
|
+
except Exception as e: # a credential adapter refusing to sign, for one
|
|
130
|
+
raise errors.DecisionUnavailable(errors.CREDENTIAL, detail=type(e).__name__) from None
|
|
131
|
+
response = Response(raw.status_code, raw.headers, _json(raw))
|
|
132
|
+
logger.debug("%s %s: HTTP %s", method, path.split("?", 1)[0], raw.status_code)
|
|
133
|
+
if raw.status_code == 401 and not reauthenticated:
|
|
134
|
+
reauthenticated = True
|
|
135
|
+
await self._invalidate()
|
|
136
|
+
continue
|
|
137
|
+
if raw.status_code == 401:
|
|
138
|
+
raise errors.DecisionUnavailable(errors.UNAUTHENTICATED, status=401)
|
|
139
|
+
if raw.status_code == 409 and code_of(response) == _IN_FLIGHT:
|
|
140
|
+
wait = _retry_after(raw.headers)
|
|
141
|
+
if time.monotonic() + wait < deadline:
|
|
142
|
+
await asyncio.sleep(wait)
|
|
143
|
+
continue
|
|
144
|
+
return response
|
|
145
|
+
|
|
146
|
+
async def aclose(self) -> None:
|
|
147
|
+
self.closed = True
|
|
148
|
+
if self._client is not None:
|
|
149
|
+
await self._client.aclose()
|
|
150
|
+
self._client = None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _json(raw: httpx.Response) -> Any:
|
|
154
|
+
if not raw.content:
|
|
155
|
+
return None
|
|
156
|
+
try:
|
|
157
|
+
return json.loads(raw.content)
|
|
158
|
+
except (ValueError, UnicodeDecodeError):
|
|
159
|
+
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def code_of(response: Response) -> str | None:
|
|
163
|
+
"""The gateway's coded-refusal code (``{"error": ..., "code": "<CODE>"}``), if the body has one."""
|
|
164
|
+
body = response.body
|
|
165
|
+
if isinstance(body, Mapping) and isinstance(body.get("code"), str):
|
|
166
|
+
return str(body["code"])
|
|
167
|
+
return None
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _retry_after(headers: httpx.Headers) -> float:
|
|
171
|
+
try:
|
|
172
|
+
return max(0.0, float(headers.get("Retry-After", "1")))
|
|
173
|
+
except ValueError:
|
|
174
|
+
return 1.0
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""Canonical JSON (RFC 8785, the JSON Canonicalization Scheme) and the hashes built on it.
|
|
5
|
+
|
|
6
|
+
The gateway hashes the same way: ``args_hash`` (a tool call's arguments) binds a tool's result to
|
|
7
|
+
the call that was allowed, and ``request_hash`` is the key of a decision's idempotency. Only
|
|
8
|
+
I-JSON is canonical: an integer outside +/-(2**53 - 1), a non-finite number or a non-string key is
|
|
9
|
+
refused, never rounded or converted.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import math
|
|
16
|
+
import re
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
MAX_SAFE_INTEGER = 2**53 - 1
|
|
20
|
+
_REPR = re.compile(r"(\d+)(?:\.(\d+))?(?:e([+-]\d+))?")
|
|
21
|
+
_ESCAPES = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _number(x: float | int) -> str:
|
|
25
|
+
"""ECMAScript Number::toString of a finite double (RFC 8785 section 3.2.2.3)."""
|
|
26
|
+
if isinstance(x, int):
|
|
27
|
+
if abs(x) > MAX_SAFE_INTEGER:
|
|
28
|
+
raise ValueError("an integer outside +/-(2**53 - 1) has no canonical form: send it as a string")
|
|
29
|
+
x = float(x)
|
|
30
|
+
if not math.isfinite(x):
|
|
31
|
+
raise ValueError("NaN and the infinities have no canonical form")
|
|
32
|
+
if x == 0:
|
|
33
|
+
return "0"
|
|
34
|
+
sign = "-" if x < 0 else ""
|
|
35
|
+
m = _REPR.fullmatch(repr(abs(x)))
|
|
36
|
+
if m is None: # pragma: no cover - repr of a finite float always matches
|
|
37
|
+
raise ValueError("unexpected float representation")
|
|
38
|
+
whole, frac, exp = m.group(1), m.group(2) or "", int(m.group(3) or 0)
|
|
39
|
+
digits_all = whole + frac
|
|
40
|
+
stripped = digits_all.lstrip("0")
|
|
41
|
+
n = len(whole) - (len(digits_all) - len(stripped)) + exp
|
|
42
|
+
digits = stripped.rstrip("0") or "0"
|
|
43
|
+
k = len(digits)
|
|
44
|
+
if k <= n <= 21:
|
|
45
|
+
text = digits + "0" * (n - k)
|
|
46
|
+
elif 0 < n <= 21:
|
|
47
|
+
text = digits[:n] + "." + digits[n:]
|
|
48
|
+
elif -6 < n <= 0:
|
|
49
|
+
text = "0." + "0" * (-n) + digits
|
|
50
|
+
else:
|
|
51
|
+
e = n - 1
|
|
52
|
+
text = digits[0] + ("." + digits[1:] if k > 1 else "") + "e" + ("+" if e >= 0 else "-") + str(abs(e))
|
|
53
|
+
return sign + text
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _string(s: str) -> str:
|
|
57
|
+
out = ['"']
|
|
58
|
+
for ch in s:
|
|
59
|
+
esc = _ESCAPES.get(ch)
|
|
60
|
+
if esc is not None:
|
|
61
|
+
out.append(esc)
|
|
62
|
+
elif ord(ch) < 0x20:
|
|
63
|
+
out.append(f"\\u{ord(ch):04x}")
|
|
64
|
+
elif 0xD800 <= ord(ch) <= 0xDFFF:
|
|
65
|
+
raise ValueError("a lone surrogate has no canonical form")
|
|
66
|
+
else:
|
|
67
|
+
out.append(ch)
|
|
68
|
+
out.append('"')
|
|
69
|
+
return "".join(out)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _write(v: Any, out: list[str]) -> None:
|
|
73
|
+
if v is None:
|
|
74
|
+
out.append("null")
|
|
75
|
+
elif v is True:
|
|
76
|
+
out.append("true")
|
|
77
|
+
elif v is False:
|
|
78
|
+
out.append("false")
|
|
79
|
+
elif isinstance(v, (int, float)):
|
|
80
|
+
out.append(_number(v))
|
|
81
|
+
elif isinstance(v, str):
|
|
82
|
+
out.append(_string(v))
|
|
83
|
+
elif isinstance(v, (list, tuple)):
|
|
84
|
+
out.append("[")
|
|
85
|
+
for i, item in enumerate(v):
|
|
86
|
+
if i:
|
|
87
|
+
out.append(",")
|
|
88
|
+
_write(item, out)
|
|
89
|
+
out.append("]")
|
|
90
|
+
elif isinstance(v, dict):
|
|
91
|
+
if not all(isinstance(k, str) for k in v):
|
|
92
|
+
raise TypeError("an object key must be a string")
|
|
93
|
+
out.append("{")
|
|
94
|
+
for i, key in enumerate(sorted(v, key=lambda k: k.encode("utf-16-be"))):
|
|
95
|
+
if i:
|
|
96
|
+
out.append(",")
|
|
97
|
+
out.append(_string(key))
|
|
98
|
+
out.append(":")
|
|
99
|
+
_write(v[key], out)
|
|
100
|
+
out.append("}")
|
|
101
|
+
else:
|
|
102
|
+
raise TypeError(f"not a JSON value: {type(v).__name__}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def canonical(value: Any) -> bytes:
|
|
106
|
+
"""The RFC 8785 canonical form of a JSON value, as UTF-8 bytes."""
|
|
107
|
+
out: list[str] = []
|
|
108
|
+
_write(value, out)
|
|
109
|
+
return "".join(out).encode("utf-8")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def sha256_hex(data: bytes) -> str:
|
|
113
|
+
return hashlib.sha256(data).hexdigest()
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def args_hash(args: Any) -> str:
|
|
117
|
+
"""sha256 hex of the canonical arguments of a tool call."""
|
|
118
|
+
return sha256_hex(canonical(args))
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def request_hash(context: Any) -> str:
|
|
122
|
+
"""sha256 hex of the canonical context as sent (its extensions included)."""
|
|
123
|
+
return sha256_hex(canonical(context))
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""The Decision API's answer, checked before anything acts on it.
|
|
5
|
+
|
|
6
|
+
An answer is the Agent Hooks transport envelope ``{verdict, extensions?}``. The verdict is checked
|
|
7
|
+
as the pinned ``verdict.schema.json`` checks it (a closed object: ``decision`` ``allow`` or
|
|
8
|
+
``deny``, no ``host_error:`` reason, ``approval`` only on a deny, a closed ``evidence``, string
|
|
9
|
+
labels); a test holds this check to the schema itself. A ``transform`` carries a closed
|
|
10
|
+
``{path, value?}`` body (required on a transform, refused on any other decision) whose path is
|
|
11
|
+
checked with the same grammar the host applies it with: a path outside it raises
|
|
12
|
+
``InvalidTransform`` with the reserved reason it becomes (``host_error:transform_invalid`` or
|
|
13
|
+
``host_error:transform_target_forbidden``), so the check and the application never disagree. The
|
|
14
|
+
envelope's ``extensions`` are bounded at 65,536 bytes of canonical JSON, the verdict's evidence at
|
|
15
|
+
10,240, and the Brutor block must be an object whose ``run`` is a string and ``receipt`` an object.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import re
|
|
21
|
+
from collections.abc import Mapping
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from brutor.runtime_hooks._jcs import canonical
|
|
25
|
+
from brutor.runtime_hooks.transform import TransformRefused, parse_path
|
|
26
|
+
|
|
27
|
+
EXTENSIONS_MAX = 65536
|
|
28
|
+
EVIDENCE_MAX = 10240
|
|
29
|
+
_VERDICT_MEMBERS = {"decision", "reason", "message", "warnings", "approval", "transform", "evidence", "result_labels"}
|
|
30
|
+
_NAMESPACE = re.compile(r"^[a-z][a-z0-9_]*$")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class InvalidResponse(ValueError):
|
|
34
|
+
"""The answer is not one the SDK may act on."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class InvalidTransform(InvalidResponse):
|
|
38
|
+
"""A transform whose path is outside the Agent Hooks grammar: ``reason`` is the deny it becomes."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, reason: str) -> None:
|
|
41
|
+
self.reason = reason
|
|
42
|
+
super().__init__(f"the transform's path is refused ({reason})")
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def code(self) -> str:
|
|
46
|
+
"""The reason without its ``host_error:`` prefix (``transform_invalid``, ``transform_target_forbidden``)."""
|
|
47
|
+
return self.reason.removeprefix("host_error:")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _opt_str(v: Any, what: str) -> None:
|
|
51
|
+
if v is not None and not isinstance(v, str):
|
|
52
|
+
raise InvalidResponse(f"{what} must be a string or null")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _reason(v: Any, what: str) -> None:
|
|
56
|
+
_opt_str(v, what)
|
|
57
|
+
if isinstance(v, str) and v.startswith("host_error:"):
|
|
58
|
+
raise InvalidResponse(f"{what} uses the reserved host_error: prefix")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def check_verdict(v: Any) -> dict[str, Any]:
|
|
62
|
+
"""The verdict as a plain dict, or InvalidResponse."""
|
|
63
|
+
if not isinstance(v, Mapping):
|
|
64
|
+
raise InvalidResponse("the verdict is not an object")
|
|
65
|
+
extra = set(v) - _VERDICT_MEMBERS
|
|
66
|
+
if extra:
|
|
67
|
+
raise InvalidResponse("the verdict has members Agent Hooks does not define")
|
|
68
|
+
decision = v.get("decision")
|
|
69
|
+
if decision not in ("allow", "deny", "transform"):
|
|
70
|
+
raise InvalidResponse("the verdict's decision is not allow, deny or transform")
|
|
71
|
+
if (decision == "transform") != ("transform" in v):
|
|
72
|
+
raise InvalidResponse("a transform body is required on a transform and refused on any other decision")
|
|
73
|
+
_reason(v.get("reason"), "the reason")
|
|
74
|
+
_opt_str(v.get("message"), "the message")
|
|
75
|
+
warnings = v.get("warnings")
|
|
76
|
+
if warnings is not None:
|
|
77
|
+
if not isinstance(warnings, list):
|
|
78
|
+
raise InvalidResponse("the warnings are not a list")
|
|
79
|
+
for w in warnings:
|
|
80
|
+
if not isinstance(w, Mapping) or set(w) - {"reason", "message"}:
|
|
81
|
+
raise InvalidResponse("a warning is not a closed object")
|
|
82
|
+
_reason(w.get("reason"), "a warning's reason")
|
|
83
|
+
_opt_str(w.get("message"), "a warning's message")
|
|
84
|
+
if "approval" in v:
|
|
85
|
+
if not isinstance(v["approval"], Mapping):
|
|
86
|
+
raise InvalidResponse("the approval block is not an object")
|
|
87
|
+
if decision != "deny":
|
|
88
|
+
raise InvalidResponse("an approval block is only allowed on a deny")
|
|
89
|
+
if "evidence" in v:
|
|
90
|
+
evidence = v["evidence"]
|
|
91
|
+
if not isinstance(evidence, Mapping) or set(evidence) - {"artefact", "verification_pointers"}:
|
|
92
|
+
raise InvalidResponse("the evidence is not a closed object")
|
|
93
|
+
_opt_str(evidence.get("artefact"), "the evidence artefact")
|
|
94
|
+
if "verification_pointers" in evidence:
|
|
95
|
+
pointers = evidence["verification_pointers"]
|
|
96
|
+
if not isinstance(pointers, Mapping) or not all(isinstance(p, str) for p in pointers.values()):
|
|
97
|
+
raise InvalidResponse("the verification pointers are not an object of strings")
|
|
98
|
+
if len(canonical(evidence)) > EVIDENCE_MAX:
|
|
99
|
+
raise InvalidResponse("the evidence is larger than 10,240 bytes")
|
|
100
|
+
labels = v.get("result_labels")
|
|
101
|
+
if labels is not None and (not isinstance(labels, list) or not all(isinstance(x, str) for x in labels)):
|
|
102
|
+
raise InvalidResponse("the result labels are not a list of strings")
|
|
103
|
+
if "transform" in v:
|
|
104
|
+
_transform(v["transform"]) # last: a verdict wrong elsewhere is verdict_invalid, whatever its path
|
|
105
|
+
return dict(v)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _transform(t: Any) -> None:
|
|
109
|
+
if not isinstance(t, Mapping) or set(t) - {"path", "value"} or not isinstance(t.get("path"), str):
|
|
110
|
+
raise InvalidResponse("the transform is not a closed {path, value} object with a string path")
|
|
111
|
+
try:
|
|
112
|
+
parse_path(t["path"])
|
|
113
|
+
except TransformRefused as e:
|
|
114
|
+
raise InvalidTransform(e.reason) from None
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def check_envelope(body: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
118
|
+
"""(verdict, the Brutor extension block or {}) of a Decision API answer, or InvalidResponse."""
|
|
119
|
+
if not isinstance(body, Mapping) or "verdict" not in body or set(body) - {"verdict", "extensions"}:
|
|
120
|
+
raise InvalidResponse("the answer is not a verdict envelope")
|
|
121
|
+
verdict = check_verdict(body["verdict"])
|
|
122
|
+
extensions = body.get("extensions", {})
|
|
123
|
+
if not isinstance(extensions, Mapping) or not all(isinstance(k, str) and _NAMESPACE.match(k) for k in extensions):
|
|
124
|
+
raise InvalidResponse("the envelope's extensions are not an object of namespaces")
|
|
125
|
+
try:
|
|
126
|
+
size = len(canonical(extensions))
|
|
127
|
+
except (TypeError, ValueError) as e:
|
|
128
|
+
raise InvalidResponse("the envelope's extensions are not I-JSON") from e
|
|
129
|
+
if size > EXTENSIONS_MAX:
|
|
130
|
+
raise InvalidResponse("the envelope's extensions are larger than 65,536 bytes")
|
|
131
|
+
brutor = extensions.get("brutor", {})
|
|
132
|
+
if not isinstance(brutor, Mapping):
|
|
133
|
+
raise InvalidResponse("the Brutor extension is not an object")
|
|
134
|
+
if "run" in brutor and not isinstance(brutor["run"], str):
|
|
135
|
+
raise InvalidResponse("the run handle is not a string")
|
|
136
|
+
if "receipt" in brutor and not isinstance(brutor["receipt"], Mapping):
|
|
137
|
+
raise InvalidResponse("the receipt is not an object")
|
|
138
|
+
return verdict, dict(brutor)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def permits(verdict: Mapping[str, Any]) -> bool:
|
|
142
|
+
"""Whether the verdict lets the action proceed: an allow, or a transform (once applied)."""
|
|
143
|
+
return verdict.get("decision") in ("allow", "transform")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def is_liftable(verdict: Mapping[str, Any]) -> bool:
|
|
147
|
+
"""A deny carrying an approval block: the approval seam may lift it."""
|
|
148
|
+
return verdict.get("decision") == "deny" and isinstance(verdict.get("approval"), Mapping)
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""Framework adapters. Each one needs its extra:
|
|
5
|
+
|
|
6
|
+
- ``brutor.runtime_hooks.adapters.agent_framework``: ``pip install 'brutor-runtime-hooks[agent-framework]'``
|
|
7
|
+
- ``brutor.runtime_hooks.adapters.claude_agent_sdk``: ``pip install 'brutor-runtime-hooks[claude-agent-sdk]'``
|
|
8
|
+
- ``brutor.runtime_hooks.adapters.openai_agents``: ``pip install 'brutor-runtime-hooks[openai-agents]'``
|
|
9
|
+
- ``brutor.runtime_hooks.adapters.langgraph``: ``pip install 'brutor-runtime-hooks[langgraph]'``
|
|
10
|
+
|
|
11
|
+
An adapter never decides: it maps the framework's events to Agent Hooks contexts, asks the
|
|
12
|
+
interceptor and maps the verdicts back. ``COVERS`` in each module lists the interception points
|
|
13
|
+
the framework lets it observe. An adapter refuses, when it wraps the agent, tools the framework
|
|
14
|
+
runs where the adapter cannot see them (``UncoveredTools``), unless they are named in
|
|
15
|
+
``allow_uncovered``.
|
|
16
|
+
"""
|