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,294 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """The local bundle cache: Brutor's stateless tool rules, evaluated in the agent's process.
5
+
6
+ Off by default (``BrutorInterceptor(bundle=True)`` turns it on; it needs the ``bundle`` extra,
7
+ the pinned Agent Control Specification runtime). After ``agent_startup`` the interceptor fetches
8
+ the agent's export (``GET /v1/runtime-hooks/acs-manifest``), writes its files to a private
9
+ temporary directory (0700, files 0600, removed when the last session using it closes) and readies
10
+ the runtime. At ``pre_tool_call`` only:
11
+
12
+ 1. the context is evaluated locally, bounded by 50 ms; a slower or failed evaluation is ignored,
13
+ never a deny;
14
+ 2. a definite local deny (not ``brutor_decision_required``, not a ``runtime_error:``) is the
15
+ host's verdict at once, and the same context is still sent to the Decision API in the
16
+ background with ``extensions.brutor.local``, under the same sequence, so the decision is
17
+ recorded; the gateway's answer never lifts the local deny;
18
+ 3. anything else goes to the Decision API as usual, with ``extensions.brutor.local`` describing
19
+ the local verdict. A local allow is never final.
20
+
21
+ An expired bundle, one for another manifest contract, or one that cannot be fetched or readied
22
+ turns the cache off for the session (a local warning through the record sink); decisions continue
23
+ remotely.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import asyncio
29
+ import concurrent.futures
30
+ import contextlib
31
+ import os
32
+ import re
33
+ import shutil
34
+ import tempfile
35
+ from collections.abc import Callable, Mapping
36
+ from datetime import UTC, datetime
37
+ from pathlib import PurePosixPath
38
+ from typing import Any
39
+
40
+ ACS_MANIFEST_VERSION = "0.5.0-alpha.1"
41
+ ACS_SOFTWARE = "0.4.0-beta.2"
42
+ ACS_MANIFEST_ROUTE = "/v1/runtime-hooks/acs-manifest"
43
+ LOCAL_BUDGET_S = 0.050
44
+ QUEUE_MAX = 256
45
+ RETRY_FOR_S = 60.0
46
+ NOT_FINAL = "brutor_decision_required"
47
+ LOCAL_DECISIONS = ("allow", "deny", "escalate", "warn")
48
+ _HASH = re.compile(r"^[0-9a-f]{64}$")
49
+ _FILE = re.compile(r"^[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*$")
50
+ _FILES_MAX = 64
51
+ _BYTES_MAX = 4 * 1024 * 1024
52
+ _WORKERS = 4
53
+
54
+
55
+ class BundleRefused(ValueError):
56
+ """The export cannot be used locally; ``code`` says why (the cache is then off for the session)."""
57
+
58
+ def __init__(self, code: str, detail: str) -> None:
59
+ self.code = code
60
+ super().__init__(f"{code}: {detail}")
61
+
62
+
63
+ def _moment(value: Any, what: str) -> datetime:
64
+ if not isinstance(value, str):
65
+ raise BundleRefused("bundle_invalid", f"{what} is not a time")
66
+ try:
67
+ moment = datetime.fromisoformat(value.replace("Z", "+00:00"))
68
+ except ValueError:
69
+ raise BundleRefused("bundle_invalid", f"{what} is not an RFC 3339 time") from None
70
+ if moment.tzinfo is None:
71
+ raise BundleRefused("bundle_invalid", f"{what} has no time zone")
72
+ return moment
73
+
74
+
75
+ def check_bundle(doc: Any, now: datetime | None = None) -> dict[str, Any]:
76
+ """The export as the cache uses it, or ``BundleRefused`` (with the reason the cache is off)."""
77
+ if not isinstance(doc, Mapping):
78
+ raise BundleRefused("bundle_invalid", "the export is not an object")
79
+ if doc.get("spec") != ACS_MANIFEST_VERSION:
80
+ raise BundleRefused("bundle_spec_mismatch", f"the export is not for manifest contract {ACS_MANIFEST_VERSION}")
81
+ source_hash = doc.get("source_hash")
82
+ if not isinstance(source_hash, str) or not _HASH.match(source_hash):
83
+ raise BundleRefused("bundle_invalid", "the source hash is not 64 hex digits")
84
+ valid_until = _moment(doc.get("valid_until"), "valid_until")
85
+ _moment(doc.get("generated_at"), "generated_at")
86
+ if valid_until <= (now or datetime.now(UTC)):
87
+ raise BundleRefused("bundle_expired", "the export is past its valid_until")
88
+ files = doc.get("files")
89
+ if not isinstance(files, Mapping) or not files:
90
+ raise BundleRefused("bundle_empty", "the export has no files (no AI System governs this agent)")
91
+ if "manifest.yaml" not in files:
92
+ raise BundleRefused("bundle_invalid", "the export has no manifest.yaml")
93
+ if len(files) > _FILES_MAX:
94
+ raise BundleRefused("bundle_invalid", "the export has too many files")
95
+ total = 0
96
+ for name, text in files.items():
97
+ if not isinstance(name, str) or not _FILE.match(name) or any(p in (".", "..") for p in name.split("/")):
98
+ raise BundleRefused("bundle_invalid", "a file path is not a plain relative path")
99
+ if not isinstance(text, str):
100
+ raise BundleRefused("bundle_invalid", "a file is not text")
101
+ total += len(text.encode("utf-8"))
102
+ if total > _BYTES_MAX:
103
+ raise BundleRefused("bundle_invalid", "the export is larger than 4 MiB")
104
+ return {"source_hash": source_hash, "valid_until": valid_until, "files": dict(files)}
105
+
106
+
107
+ def local_member(verdict: Mapping[str, Any], source_hash: str) -> dict[str, Any] | None:
108
+ """``extensions.brutor.local`` for an ACS verdict, or None when it has no local meaning.
109
+
110
+ ``deny`` with an approval block is ``escalate``; ``allow`` with warnings is ``warn``. A
111
+ ``transform`` (never in an export) has no local meaning: the context goes remote without it.
112
+ """
113
+ decision = verdict.get("decision")
114
+ if decision == "deny":
115
+ local = "escalate" if isinstance(verdict.get("approval"), Mapping) else "deny"
116
+ elif decision == "allow":
117
+ local = "warn" if verdict.get("warnings") else "allow"
118
+ else:
119
+ return None
120
+ out: dict[str, Any] = {"decision": local}
121
+ reason = verdict.get("reason")
122
+ if isinstance(reason, str) and reason:
123
+ out["reason"] = reason
124
+ out["source_hash"] = source_hash
125
+ return out
126
+
127
+
128
+ def is_final(local: Mapping[str, Any] | None) -> bool:
129
+ """A definite local deny: the only local verdict the host enforces without the gateway."""
130
+ if local is None or local.get("decision") != "deny":
131
+ return False
132
+ reason = str(local.get("reason") or "")
133
+ return reason != NOT_FINAL and not reason.startswith("runtime_error:")
134
+
135
+
136
+ def host_verdict(verdict: Mapping[str, Any]) -> dict[str, Any]:
137
+ """The verdict a host enforces for a final local deny: the decision, reason and message."""
138
+ return {k: verdict[k] for k in ("decision", "reason", "message") if isinstance(verdict.get(k), str)}
139
+
140
+
141
+ def _activator() -> Callable[[str], Any]:
142
+ try:
143
+ from agent_control_spec import ActivatedPolicy # noqa: PLC0415 (the bundle extra)
144
+ except ImportError: # pragma: no cover - the interceptor checks the extra when bundle=True
145
+ raise BundleRefused("bundle_runtime_missing", "install brutor-runtime-hooks[bundle]") from None
146
+ activate: Callable[[str], Any] = ActivatedPolicy
147
+ return activate
148
+
149
+
150
+ def runtime_available() -> bool:
151
+ try:
152
+ _activator()
153
+ except BundleRefused: # pragma: no cover - the extra is installed where this is tested
154
+ return False
155
+ return True
156
+
157
+
158
+ def _wall_clock() -> datetime:
159
+ return datetime.now(UTC)
160
+
161
+
162
+ class LocalBundle:
163
+ """One export on disk, readied in the pinned runtime, shared by the sessions that use it."""
164
+
165
+ def __init__(
166
+ self,
167
+ checked: Mapping[str, Any],
168
+ *,
169
+ activate: Callable[[str], Any] | None = None,
170
+ clock: Callable[[], datetime] | None = None,
171
+ ) -> None:
172
+ self._clock = clock or _wall_clock
173
+ self.source_hash: str = checked["source_hash"]
174
+ self.valid_until: datetime = checked["valid_until"]
175
+ self.users = 0
176
+ self._dir = tempfile.mkdtemp(prefix="brutor-acs-") # 0700
177
+ try:
178
+ os.chmod(self._dir, 0o700)
179
+ for name, text in checked["files"].items():
180
+ self._write(name, text)
181
+ ready = activate or _activator()
182
+ self._policy = ready(os.path.join(self._dir, "manifest.yaml"))
183
+ except BaseException:
184
+ shutil.rmtree(self._dir, ignore_errors=True)
185
+ raise
186
+ self._pool = concurrent.futures.ThreadPoolExecutor(max_workers=_WORKERS, thread_name_prefix="brutor-acs")
187
+
188
+ @property
189
+ def directory(self) -> str:
190
+ return self._dir
191
+
192
+ def _write(self, name: str, text: str) -> None:
193
+ path = PurePosixPath(name)
194
+ current = self._dir
195
+ for part in path.parts[:-1]:
196
+ current = os.path.join(current, part)
197
+ if not os.path.isdir(current):
198
+ os.mkdir(current, 0o700)
199
+ target = os.path.join(current, path.parts[-1])
200
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
201
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
202
+ f.write(text)
203
+
204
+ def expired(self, now: datetime | None = None) -> bool:
205
+ return self.valid_until <= (now or self._clock())
206
+
207
+ async def evaluate(self, context: Mapping[str, Any]) -> dict[str, Any] | None:
208
+ """The local ACS verdict (wire form) within the 50 ms budget, or None (slow, failed, expired)."""
209
+ if self.expired():
210
+ return None
211
+ loop = asyncio.get_running_loop()
212
+ future = loop.run_in_executor(self._pool, self._policy.evaluate, "pre_tool_call", dict(context))
213
+ try:
214
+ verdict = await asyncio.wait_for(future, LOCAL_BUDGET_S)
215
+ except (TimeoutError, Exception):
216
+ return None # ignored, never a deny: the gateway decides
217
+ to_wire = getattr(verdict, "to_wire", None)
218
+ wire = to_wire() if callable(to_wire) else verdict
219
+ return dict(wire) if isinstance(wire, Mapping) else None
220
+
221
+ def close(self) -> None:
222
+ self._pool.shutdown(wait=False, cancel_futures=True)
223
+ shutil.rmtree(self._dir, ignore_errors=True)
224
+
225
+ def __repr__(self) -> str:
226
+ return f"LocalBundle(source_hash={self.source_hash[:12]!r})"
227
+
228
+
229
+ class Background:
230
+ """A session's queue of contexts sent after a final local deny: bounded, retried, flushed.
231
+
232
+ ``send(body)`` is the interceptor's call that evaluates a body and records the answer. A
233
+ send that fails is retried with the identical body (the gateway answers a retry from its
234
+ stored decision) for up to 60 s. ``flush()`` waits until every queued body was sent or gave
235
+ up; ``drop()`` discards what is left. A body that does not fit in the queue is not sent: the
236
+ gateway then sees a gap in the session's sequences, which coverage reports.
237
+ """
238
+
239
+ def __init__(
240
+ self, send: Callable[[bytes], Any], *, retry_for: float | None = None, size: int | None = None
241
+ ) -> None:
242
+ self._send = send
243
+ self._retry_for = RETRY_FOR_S if retry_for is None else retry_for
244
+ self._queue: asyncio.Queue[tuple[bytes, float]] = asyncio.Queue(maxsize=QUEUE_MAX if size is None else size)
245
+ self._worker: asyncio.Task[None] | None = None
246
+
247
+ def put(self, body: bytes) -> bool:
248
+ """Queue a body; False when the queue is full (the body is not sent)."""
249
+ try:
250
+ self._queue.put_nowait((body, asyncio.get_running_loop().time() + self._retry_for))
251
+ except asyncio.QueueFull:
252
+ return False
253
+ if self._worker is None or self._worker.done():
254
+ self._worker = asyncio.create_task(self._run())
255
+ return True
256
+
257
+ async def _run(self) -> None:
258
+ while not self._queue.empty():
259
+ body, give_up_at = await self._queue.get()
260
+ try:
261
+ await self._deliver(body, give_up_at)
262
+ finally:
263
+ self._queue.task_done()
264
+
265
+ async def _deliver(self, body: bytes, give_up_at: float) -> None:
266
+ loop = asyncio.get_running_loop()
267
+ wait = 0.25
268
+ while True:
269
+ try:
270
+ await self._send(body)
271
+ return
272
+ except asyncio.CancelledError:
273
+ raise
274
+ except Exception:
275
+ if loop.time() + wait >= give_up_at:
276
+ return # given up: the gap is reported by coverage
277
+ await asyncio.sleep(wait)
278
+ wait = min(wait * 2, 5.0)
279
+
280
+ async def flush(self) -> None:
281
+ if self._worker is not None:
282
+ await self._queue.join()
283
+
284
+ def drop(self) -> None:
285
+ if self._worker is not None and not self._worker.done():
286
+ self._worker.cancel()
287
+ while not self._queue.empty():
288
+ with contextlib.suppress(asyncio.QueueEmpty):
289
+ self._queue.get_nowait()
290
+ self._queue.task_done()
291
+
292
+ @property
293
+ def pending(self) -> int:
294
+ return self._queue.qsize()
@@ -0,0 +1,92 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """The exceptions the SDK raises. None of them carries a credential, a run handle or content."""
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+
11
+ # Codes of DecisionUnavailable the SDK sets itself; the gateway's own codes (HOOKS_*) pass through.
12
+ TIMEOUT = "timeout"
13
+ CONNECTION = "connection"
14
+ NO_RUN = "no_run"
15
+ INVALID_CONTEXT = "invalid_context"
16
+ VERDICT_INVALID = "verdict_invalid"
17
+ UNAUTHENTICATED = "unauthenticated"
18
+ CREDENTIAL = "credential"
19
+ CLOSED = "closed"
20
+ # A transform whose path is outside the Agent Hooks grammar: a host denies it with host_error:<code>.
21
+ TRANSFORM_INVALID = "transform_invalid"
22
+ TRANSFORM_TARGET_FORBIDDEN = "transform_target_forbidden"
23
+ # The gateway's code for a sequence this session already used with another context.
24
+ SEQUENCE_CONFLICT = "HOOKS_SEQUENCE_CONFLICT"
25
+
26
+
27
+ class DecisionUnavailable(Exception):
28
+ """The gateway gave no usable decision, so the host must fail closed.
29
+
30
+ An Agent Hooks host maps it to ``host_error:interceptor_failed``. ``code`` is the gateway's
31
+ code (``HOOKS_INVALID_CONTEXT``, ``HOOKS_SEQUENCE_CONFLICT``, ``HOOKS_UNAVAILABLE`` and the
32
+ others), ``http_<status>`` for an answer without one, or one of the SDK's own: ``timeout``,
33
+ ``connection``, ``no_run``, ``invalid_context``, ``verdict_invalid``, ``unauthenticated``,
34
+ ``credential``, ``closed``, and ``transform_invalid`` or ``transform_target_forbidden`` for a
35
+ transform whose path the Agent Hooks grammar refuses (``HookSession`` denies those with the
36
+ matching ``host_error:`` reason). ``status`` is the HTTP status when there was an answer.
37
+ """
38
+
39
+ def __init__(self, code: str, *, status: int | None = None, detail: str | None = None) -> None:
40
+ self.code = code
41
+ self.status = status
42
+ self.detail = detail
43
+ text = f"no decision from the gateway: {code}"
44
+ if status is not None:
45
+ text += f" (HTTP {status})"
46
+ if detail:
47
+ text += f": {detail}"
48
+ super().__init__(text)
49
+
50
+ def __repr__(self) -> str:
51
+ return f"DecisionUnavailable({self.code!r}, status={self.status!r})"
52
+
53
+
54
+ class HookDenied(Exception):
55
+ """A deny the host enforces by not starting: the session (or client) was refused at startup.
56
+
57
+ ``verdict`` is the verdict as the gateway (or the host's fail-closed rule) gave it.
58
+ """
59
+
60
+ def __init__(self, verdict: Mapping[str, Any]) -> None:
61
+ self.verdict = dict(verdict)
62
+ super().__init__(_sentence(self.verdict))
63
+
64
+ def __repr__(self) -> str:
65
+ return f"{type(self).__name__}(reason={self.verdict.get('reason')!r})"
66
+
67
+
68
+ class OutputDenied(HookDenied):
69
+ """The agent's final answer was denied at ``output``: it is not handed to the caller."""
70
+
71
+
72
+ class UncoveredTools(ValueError):
73
+ """The agent has tools its framework runs where the adapter cannot see them.
74
+
75
+ Raised when the agent is wrapped, before anything starts. ``tools`` names them. Pass them in
76
+ ``allow_uncovered`` to run the agent anyway: they are then still reported at
77
+ ``agent_startup`` (``tools_registered``) and a local ``uncovered_tools`` warning goes to the
78
+ interceptor's ``record_sink``.
79
+ """
80
+
81
+ def __init__(self, tools: list[str], why: str) -> None:
82
+ self.tools = list(tools)
83
+ super().__init__(
84
+ f"these tools run where the adapter cannot intercept them ({why}): {', '.join(self.tools)}; "
85
+ "remove them or pass them in allow_uncovered"
86
+ )
87
+
88
+
89
+ def _sentence(verdict: Mapping[str, Any]) -> str:
90
+ reason = verdict.get("reason") or "denied"
91
+ message = verdict.get("message")
92
+ return f"{reason}: {message}" if message else str(reason)