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,495 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""BrutorInterceptor: an Agent Hooks interceptor whose decisions come from the gateway's Decision API.
|
|
5
|
+
|
|
6
|
+
Each context is sent to ``POST /v1/runtime-hooks/evaluate`` with Brutor's extension
|
|
7
|
+
(``extensions.brutor``: the session's run handle, the gateway-routed claim on model points, the
|
|
8
|
+
members it minimised), and the gateway's verdict is returned for the host to enforce. The run
|
|
9
|
+
handle comes from the ``agent_startup`` answer, is refreshed from every answer and is dropped at
|
|
10
|
+
``agent_shutdown``. When the gateway gives no usable verdict the interceptor raises
|
|
11
|
+
``DecisionUnavailable``, which an Agent Hooks host turns into a deny: it fails closed.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import asyncio
|
|
17
|
+
import copy
|
|
18
|
+
import json
|
|
19
|
+
import logging
|
|
20
|
+
import math
|
|
21
|
+
import time
|
|
22
|
+
from collections import OrderedDict
|
|
23
|
+
from collections.abc import Callable, Mapping
|
|
24
|
+
from datetime import UTC, datetime
|
|
25
|
+
from typing import Any, NoReturn
|
|
26
|
+
|
|
27
|
+
from brutor.runtime_hooks import _env, errors
|
|
28
|
+
from brutor.runtime_hooks import bundle as _bundle
|
|
29
|
+
from brutor.runtime_hooks._delegation import check_delegation
|
|
30
|
+
from brutor.runtime_hooks._http import Transport, check_gateway_url, code_of
|
|
31
|
+
from brutor.runtime_hooks._jcs import canonical
|
|
32
|
+
from brutor.runtime_hooks._verdict import InvalidResponse, InvalidTransform, check_envelope, is_liftable
|
|
33
|
+
from brutor.runtime_hooks.minimise import minimise, needs_profile
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger("brutor.runtime_hooks")
|
|
36
|
+
|
|
37
|
+
SPEC_VERSION = "agent-hooks/0.1"
|
|
38
|
+
EVALUATE = "/v1/runtime-hooks/evaluate"
|
|
39
|
+
PROFILE = "/v1/runtime-hooks/profile"
|
|
40
|
+
POINTS = (
|
|
41
|
+
"agent_startup",
|
|
42
|
+
"input",
|
|
43
|
+
"pre_model_call",
|
|
44
|
+
"post_model_call",
|
|
45
|
+
"pre_tool_call",
|
|
46
|
+
"post_tool_call",
|
|
47
|
+
"output",
|
|
48
|
+
"agent_shutdown",
|
|
49
|
+
)
|
|
50
|
+
MODEL_POINTS = ("pre_model_call", "post_model_call")
|
|
51
|
+
_VERDICT_STATUSES = (200, 403, 429)
|
|
52
|
+
_PROFILE_MAX_AGE = 60.0
|
|
53
|
+
_SESSIONS_KEPT = 4096 # the receipts and held bodies kept, by session, oldest dropped first
|
|
54
|
+
_HELD_KEPT = 1024
|
|
55
|
+
|
|
56
|
+
RecordSink = Callable[[Mapping[str, Any], Mapping[str, Any]], None]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class BrutorInterceptor:
|
|
60
|
+
"""An Agent Hooks interceptor backed by Brutor's Decision API.
|
|
61
|
+
|
|
62
|
+
``gateway_url`` (``BRUTOR_GATEWAY_URL``) is the gateway's base URL. ``auth`` is a
|
|
63
|
+
``brutor.auth.WorkloadAuth`` or anything with a ``headers()`` method (and, optionally,
|
|
64
|
+
``invalidate()``); None makes a ``WorkloadAuth()`` from the environment. ``tenant_id``
|
|
65
|
+
(``BRUTOR_TENANT_ID``) and ``resource_group`` (``BRUTOR_RESOURCE_GROUP``) are sent as
|
|
66
|
+
``X-Tenant-ID`` and ``X-Resource-Group``. ``timeout`` bounds each decision, retries included.
|
|
67
|
+
``gateway_routed`` claims, on the model points, that the model call also goes through the
|
|
68
|
+
gateway (a bool, or a function of the context); the gateway evaluates either way. ``minimise``
|
|
69
|
+
replaces content the gateway's checks do not read by its hash. ``record_sink(context,
|
|
70
|
+
envelope)`` is called after each decision, with the run handle and a delegate's delegation
|
|
71
|
+
removed from both.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
gateway_url: str | None = None,
|
|
77
|
+
auth: Any = None,
|
|
78
|
+
tenant_id: str | None = None,
|
|
79
|
+
resource_group: str | None = None,
|
|
80
|
+
timeout: float = 5.0,
|
|
81
|
+
gateway_routed: bool | Callable[[Mapping[str, Any]], bool] = False,
|
|
82
|
+
minimise: bool = True,
|
|
83
|
+
record_sink: RecordSink | None = None,
|
|
84
|
+
bundle: bool = False,
|
|
85
|
+
clock: Callable[[], datetime] | None = None,
|
|
86
|
+
) -> None:
|
|
87
|
+
url = gateway_url or _env.read("BRUTOR_GATEWAY_URL")
|
|
88
|
+
if not url:
|
|
89
|
+
raise ValueError("the gateway URL is required: pass gateway_url= or set BRUTOR_GATEWAY_URL")
|
|
90
|
+
self.gateway_url = check_gateway_url(url)
|
|
91
|
+
if (
|
|
92
|
+
isinstance(timeout, bool)
|
|
93
|
+
or not isinstance(timeout, (int, float))
|
|
94
|
+
or not math.isfinite(timeout)
|
|
95
|
+
or timeout <= 0
|
|
96
|
+
):
|
|
97
|
+
raise ValueError("timeout must be a positive number of seconds")
|
|
98
|
+
self.timeout = float(timeout)
|
|
99
|
+
self.tenant_id = tenant_id or _env.read("BRUTOR_TENANT_ID")
|
|
100
|
+
self.resource_group = resource_group or _env.read("BRUTOR_RESOURCE_GROUP")
|
|
101
|
+
if auth is None:
|
|
102
|
+
from brutor.auth import WorkloadAuth # noqa: PLC0415 (only when no credential is given)
|
|
103
|
+
|
|
104
|
+
auth = WorkloadAuth(
|
|
105
|
+
gateway_url=self.gateway_url, tenant_id=self.tenant_id, resource_group=self.resource_group
|
|
106
|
+
)
|
|
107
|
+
if not callable(getattr(auth, "headers", None)):
|
|
108
|
+
raise TypeError("auth must be a brutor.auth.WorkloadAuth or have a headers() method")
|
|
109
|
+
self._auth = auth
|
|
110
|
+
self.gateway_routed = gateway_routed
|
|
111
|
+
self.minimise = bool(minimise)
|
|
112
|
+
self.record_sink = record_sink
|
|
113
|
+
self.bundle = bool(bundle)
|
|
114
|
+
self._clock: Callable[[], datetime] = clock or (lambda: datetime.now(UTC)) # a test seam: the real clock
|
|
115
|
+
if self.bundle and not _bundle.runtime_available(): # pragma: no cover - the extra is installed in tests
|
|
116
|
+
raise ImportError("bundle=True needs the bundle extra: pip install 'brutor-runtime-hooks[bundle]'")
|
|
117
|
+
self._bundle_doc: tuple[float, str, dict[str, Any]] | None = None # (fresh until, etag, export)
|
|
118
|
+
self._bundle_lock = asyncio.Lock()
|
|
119
|
+
self._bundles_by_hash: dict[str, _bundle.LocalBundle] = {}
|
|
120
|
+
self._session_bundles: dict[str, _bundle.LocalBundle | None] = {}
|
|
121
|
+
self._background: dict[str, _bundle.Background] = {}
|
|
122
|
+
self._transport = Transport(
|
|
123
|
+
self.gateway_url, auth, tenant_id=self.tenant_id, resource_group=self.resource_group
|
|
124
|
+
)
|
|
125
|
+
self._runs: dict[str, str] = {}
|
|
126
|
+
self._receipts: OrderedDict[str, dict[str, Any]] = OrderedDict()
|
|
127
|
+
self._pending: OrderedDict[tuple[str, int], bytes] = OrderedDict()
|
|
128
|
+
self._profile: tuple[float, Mapping[str, Any] | None] | None = None
|
|
129
|
+
self._profile_lock = asyncio.Lock()
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def auth(self) -> Any:
|
|
133
|
+
return self._auth
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def closed(self) -> bool:
|
|
137
|
+
return self._transport.closed
|
|
138
|
+
|
|
139
|
+
# ------------------------------------------------------------------ the Interceptor protocol
|
|
140
|
+
|
|
141
|
+
async def intercept(self, context: Mapping[str, Any], /) -> dict[str, Any]:
|
|
142
|
+
"""The gateway's verdict for ``context`` (an Agent Hooks context: a mapping)."""
|
|
143
|
+
point, session_id, sequence = _route(context)
|
|
144
|
+
local: dict[str, Any] | None = None
|
|
145
|
+
local_verdict: dict[str, Any] | None = None
|
|
146
|
+
if point == "pre_tool_call" and self.bundle:
|
|
147
|
+
local_verdict, local = await self._evaluate_locally(context, session_id)
|
|
148
|
+
if point == "agent_shutdown":
|
|
149
|
+
await self._flush_background(session_id)
|
|
150
|
+
body, sent = await self._prepare(context, point, session_id, local=local)
|
|
151
|
+
if local_verdict is not None and _bundle.is_final(local):
|
|
152
|
+
# A definite local deny is final now; the gateway records the same context meanwhile.
|
|
153
|
+
self._send_later(session_id, body, sent)
|
|
154
|
+
return _bundle.host_verdict(local_verdict)
|
|
155
|
+
try:
|
|
156
|
+
verdict, envelope = await self._evaluate(body, point, session_id)
|
|
157
|
+
finally:
|
|
158
|
+
if point == "agent_shutdown":
|
|
159
|
+
self._end_session(session_id)
|
|
160
|
+
if is_liftable(verdict) and sequence is not None:
|
|
161
|
+
self._keep(self._pending, (session_id, sequence), body, _HELD_KEPT)
|
|
162
|
+
self._record(sent, envelope)
|
|
163
|
+
if point == "agent_startup" and self.bundle and verdict.get("decision") == "allow":
|
|
164
|
+
await self._open_bundle(session_id)
|
|
165
|
+
return verdict
|
|
166
|
+
|
|
167
|
+
def receipt(self, session_id: str) -> dict[str, Any] | None:
|
|
168
|
+
"""The receipt of the session's last decision (``extensions.brutor.receipt``), or None."""
|
|
169
|
+
receipt = self._receipts.get(session_id)
|
|
170
|
+
return copy.deepcopy(receipt) if receipt is not None else None
|
|
171
|
+
|
|
172
|
+
def run(self, session_id: str) -> str | None:
|
|
173
|
+
"""The session's run handle, or None before ``agent_startup`` and after ``agent_shutdown``."""
|
|
174
|
+
return self._runs.get(session_id)
|
|
175
|
+
|
|
176
|
+
async def aclose(self) -> None:
|
|
177
|
+
for session_id in list(self._background):
|
|
178
|
+
self._background.pop(session_id).drop()
|
|
179
|
+
for session_id in list(self._session_bundles):
|
|
180
|
+
self._end_session(session_id)
|
|
181
|
+
for local in self._bundles_by_hash.values():
|
|
182
|
+
local.close()
|
|
183
|
+
self._bundles_by_hash.clear()
|
|
184
|
+
await self._transport.aclose()
|
|
185
|
+
self._runs.clear()
|
|
186
|
+
self._pending.clear()
|
|
187
|
+
|
|
188
|
+
# ------------------------------------------------------------------ the local bundle cache
|
|
189
|
+
|
|
190
|
+
async def _fetch_bundle(self) -> dict[str, Any]:
|
|
191
|
+
"""The agent's export: cached for its max-age (at most 60 s), revalidated by its ETag."""
|
|
192
|
+
async with self._bundle_lock:
|
|
193
|
+
now = time.monotonic()
|
|
194
|
+
cached = self._bundle_doc
|
|
195
|
+
if cached is not None and cached[0] > now:
|
|
196
|
+
return cached[2]
|
|
197
|
+
extra = {"If-None-Match": cached[1]} if cached is not None else None
|
|
198
|
+
response = await self._transport.request(
|
|
199
|
+
"GET", _bundle.ACS_MANIFEST_ROUTE, deadline=now + self.timeout, extra_headers=extra
|
|
200
|
+
)
|
|
201
|
+
max_age = min(_PROFILE_MAX_AGE, _max_age(response.headers.get("Cache-Control")))
|
|
202
|
+
if response.status == 304 and cached is not None:
|
|
203
|
+
doc = cached[2]
|
|
204
|
+
elif response.status == 200 and isinstance(response.body, Mapping):
|
|
205
|
+
doc = dict(response.body)
|
|
206
|
+
else:
|
|
207
|
+
raise _bundle.BundleRefused("bundle_unavailable", f"the export answered HTTP {response.status}")
|
|
208
|
+
etag = response.headers.get("ETag") or (cached[1] if cached is not None else "")
|
|
209
|
+
self._bundle_doc = (now + max_age, etag, doc)
|
|
210
|
+
return doc
|
|
211
|
+
|
|
212
|
+
async def _open_bundle(self, session_id: str) -> None:
|
|
213
|
+
"""Turn the cache on for a session that started; any failure turns it off, with a warning."""
|
|
214
|
+
try:
|
|
215
|
+
checked = _bundle.check_bundle(await self._fetch_bundle(), self._clock())
|
|
216
|
+
local = self._bundles_by_hash.get(checked["source_hash"])
|
|
217
|
+
if local is None or local.expired():
|
|
218
|
+
local = await asyncio.to_thread(_bundle.LocalBundle, checked, clock=self._clock)
|
|
219
|
+
self._bundles_by_hash[checked["source_hash"]] = local
|
|
220
|
+
except _bundle.BundleRefused as e:
|
|
221
|
+
self._bundle_off(session_id, e.code)
|
|
222
|
+
return
|
|
223
|
+
except errors.DecisionUnavailable as e:
|
|
224
|
+
self._bundle_off(session_id, "bundle_unavailable", detail=e.code)
|
|
225
|
+
return
|
|
226
|
+
except Exception as e: # the runtime refused the export: never fatal, the gateway decides
|
|
227
|
+
self._bundle_off(session_id, "bundle_not_loaded", detail=type(e).__name__)
|
|
228
|
+
return
|
|
229
|
+
local.users += 1
|
|
230
|
+
self._session_bundles[session_id] = local
|
|
231
|
+
|
|
232
|
+
def _bundle_off(self, session_id: str, code: str, *, detail: str | None = None) -> None:
|
|
233
|
+
self._session_bundles[session_id] = None
|
|
234
|
+
message = "the local bundle cache is off for this session; decisions are made by the gateway"
|
|
235
|
+
details = {"code": code} | ({"detail": detail} if detail else {})
|
|
236
|
+
self._local_warning(session_id, "agent_startup", "bundle_off", message, **details)
|
|
237
|
+
|
|
238
|
+
async def _evaluate_locally(
|
|
239
|
+
self, context: Mapping[str, Any], session_id: str
|
|
240
|
+
) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
|
|
241
|
+
local = self._session_bundles.get(session_id)
|
|
242
|
+
if local is None:
|
|
243
|
+
return None, None
|
|
244
|
+
if local.expired():
|
|
245
|
+
self._release(session_id)
|
|
246
|
+
self._bundle_off(session_id, "bundle_expired")
|
|
247
|
+
return None, None
|
|
248
|
+
verdict = await local.evaluate(context)
|
|
249
|
+
if verdict is None:
|
|
250
|
+
return None, None
|
|
251
|
+
return verdict, _bundle.local_member(verdict, local.source_hash)
|
|
252
|
+
|
|
253
|
+
def _send_later(self, session_id: str, body: bytes, sent: Mapping[str, Any]) -> None:
|
|
254
|
+
point = str(sent.get("interception_point"))
|
|
255
|
+
|
|
256
|
+
async def send(queued: bytes) -> None:
|
|
257
|
+
_, envelope = await self._evaluate(queued, point, session_id)
|
|
258
|
+
self._record(sent, envelope)
|
|
259
|
+
|
|
260
|
+
background = self._background.get(session_id)
|
|
261
|
+
if background is None:
|
|
262
|
+
background = self._background[session_id] = _bundle.Background(send)
|
|
263
|
+
if not background.put(body):
|
|
264
|
+
self._local_warning(
|
|
265
|
+
session_id, point, "background_queue_full", "a locally denied context was not sent to the gateway"
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
async def _flush_background(self, session_id: str) -> None:
|
|
269
|
+
background = self._background.get(session_id)
|
|
270
|
+
if background is not None:
|
|
271
|
+
await background.flush()
|
|
272
|
+
|
|
273
|
+
def _release(self, session_id: str) -> None:
|
|
274
|
+
local = self._session_bundles.pop(session_id, None)
|
|
275
|
+
if local is None:
|
|
276
|
+
return
|
|
277
|
+
local.users -= 1
|
|
278
|
+
if local.users <= 0:
|
|
279
|
+
self._bundles_by_hash.pop(local.source_hash, None)
|
|
280
|
+
local.close()
|
|
281
|
+
|
|
282
|
+
def _end_session(self, session_id: str) -> None:
|
|
283
|
+
"""At agent_shutdown: unsent background contexts are dropped and the bundle released."""
|
|
284
|
+
background = self._background.pop(session_id, None)
|
|
285
|
+
if background is not None:
|
|
286
|
+
background.drop()
|
|
287
|
+
self._release(session_id)
|
|
288
|
+
|
|
289
|
+
async def __aenter__(self) -> BrutorInterceptor:
|
|
290
|
+
return self
|
|
291
|
+
|
|
292
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
293
|
+
await self.aclose()
|
|
294
|
+
|
|
295
|
+
# ------------------------------------------------------------------ approval (the resolver's)
|
|
296
|
+
|
|
297
|
+
async def _lift(self, context: Mapping[str, Any], approval_token: str) -> dict[str, Any]:
|
|
298
|
+
"""The same context, sent again byte for byte with the approval token: the lifted verdict."""
|
|
299
|
+
point, session_id, sequence = _route(context)
|
|
300
|
+
body = self._pending.get((session_id, sequence)) if sequence is not None else None
|
|
301
|
+
if body is None:
|
|
302
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="this context was not held")
|
|
303
|
+
verdict, envelope = await self._evaluate(body, point, session_id, {"X-Approval-Token": approval_token})
|
|
304
|
+
self._pending.pop((session_id, sequence), None) # type: ignore[arg-type]
|
|
305
|
+
self._record(json.loads(body), envelope)
|
|
306
|
+
return verdict
|
|
307
|
+
|
|
308
|
+
# ------------------------------------------------------------------ sessions that outlive a process
|
|
309
|
+
|
|
310
|
+
def _restore_run(self, session_id: str, run: str) -> None:
|
|
311
|
+
"""Continue a session another process (or an earlier checkpoint) opened: its run handle."""
|
|
312
|
+
if not isinstance(run, str) or not run:
|
|
313
|
+
raise ValueError("a restored session needs the run handle it was given")
|
|
314
|
+
self._runs[session_id] = run
|
|
315
|
+
|
|
316
|
+
async def _rehold(self, context: Mapping[str, Any], run: str) -> None:
|
|
317
|
+
"""Hold a context again, as it was sent with ``run``, so an approval can lift it."""
|
|
318
|
+
point, session_id, sequence = _route(context)
|
|
319
|
+
if sequence is None:
|
|
320
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="a held context has a sequence")
|
|
321
|
+
body, _ = await self._prepare(context, point, session_id, run=run)
|
|
322
|
+
self._keep(self._pending, (session_id, sequence), body, _HELD_KEPT)
|
|
323
|
+
|
|
324
|
+
def _local_warning(self, session_id: str, point: str, reason: str, message: str, **details: Any) -> None:
|
|
325
|
+
"""A warning the SDK raises itself (nothing is sent): to the record sink, never logged with content."""
|
|
326
|
+
logger.debug("local warning at %s: %s", point, reason)
|
|
327
|
+
if self.record_sink is None:
|
|
328
|
+
return
|
|
329
|
+
warning = {"reason": reason, "message": message, **details}
|
|
330
|
+
try:
|
|
331
|
+
self.record_sink({"interception_point": point, "session": {"id": session_id}}, {"local_warning": warning})
|
|
332
|
+
except Exception as e:
|
|
333
|
+
logger.debug("the record sink failed: %s", type(e).__name__)
|
|
334
|
+
|
|
335
|
+
async def _poll(self, path: str, deadline: float) -> tuple[int, Any]:
|
|
336
|
+
response = await self._transport.request("GET", path, deadline=deadline)
|
|
337
|
+
return response.status, response.body
|
|
338
|
+
|
|
339
|
+
# ------------------------------------------------------------------ the request
|
|
340
|
+
|
|
341
|
+
async def _prepare(
|
|
342
|
+
self,
|
|
343
|
+
context: Mapping[str, Any],
|
|
344
|
+
point: str,
|
|
345
|
+
session_id: str,
|
|
346
|
+
*,
|
|
347
|
+
run: str | None = None,
|
|
348
|
+
local: Mapping[str, Any] | None = None,
|
|
349
|
+
) -> tuple[bytes, dict[str, Any]]:
|
|
350
|
+
profile = await self._read_profile() if self.minimise and needs_profile(point) else None
|
|
351
|
+
out, done = minimise(context, profile, enabled=self.minimise)
|
|
352
|
+
extensions = out.get("extensions")
|
|
353
|
+
extensions = dict(extensions) if isinstance(extensions, Mapping) else {}
|
|
354
|
+
given = extensions.get("brutor")
|
|
355
|
+
given = given if isinstance(given, Mapping) else {}
|
|
356
|
+
brutor: dict[str, Any] = {}
|
|
357
|
+
if "delegation" in given:
|
|
358
|
+
# The delegation a delegate's host received: valid at agent_startup only.
|
|
359
|
+
if point != "agent_startup":
|
|
360
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="a delegation outside agent_startup")
|
|
361
|
+
try:
|
|
362
|
+
brutor["delegation"] = check_delegation(given["delegation"])
|
|
363
|
+
except ValueError:
|
|
364
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="the delegation is invalid") from None
|
|
365
|
+
if point != "agent_startup":
|
|
366
|
+
run = run if run is not None else self._runs.get(session_id)
|
|
367
|
+
if run is None:
|
|
368
|
+
raise errors.DecisionUnavailable(errors.NO_RUN, detail="no run handle for this session")
|
|
369
|
+
brutor["run"] = run
|
|
370
|
+
if point in MODEL_POINTS:
|
|
371
|
+
routed = self.gateway_routed(context) if callable(self.gateway_routed) else self.gateway_routed
|
|
372
|
+
brutor["gateway_routed"] = bool(routed)
|
|
373
|
+
brutor["minimised"] = done
|
|
374
|
+
if local is not None:
|
|
375
|
+
brutor["local"] = dict(local)
|
|
376
|
+
extensions["brutor"] = brutor
|
|
377
|
+
out["extensions"] = extensions
|
|
378
|
+
try:
|
|
379
|
+
canonical(out) # I-JSON only: an out-of-range integer is refused, never rounded
|
|
380
|
+
body = json.dumps(out, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
|
381
|
+
except (TypeError, ValueError):
|
|
382
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="the context is not I-JSON") from None
|
|
383
|
+
return body, out
|
|
384
|
+
|
|
385
|
+
async def _evaluate(
|
|
386
|
+
self, body: bytes, point: str, session_id: str, extra: Mapping[str, str] | None = None
|
|
387
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
388
|
+
deadline = time.monotonic() + self.timeout
|
|
389
|
+
response = await self._transport.request("POST", EVALUATE, deadline=deadline, body=body, extra_headers=extra)
|
|
390
|
+
if response.status not in _VERDICT_STATUSES:
|
|
391
|
+
code = code_of(response) or f"http_{response.status}"
|
|
392
|
+
raise errors.DecisionUnavailable(code, status=response.status)
|
|
393
|
+
try:
|
|
394
|
+
verdict, brutor = check_envelope(response.body)
|
|
395
|
+
except InvalidTransform as e:
|
|
396
|
+
raise errors.DecisionUnavailable(e.code, status=response.status) from None
|
|
397
|
+
except InvalidResponse:
|
|
398
|
+
raise errors.DecisionUnavailable(errors.VERDICT_INVALID, status=response.status) from None
|
|
399
|
+
run = brutor.get("run")
|
|
400
|
+
if point == "agent_shutdown":
|
|
401
|
+
self._runs.pop(session_id, None)
|
|
402
|
+
for key in [k for k in self._pending if k[0] == session_id]:
|
|
403
|
+
del self._pending[key]
|
|
404
|
+
elif isinstance(run, str):
|
|
405
|
+
self._runs[session_id] = run
|
|
406
|
+
receipt = brutor.get("receipt")
|
|
407
|
+
if isinstance(receipt, Mapping):
|
|
408
|
+
self._keep(self._receipts, session_id, dict(receipt), _SESSIONS_KEPT)
|
|
409
|
+
logger.debug("decision at %s: %s %s", point, verdict.get("decision"), verdict.get("reason") or "")
|
|
410
|
+
envelope = {"verdict": verdict, "extensions": {"brutor": brutor}} if brutor else {"verdict": verdict}
|
|
411
|
+
return verdict, envelope
|
|
412
|
+
|
|
413
|
+
async def _read_profile(self) -> Mapping[str, Any] | None:
|
|
414
|
+
"""The gateway's content profile, cached for its max-age (at most 60 s); None when unreadable."""
|
|
415
|
+
async with self._profile_lock:
|
|
416
|
+
now = time.monotonic()
|
|
417
|
+
if self._profile is not None and self._profile[0] > now:
|
|
418
|
+
return self._profile[1]
|
|
419
|
+
profile: Mapping[str, Any] | None = None
|
|
420
|
+
max_age = _PROFILE_MAX_AGE
|
|
421
|
+
try:
|
|
422
|
+
response = await self._transport.request("GET", PROFILE, deadline=now + self.timeout)
|
|
423
|
+
if response.status == 200 and isinstance(response.body, Mapping):
|
|
424
|
+
profile = response.body
|
|
425
|
+
max_age = min(_PROFILE_MAX_AGE, _max_age(response.headers.get("Cache-Control")))
|
|
426
|
+
else:
|
|
427
|
+
max_age = 0.0
|
|
428
|
+
except errors.DecisionUnavailable as e:
|
|
429
|
+
logger.debug("the content profile could not be read (%s): minimising everything", e.code)
|
|
430
|
+
max_age = 0.0
|
|
431
|
+
self._profile = (now + max_age, profile)
|
|
432
|
+
return profile
|
|
433
|
+
|
|
434
|
+
def _record(self, sent: Mapping[str, Any], envelope: Mapping[str, Any]) -> None:
|
|
435
|
+
if self.record_sink is None:
|
|
436
|
+
return
|
|
437
|
+
try:
|
|
438
|
+
self.record_sink(_for_the_sink(sent), _for_the_sink(envelope))
|
|
439
|
+
except Exception as e:
|
|
440
|
+
logger.debug("the record sink failed: %s", type(e).__name__)
|
|
441
|
+
|
|
442
|
+
@staticmethod
|
|
443
|
+
def _keep(store: OrderedDict[Any, Any], key: Any, value: Any, limit: int) -> None:
|
|
444
|
+
store[key] = value
|
|
445
|
+
store.move_to_end(key)
|
|
446
|
+
while len(store) > limit:
|
|
447
|
+
store.popitem(last=False)
|
|
448
|
+
|
|
449
|
+
# ------------------------------------------------------------------ never copied, never shown
|
|
450
|
+
|
|
451
|
+
def __repr__(self) -> str:
|
|
452
|
+
return f"BrutorInterceptor(gateway_url={self.gateway_url!r}, timeout={self.timeout!r})"
|
|
453
|
+
|
|
454
|
+
def __reduce_ex__(self, protocol: object) -> NoReturn:
|
|
455
|
+
raise TypeError("a BrutorInterceptor holds credentials and run handles: it is never serialised")
|
|
456
|
+
|
|
457
|
+
def __copy__(self) -> NoReturn:
|
|
458
|
+
raise TypeError("a BrutorInterceptor is never copied")
|
|
459
|
+
|
|
460
|
+
def __deepcopy__(self, memo: object) -> NoReturn:
|
|
461
|
+
raise TypeError("a BrutorInterceptor is never copied")
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
def _route(context: Any) -> tuple[str, str, int | None]:
|
|
465
|
+
"""(point, session id, sequence) of a context, or DecisionUnavailable('invalid_context')."""
|
|
466
|
+
if not isinstance(context, Mapping):
|
|
467
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="the context is not a mapping")
|
|
468
|
+
point = context.get("interception_point")
|
|
469
|
+
session = context.get("session")
|
|
470
|
+
session_id = session.get("id") if isinstance(session, Mapping) else None
|
|
471
|
+
if point not in POINTS or not isinstance(session_id, str) or not session_id:
|
|
472
|
+
raise errors.DecisionUnavailable(errors.INVALID_CONTEXT, detail="no interception point or session id")
|
|
473
|
+
sequence = context.get("sequence")
|
|
474
|
+
seq = sequence if isinstance(sequence, int) and not isinstance(sequence, bool) else None
|
|
475
|
+
return str(point), session_id, seq
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _max_age(cache_control: str | None) -> float:
|
|
479
|
+
for part in (cache_control or "").split(","):
|
|
480
|
+
name, _, value = part.strip().partition("=")
|
|
481
|
+
if name.lower() == "max-age":
|
|
482
|
+
try:
|
|
483
|
+
return max(0.0, float(value))
|
|
484
|
+
except ValueError:
|
|
485
|
+
return 0.0
|
|
486
|
+
return _PROFILE_MAX_AGE
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
def _for_the_sink(value: Mapping[str, Any]) -> dict[str, Any]:
|
|
490
|
+
out = copy.deepcopy(dict(value))
|
|
491
|
+
brutor = out.get("extensions", {}).get("brutor") if isinstance(out.get("extensions"), dict) else None
|
|
492
|
+
if isinstance(brutor, dict):
|
|
493
|
+
brutor.pop("run", None) # the run handle: bound to the agent's credential
|
|
494
|
+
brutor.pop("delegation", None) # the caller's delegation chain: the gateway's to read, no one else's
|
|
495
|
+
return out
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""Data minimisation: content the gateway's checks do not read never leaves the process.
|
|
5
|
+
|
|
6
|
+
The gateway's profile (``GET /v1/runtime-hooks/profile``) says which content a check reads: the
|
|
7
|
+
input, the output, and the results of which tools. Every other content member is replaced by
|
|
8
|
+
``{"sha256": <hex of its canonical JSON>}`` (``messages`` by ``[]``), and ``target``, which mirrors
|
|
9
|
+
the point's subject, is set to the replaced value too. Tool arguments and the tool calls a model
|
|
10
|
+
asks for are always sent: policies read them. A member that is null, or ``messages`` that is
|
|
11
|
+
already empty, is left as it is. With no profile, everything that can be minimised is.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import copy
|
|
17
|
+
from collections.abc import Mapping
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from brutor.runtime_hooks._jcs import canonical, sha256_hex
|
|
21
|
+
|
|
22
|
+
MINIMISABLE = ("messages", "input.content", "output.content", "tool_result.value", "response.content")
|
|
23
|
+
TARGET_OF = {
|
|
24
|
+
"agent_startup": "agent_init",
|
|
25
|
+
"input": "input",
|
|
26
|
+
"pre_model_call": "messages",
|
|
27
|
+
"post_model_call": "response",
|
|
28
|
+
"pre_tool_call": "tool_call.args",
|
|
29
|
+
"post_tool_call": "tool_result.value",
|
|
30
|
+
"output": "output",
|
|
31
|
+
"agent_shutdown": "summary",
|
|
32
|
+
}
|
|
33
|
+
_MISSING = object()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _get(ctx: Mapping[str, Any], path: str) -> Any:
|
|
37
|
+
cur: Any = ctx
|
|
38
|
+
for part in path.split("."):
|
|
39
|
+
if not isinstance(cur, Mapping) or part not in cur:
|
|
40
|
+
return _MISSING
|
|
41
|
+
cur = cur[part]
|
|
42
|
+
return cur
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _set(ctx: dict[str, Any], path: str, value: Any) -> None:
|
|
46
|
+
parts = path.split(".")
|
|
47
|
+
cur = ctx
|
|
48
|
+
for part in parts[:-1]:
|
|
49
|
+
cur = cur[part]
|
|
50
|
+
cur[parts[-1]] = value
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def hashed(value: Any) -> dict[str, str]:
|
|
54
|
+
return {"sha256": sha256_hex(canonical(value))}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _needed(profile: Mapping[str, Any] | None, member: str, ctx: Mapping[str, Any]) -> bool:
|
|
58
|
+
content = (profile or {}).get("content")
|
|
59
|
+
if not isinstance(content, Mapping):
|
|
60
|
+
return False
|
|
61
|
+
if member == "input.content":
|
|
62
|
+
return content.get("input") is True
|
|
63
|
+
if member == "output.content":
|
|
64
|
+
return content.get("output") is True
|
|
65
|
+
if member == "messages":
|
|
66
|
+
return content.get("messages") is True
|
|
67
|
+
if member == "tool_result.value":
|
|
68
|
+
tools = content.get("tool_results")
|
|
69
|
+
if not isinstance(tools, list):
|
|
70
|
+
return False
|
|
71
|
+
name = _get(ctx, "tool_call.name")
|
|
72
|
+
return "*" in tools or (isinstance(name, str) and name in tools)
|
|
73
|
+
return False # response.content: no check reads it
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def needs_profile(point: str) -> bool:
|
|
77
|
+
"""Whether a point carries content that the profile decides about."""
|
|
78
|
+
return point in ("input", "pre_model_call", "post_model_call", "post_tool_call", "output")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def minimise(
|
|
82
|
+
context: Mapping[str, Any], profile: Mapping[str, Any] | None, *, enabled: bool = True
|
|
83
|
+
) -> tuple[dict[str, Any], list[str]]:
|
|
84
|
+
"""The context to send and the members replaced. Never changes ``context``."""
|
|
85
|
+
out: dict[str, Any] = copy.deepcopy(dict(context))
|
|
86
|
+
done: list[str] = []
|
|
87
|
+
if not enabled:
|
|
88
|
+
return out, done
|
|
89
|
+
for member in MINIMISABLE:
|
|
90
|
+
value = _get(out, member)
|
|
91
|
+
if value is _MISSING or value is None or _needed(profile, member, out):
|
|
92
|
+
continue
|
|
93
|
+
if member == "messages":
|
|
94
|
+
if value == []:
|
|
95
|
+
continue
|
|
96
|
+
_set(out, member, [])
|
|
97
|
+
else:
|
|
98
|
+
_set(out, member, hashed(value))
|
|
99
|
+
done.append(member)
|
|
100
|
+
target_path = TARGET_OF.get(str(out.get("interception_point")))
|
|
101
|
+
if target_path is not None and done:
|
|
102
|
+
target = _get(out, target_path)
|
|
103
|
+
if target is not _MISSING:
|
|
104
|
+
out["target"] = copy.deepcopy(target)
|
|
105
|
+
return out, done
|
|
File without changes
|