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,566 @@
|
|
|
1
|
+
# Copyright 2026 Brutor AI Ltd. All rights reserved.
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
|
|
3
|
+
|
|
4
|
+
"""HookSession: an Agent Hooks host for code that has none (a hand-written loop, a framework without one).
|
|
5
|
+
|
|
6
|
+
The session builds each context as Agent Hooks 0.1 defines it, owns its ``sequence`` (0 at
|
|
7
|
+
``agent_startup``, one more per emission, under a lock, so parallel tool calls get distinct
|
|
8
|
+
numbers), asks the interceptor, consults the approval resolver for a liftable deny, applies a
|
|
9
|
+
``transform`` to the point's target, and fails closed as a host must: an interceptor that raises or
|
|
10
|
+
answers nothing usable gives a deny with the reserved ``host_error:`` reason, and so does a
|
|
11
|
+
transform that does not apply (``host_error:transform_invalid``; at ``agent_startup``
|
|
12
|
+
``host_error:transform_target_forbidden``). Every step returns a ``HookOutcome``: the host acts
|
|
13
|
+
only when ``proceeds`` is true, and then with ``target``, which is the transformed value when the
|
|
14
|
+
gateway redacted or rewrote it. A deny at ``agent_startup`` raises ``HookDenied`` and the block
|
|
15
|
+
does not run. ``agent_shutdown`` is sent when
|
|
16
|
+
the block ends, with the reason ``completed``, ``error`` or ``cancelled`` (and with ``error`` right
|
|
17
|
+
after a denied start); its verdict is not enforced.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import asyncio
|
|
23
|
+
import copy
|
|
24
|
+
import logging
|
|
25
|
+
import re
|
|
26
|
+
import uuid
|
|
27
|
+
from collections.abc import Mapping, Sequence
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from datetime import UTC, datetime
|
|
30
|
+
from types import TracebackType
|
|
31
|
+
from typing import Any, Protocol
|
|
32
|
+
|
|
33
|
+
from brutor.runtime_hooks import errors
|
|
34
|
+
from brutor.runtime_hooks._delegation import RUN_HEADER, check_delegation, without_delegation
|
|
35
|
+
from brutor.runtime_hooks._jcs import canonical, sha256_hex
|
|
36
|
+
from brutor.runtime_hooks._verdict import InvalidResponse, InvalidTransform, check_verdict, is_liftable, permits
|
|
37
|
+
from brutor.runtime_hooks.interceptor import SPEC_VERSION
|
|
38
|
+
from brutor.runtime_hooks.transform import (
|
|
39
|
+
TRANSFORM_INVALID,
|
|
40
|
+
TRANSFORM_TARGET_FORBIDDEN,
|
|
41
|
+
TransformRefused,
|
|
42
|
+
apply_transform,
|
|
43
|
+
target_fits,
|
|
44
|
+
transform_permitted,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
logger = logging.getLogger("brutor.runtime_hooks")
|
|
48
|
+
_FRAMEWORK = re.compile(r"^[a-z0-9_-]+$")
|
|
49
|
+
|
|
50
|
+
INTERCEPTOR_FAILED = "host_error:interceptor_failed"
|
|
51
|
+
INTERCEPTOR_TIMEOUT = "host_error:interceptor_timeout"
|
|
52
|
+
VERDICT_INVALID = "host_error:verdict_invalid"
|
|
53
|
+
CONTEXT_INVALID = "host_error:context_invalid"
|
|
54
|
+
APPROVAL_RESOLVER_FAILED = "host_error:approval_resolver_failed"
|
|
55
|
+
APPROVAL_UNRESOLVED = "host_error:approval_unresolved"
|
|
56
|
+
APPROVAL_IDENTITY_MISMATCH = "host_error:approval_identity_mismatch"
|
|
57
|
+
# The interceptor's codes for a transform outside the grammar, and the deny each one becomes.
|
|
58
|
+
_TRANSFORM_CODES = {
|
|
59
|
+
errors.TRANSFORM_INVALID: TRANSFORM_INVALID,
|
|
60
|
+
errors.TRANSFORM_TARGET_FORBIDDEN: TRANSFORM_TARGET_FORBIDDEN,
|
|
61
|
+
}
|
|
62
|
+
# Where the session applies a transform: every point with a target.
|
|
63
|
+
TRANSFORMS = {
|
|
64
|
+
"input": "applied",
|
|
65
|
+
"pre_model_call": "applied",
|
|
66
|
+
"post_model_call": "applied",
|
|
67
|
+
"pre_tool_call": "applied",
|
|
68
|
+
"post_tool_call": "applied",
|
|
69
|
+
"output": "applied",
|
|
70
|
+
}
|
|
71
|
+
# A restored session (another process, a checkpoint) does not know every sequence its earlier part
|
|
72
|
+
# used; a sequence the gateway already holds with another context is skipped, at most this often.
|
|
73
|
+
_SEQUENCE_PROBES = 64
|
|
74
|
+
|
|
75
|
+
# The closed projection the jcs-sha256 identity hashes: the required core and, per point, the
|
|
76
|
+
# required members with their required subfields.
|
|
77
|
+
_CORE = {
|
|
78
|
+
"spec": None,
|
|
79
|
+
"interception_point": None,
|
|
80
|
+
"timestamp": None,
|
|
81
|
+
"sequence": None,
|
|
82
|
+
"agent": ("id", "framework"),
|
|
83
|
+
"session": ("id",),
|
|
84
|
+
"target": None,
|
|
85
|
+
}
|
|
86
|
+
_PER_POINT: dict[str, dict[str, tuple[str, ...] | None]] = {
|
|
87
|
+
"agent_startup": {"agent_init": ("tools_registered",)},
|
|
88
|
+
"input": {"input": ("content", "role")},
|
|
89
|
+
"pre_model_call": {"model": ("id",), "messages": None},
|
|
90
|
+
"post_model_call": {"model": ("id",), "response": ("content", "tool_calls", "finish_reason")},
|
|
91
|
+
"pre_tool_call": {"tool_call": ("id", "name", "args")},
|
|
92
|
+
"post_tool_call": {"tool_call": ("id", "name", "args"), "tool_result": ("value", "is_error")},
|
|
93
|
+
"output": {"output": ("content",)},
|
|
94
|
+
"agent_shutdown": {"summary": ("reason",)},
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class HookOutcome:
|
|
100
|
+
"""What the host does after one step: whether the action proceeds, and with what.
|
|
101
|
+
|
|
102
|
+
``verdict`` is the verdict enforced (after the approval resolver; a transform that did not apply
|
|
103
|
+
is the deny it became). ``proceeds`` is true for an allow and for a transform that was applied.
|
|
104
|
+
``target`` is the point's target as the host must use it when it proceeds: the transformed value
|
|
105
|
+
after a transform (the arguments to call the tool with, the result to hand back, the text to
|
|
106
|
+
deliver), else a copy of the value sent; ``None`` when the action does not proceed.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
verdict: dict[str, Any]
|
|
110
|
+
proceeds: bool
|
|
111
|
+
target: Any = None
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def transformed(self) -> bool:
|
|
115
|
+
"""True when a transform was applied to the target."""
|
|
116
|
+
return self.proceeds and self.verdict.get("decision") == "transform"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Interceptor(Protocol):
|
|
120
|
+
async def intercept(self, context: Mapping[str, Any], /) -> Any: ...
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class Resolver(Protocol):
|
|
124
|
+
async def resolve(self, request: Any, /) -> Any: ...
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def context_identity(context: Mapping[str, Any]) -> str:
|
|
128
|
+
"""The Agent Hooks ``jcs-sha256`` identity: ``sha256:`` + the hash of the closed projection."""
|
|
129
|
+
point = context.get("interception_point")
|
|
130
|
+
if point not in _PER_POINT:
|
|
131
|
+
raise ValueError("no identity for a context without a known interception point")
|
|
132
|
+
projection: dict[str, Any] = {}
|
|
133
|
+
for name, sub in {**_CORE, **_PER_POINT[str(point)]}.items():
|
|
134
|
+
if name not in context:
|
|
135
|
+
continue
|
|
136
|
+
value = context[name]
|
|
137
|
+
projection[name] = {k: value[k] for k in sub if k in value} if sub and isinstance(value, Mapping) else value
|
|
138
|
+
return "sha256:" + sha256_hex(canonical(projection))
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def host_error(reason: str) -> dict[str, Any]:
|
|
142
|
+
return {"decision": "deny", "reason": reason}
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class _SequenceTaken(Exception):
|
|
146
|
+
"""The gateway holds another context at this sequence: a restored session moves past it."""
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class HookSession:
|
|
150
|
+
"""One agent session, bracketed by ``agent_startup`` and ``agent_shutdown``.
|
|
151
|
+
|
|
152
|
+
``async with HookSession(interceptor, agent_id=..., framework=..., tools=[...], resolver=...) as
|
|
153
|
+
hooks:`` then ``await hooks.pre_tool_call(call_id, name, args)`` and the other step methods,
|
|
154
|
+
each returning the ``HookOutcome`` the host enforces: call the tool with ``outcome.target`` (the
|
|
155
|
+
arguments, transformed or not) only when ``outcome.proceeds``, and pass those same arguments to
|
|
156
|
+
``post_tool_call``; use its ``target`` as the result, and ``output``'s ``target["content"]``
|
|
157
|
+
as the answer.
|
|
158
|
+
|
|
159
|
+
``delegation`` is for an agent reached as a delegate: the ``x-brutor-delegation-*`` headers of
|
|
160
|
+
the inbound request (``delegation_from_headers(request.headers)``). ``agent_startup`` then joins
|
|
161
|
+
the caller's run instead of opening one, and the agent's own gateway calls must send
|
|
162
|
+
``outbound_headers()`` (the run handle) and never the delegation headers.
|
|
163
|
+
"""
|
|
164
|
+
|
|
165
|
+
def __init__(
|
|
166
|
+
self,
|
|
167
|
+
interceptor: Interceptor,
|
|
168
|
+
*,
|
|
169
|
+
agent_id: str,
|
|
170
|
+
framework: str,
|
|
171
|
+
tools: Sequence[str] = (),
|
|
172
|
+
resolver: Resolver | None = None,
|
|
173
|
+
session_id: str | None = None,
|
|
174
|
+
agent_name: str | None = None,
|
|
175
|
+
agent_version: str | None = None,
|
|
176
|
+
turn: int | None = None,
|
|
177
|
+
delegation: Mapping[str, str] | None = None,
|
|
178
|
+
) -> None:
|
|
179
|
+
if not agent_id:
|
|
180
|
+
raise ValueError("agent_id must name the agent")
|
|
181
|
+
if not _FRAMEWORK.match(framework or ""):
|
|
182
|
+
raise ValueError("framework must match ^[a-z0-9_-]+$ (for example 'langgraph')")
|
|
183
|
+
self.interceptor = interceptor
|
|
184
|
+
self.resolver = resolver
|
|
185
|
+
self.session_id = session_id or f"s-{uuid.uuid4()}"
|
|
186
|
+
self.tools = list(tools)
|
|
187
|
+
self._agent: dict[str, Any] = {"id": agent_id, "framework": framework}
|
|
188
|
+
if agent_name:
|
|
189
|
+
self._agent["name"] = agent_name
|
|
190
|
+
if agent_version:
|
|
191
|
+
self._agent["version"] = agent_version
|
|
192
|
+
self._turn = turn
|
|
193
|
+
self._delegation = check_delegation(delegation) if delegation else None
|
|
194
|
+
self._sequence = 0
|
|
195
|
+
self._lock = asyncio.Lock()
|
|
196
|
+
self._open = False
|
|
197
|
+
self._restored = False
|
|
198
|
+
self._entered = False
|
|
199
|
+
self.startup_receipt: dict[str, Any] | None = None
|
|
200
|
+
|
|
201
|
+
# ------------------------------------------------------------------ restoring a session
|
|
202
|
+
|
|
203
|
+
def snapshot(self) -> dict[str, Any]:
|
|
204
|
+
"""What another process needs to continue this session: JSON, and it holds the run handle.
|
|
205
|
+
|
|
206
|
+
Keep it where the agent's own state is kept (a checkpoint), never in a log. The handle is
|
|
207
|
+
bound to the agent's principal: it is of no use to another credential.
|
|
208
|
+
"""
|
|
209
|
+
if not self._open:
|
|
210
|
+
raise RuntimeError("only an open session can be continued elsewhere")
|
|
211
|
+
snap: dict[str, Any] = {
|
|
212
|
+
"session_id": self.session_id,
|
|
213
|
+
"next_sequence": self._sequence,
|
|
214
|
+
"agent": dict(self._agent),
|
|
215
|
+
"run": self._run(),
|
|
216
|
+
}
|
|
217
|
+
if self._turn is not None:
|
|
218
|
+
snap["turn"] = self._turn
|
|
219
|
+
return snap
|
|
220
|
+
|
|
221
|
+
@classmethod
|
|
222
|
+
def restore(
|
|
223
|
+
cls,
|
|
224
|
+
interceptor: Interceptor,
|
|
225
|
+
snapshot: Mapping[str, Any],
|
|
226
|
+
*,
|
|
227
|
+
tools: Sequence[str] = (),
|
|
228
|
+
resolver: Resolver | None = None,
|
|
229
|
+
) -> HookSession:
|
|
230
|
+
"""The session a ``snapshot()`` describes, open, without a new ``agent_startup``.
|
|
231
|
+
|
|
232
|
+
A sequence the session used after the snapshot was taken is skipped when the gateway
|
|
233
|
+
reports it taken, so the continued session never reuses one.
|
|
234
|
+
"""
|
|
235
|
+
agent = snapshot.get("agent")
|
|
236
|
+
run = snapshot.get("run")
|
|
237
|
+
next_sequence = snapshot.get("next_sequence")
|
|
238
|
+
session_id = snapshot.get("session_id")
|
|
239
|
+
if (
|
|
240
|
+
not isinstance(agent, Mapping)
|
|
241
|
+
or not isinstance(run, str)
|
|
242
|
+
or not isinstance(session_id, str)
|
|
243
|
+
or not isinstance(next_sequence, int)
|
|
244
|
+
or isinstance(next_sequence, bool)
|
|
245
|
+
or next_sequence < 1
|
|
246
|
+
):
|
|
247
|
+
raise ValueError("not a session snapshot")
|
|
248
|
+
turn = snapshot.get("turn")
|
|
249
|
+
session = cls(
|
|
250
|
+
interceptor,
|
|
251
|
+
agent_id=str(agent.get("id") or ""),
|
|
252
|
+
framework=str(agent.get("framework") or ""),
|
|
253
|
+
tools=tools,
|
|
254
|
+
resolver=resolver,
|
|
255
|
+
session_id=session_id,
|
|
256
|
+
agent_name=agent.get("name"),
|
|
257
|
+
agent_version=agent.get("version"),
|
|
258
|
+
turn=turn if isinstance(turn, int) and not isinstance(turn, bool) else None,
|
|
259
|
+
)
|
|
260
|
+
restore_run = getattr(interceptor, "_restore_run", None)
|
|
261
|
+
if callable(restore_run):
|
|
262
|
+
restore_run(session_id, run)
|
|
263
|
+
session._sequence = next_sequence
|
|
264
|
+
session._open = True
|
|
265
|
+
session._restored = True
|
|
266
|
+
return session
|
|
267
|
+
|
|
268
|
+
@property
|
|
269
|
+
def is_open(self) -> bool:
|
|
270
|
+
return self._open
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def next_sequence(self) -> int:
|
|
274
|
+
return self._sequence
|
|
275
|
+
|
|
276
|
+
# ------------------------------------------------------------------ the run, for the agent's gateway calls
|
|
277
|
+
|
|
278
|
+
@property
|
|
279
|
+
def joined(self) -> dict[str, Any] | None:
|
|
280
|
+
"""For a delegate's session: the caller's run it joined (``root_task_id``, ``depth``, ...)."""
|
|
281
|
+
joined = (self.startup_receipt or {}).get("joined")
|
|
282
|
+
return dict(joined) if isinstance(joined, Mapping) else None
|
|
283
|
+
|
|
284
|
+
def _run(self) -> str:
|
|
285
|
+
run_of = getattr(self.interceptor, "run", None)
|
|
286
|
+
run = run_of(self.session_id) if callable(run_of) else None
|
|
287
|
+
if not isinstance(run, str) or not run:
|
|
288
|
+
raise RuntimeError("the session has no run handle: it is not open, or its interceptor keeps none")
|
|
289
|
+
return run
|
|
290
|
+
|
|
291
|
+
def run_headers(self) -> dict[str, str]:
|
|
292
|
+
"""``X-Brutor-Run-Id``: the header the agent's own gateway calls send, so they are steps of this run."""
|
|
293
|
+
return {RUN_HEADER: self._run()}
|
|
294
|
+
|
|
295
|
+
def outbound_headers(self, headers: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
296
|
+
"""``headers`` for a gateway call of this agent: the run handle in, every delegation header out.
|
|
297
|
+
|
|
298
|
+
A delegate that joined its caller's run must not forward the delegation it received: a call
|
|
299
|
+
that presents the chain is resolved by the chain, not by the hooked run, and is refused when
|
|
300
|
+
the agent's AI System requires runtime hooks.
|
|
301
|
+
"""
|
|
302
|
+
return {**without_delegation(headers), **self.run_headers()}
|
|
303
|
+
|
|
304
|
+
# ------------------------------------------------------------------ the session
|
|
305
|
+
|
|
306
|
+
async def __aenter__(self) -> HookSession:
|
|
307
|
+
if self._restored and self._open and not self._entered:
|
|
308
|
+
self._entered = True # a restored session continues: no new agent_startup
|
|
309
|
+
return self
|
|
310
|
+
if self._open or self._entered:
|
|
311
|
+
raise RuntimeError("the session is already open")
|
|
312
|
+
self._entered = True
|
|
313
|
+
init = {"tools_registered": list(self.tools)}
|
|
314
|
+
payload: dict[str, Any] = {"agent_init": init}
|
|
315
|
+
if self._delegation:
|
|
316
|
+
payload["extensions"] = {"brutor": {"delegation": dict(self._delegation)}}
|
|
317
|
+
started = await self._emit("agent_startup", payload, init)
|
|
318
|
+
receipt_of = getattr(self.interceptor, "receipt", None)
|
|
319
|
+
receipt = receipt_of(self.session_id) if callable(receipt_of) else None
|
|
320
|
+
self.startup_receipt = dict(receipt) if isinstance(receipt, Mapping) else None
|
|
321
|
+
if not started.proceeds:
|
|
322
|
+
# The session is blocked; agent_shutdown is still emitted (not enforced) to close it.
|
|
323
|
+
summary = {"reason": "error"}
|
|
324
|
+
await self._emit("agent_shutdown", {"summary": summary}, summary, enforce=False)
|
|
325
|
+
raise errors.HookDenied(started.verdict)
|
|
326
|
+
self._open = True
|
|
327
|
+
return self
|
|
328
|
+
|
|
329
|
+
async def __aexit__(
|
|
330
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
331
|
+
) -> None:
|
|
332
|
+
if not self._open:
|
|
333
|
+
return
|
|
334
|
+
if exc_type is None:
|
|
335
|
+
reason = "completed"
|
|
336
|
+
elif issubclass(exc_type, asyncio.CancelledError):
|
|
337
|
+
reason = "cancelled"
|
|
338
|
+
else:
|
|
339
|
+
reason = "error"
|
|
340
|
+
summary = {"reason": reason}
|
|
341
|
+
try:
|
|
342
|
+
await self._emit("agent_shutdown", {"summary": summary}, summary, enforce=False)
|
|
343
|
+
finally:
|
|
344
|
+
self._open = False
|
|
345
|
+
|
|
346
|
+
# ------------------------------------------------------------------ the steps
|
|
347
|
+
|
|
348
|
+
async def input(self, content: Any, role: str = "user") -> HookOutcome:
|
|
349
|
+
payload = {"content": content, "role": role}
|
|
350
|
+
return await self._step("input", {"input": payload}, payload)
|
|
351
|
+
|
|
352
|
+
async def pre_model_call(self, model: str, messages: Sequence[Mapping[str, Any]], **extra: Any) -> HookOutcome:
|
|
353
|
+
msgs = [dict(m) for m in messages]
|
|
354
|
+
return await self._step("pre_model_call", {"model": {"id": model}, "messages": msgs, **extra}, msgs)
|
|
355
|
+
|
|
356
|
+
async def post_model_call(
|
|
357
|
+
self,
|
|
358
|
+
model: str,
|
|
359
|
+
*,
|
|
360
|
+
content: Any,
|
|
361
|
+
tool_calls: Sequence[Mapping[str, Any]] = (),
|
|
362
|
+
finish_reason: str = "stop",
|
|
363
|
+
**extra: Any,
|
|
364
|
+
) -> HookOutcome:
|
|
365
|
+
response = {"content": content, "tool_calls": [dict(t) for t in tool_calls], "finish_reason": finish_reason}
|
|
366
|
+
return await self._step("post_model_call", {"model": {"id": model}, "response": response, **extra}, response)
|
|
367
|
+
|
|
368
|
+
async def pre_tool_call(self, call_id: str, name: str, args: Mapping[str, Any]) -> HookOutcome:
|
|
369
|
+
call = {"id": call_id, "name": name, "args": dict(args)}
|
|
370
|
+
return await self._step("pre_tool_call", {"tool_call": call}, call["args"])
|
|
371
|
+
|
|
372
|
+
async def post_tool_call(
|
|
373
|
+
self,
|
|
374
|
+
call_id: str,
|
|
375
|
+
name: str,
|
|
376
|
+
args: Mapping[str, Any],
|
|
377
|
+
value: Any,
|
|
378
|
+
*,
|
|
379
|
+
is_error: bool = False,
|
|
380
|
+
duration_ms: float | None = None,
|
|
381
|
+
) -> HookOutcome:
|
|
382
|
+
"""``post_tool_call``: ``args`` are the arguments the tool ran with (``pre_tool_call``'s target)."""
|
|
383
|
+
result: dict[str, Any] = {"value": value, "is_error": bool(is_error)}
|
|
384
|
+
if duration_ms is not None:
|
|
385
|
+
result["duration_ms"] = duration_ms
|
|
386
|
+
call = {"id": call_id, "name": name, "args": dict(args)}
|
|
387
|
+
return await self._step("post_tool_call", {"tool_call": call, "tool_result": result}, value)
|
|
388
|
+
|
|
389
|
+
async def output(self, content: Any) -> HookOutcome:
|
|
390
|
+
payload = {"content": content}
|
|
391
|
+
return await self._step("output", {"output": payload}, payload)
|
|
392
|
+
|
|
393
|
+
# ------------------------------------------------------------------ for hosts that resolve holds later
|
|
394
|
+
|
|
395
|
+
async def _pre_tool_call_held(
|
|
396
|
+
self, call_id: str, name: str, args: Mapping[str, Any]
|
|
397
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
398
|
+
"""(verdict, context) of a tool call, a liftable deny left unresolved for the host to handle."""
|
|
399
|
+
if not self._open:
|
|
400
|
+
raise RuntimeError("use the session inside `async with HookSession(...)`")
|
|
401
|
+
call = {"id": call_id, "name": name, "args": dict(args)}
|
|
402
|
+
return await self._decide("pre_tool_call", {"tool_call": call}, call["args"], resolve=False)
|
|
403
|
+
|
|
404
|
+
def _context(
|
|
405
|
+
self,
|
|
406
|
+
point: str,
|
|
407
|
+
payload: Mapping[str, Any],
|
|
408
|
+
target: Any,
|
|
409
|
+
sequence: int,
|
|
410
|
+
timestamp: str | None = None,
|
|
411
|
+
) -> dict[str, Any]:
|
|
412
|
+
return {
|
|
413
|
+
"spec": SPEC_VERSION,
|
|
414
|
+
"interception_point": point,
|
|
415
|
+
"timestamp": timestamp or datetime.now(UTC).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
|
416
|
+
"sequence": sequence,
|
|
417
|
+
"agent": dict(self._agent),
|
|
418
|
+
"session": {"id": self.session_id} | ({"turn": self._turn} if self._turn is not None else {}),
|
|
419
|
+
**copy.deepcopy(dict(payload)),
|
|
420
|
+
"target": copy.deepcopy(target),
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
def _hold_request(self, context: Mapping[str, Any], verdict: Mapping[str, Any]) -> dict[str, Any]:
|
|
424
|
+
"""The approval request of a liftable deny, as the Agent Hooks approval seam defines it."""
|
|
425
|
+
return {
|
|
426
|
+
"context_identity": context_identity(context),
|
|
427
|
+
"interception_point": context["interception_point"],
|
|
428
|
+
"verdict": copy.deepcopy(dict(verdict)),
|
|
429
|
+
"context": copy.deepcopy(dict(context)),
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
# ------------------------------------------------------------------ the host's rules
|
|
433
|
+
|
|
434
|
+
async def _step(self, point: str, payload: Mapping[str, Any], target: Any) -> HookOutcome:
|
|
435
|
+
if not self._open:
|
|
436
|
+
raise RuntimeError("use the session inside `async with HookSession(...)`")
|
|
437
|
+
return await self._emit(point, payload, target)
|
|
438
|
+
|
|
439
|
+
async def _emit(self, point: str, payload: Mapping[str, Any], target: Any, *, enforce: bool = True) -> HookOutcome:
|
|
440
|
+
verdict, _ = await self._decide(point, payload, target, resolve=enforce)
|
|
441
|
+
if not enforce:
|
|
442
|
+
return HookOutcome(verdict, False)
|
|
443
|
+
return self._outcome(point, verdict, target)
|
|
444
|
+
|
|
445
|
+
def _outcome(self, point: str, verdict: dict[str, Any], target: Any) -> HookOutcome:
|
|
446
|
+
"""The verdict enforced at ``point`` on ``target``: a transform is applied here, or becomes a deny."""
|
|
447
|
+
decision = verdict.get("decision")
|
|
448
|
+
if decision == "allow":
|
|
449
|
+
return HookOutcome(verdict, True, copy.deepcopy(target))
|
|
450
|
+
if decision != "transform":
|
|
451
|
+
return HookOutcome(verdict, False)
|
|
452
|
+
transform = verdict.get("transform") or {}
|
|
453
|
+
try:
|
|
454
|
+
if not transform_permitted(point):
|
|
455
|
+
raise TransformRefused(TRANSFORM_TARGET_FORBIDDEN)
|
|
456
|
+
applied = apply_transform(target, transform.get("path"), transform.get("value"))
|
|
457
|
+
except TransformRefused as e:
|
|
458
|
+
logger.debug("the transform at %s does not apply (%s): deny", point, e.reason)
|
|
459
|
+
return HookOutcome(host_error(e.reason), False)
|
|
460
|
+
try:
|
|
461
|
+
canonical(applied) # I-JSON, as the context it stands for must be
|
|
462
|
+
except (TypeError, ValueError):
|
|
463
|
+
return HookOutcome(host_error(CONTEXT_INVALID), False)
|
|
464
|
+
if not target_fits(point, applied):
|
|
465
|
+
logger.debug("the transformed target at %s is not what the point's context requires: deny", point)
|
|
466
|
+
return HookOutcome(host_error(CONTEXT_INVALID), False)
|
|
467
|
+
return HookOutcome(verdict, True, applied)
|
|
468
|
+
|
|
469
|
+
async def _decide(
|
|
470
|
+
self, point: str, payload: Mapping[str, Any], target: Any, *, resolve: bool
|
|
471
|
+
) -> tuple[dict[str, Any], dict[str, Any]]:
|
|
472
|
+
probes = _SEQUENCE_PROBES if self._restored else 0
|
|
473
|
+
verdict: dict[str, Any] | None = None
|
|
474
|
+
while verdict is None:
|
|
475
|
+
async with self._lock:
|
|
476
|
+
sequence = self._sequence
|
|
477
|
+
self._sequence += 1
|
|
478
|
+
context = self._context(point, payload, target, sequence)
|
|
479
|
+
try:
|
|
480
|
+
verdict = await self._ask(context, probing=probes > 0)
|
|
481
|
+
except _SequenceTaken:
|
|
482
|
+
probes -= 1
|
|
483
|
+
if resolve and is_liftable(verdict) and point != "agent_shutdown":
|
|
484
|
+
verdict = await self._resolve(context, verdict)
|
|
485
|
+
return verdict, context
|
|
486
|
+
|
|
487
|
+
async def _ask(self, context: Mapping[str, Any], *, probing: bool = False) -> dict[str, Any]:
|
|
488
|
+
point = context["interception_point"]
|
|
489
|
+
try:
|
|
490
|
+
raw = await self.interceptor.intercept(copy.deepcopy(dict(context)))
|
|
491
|
+
except errors.DecisionUnavailable as e:
|
|
492
|
+
if probing and e.code == errors.SEQUENCE_CONFLICT:
|
|
493
|
+
raise _SequenceTaken from None
|
|
494
|
+
logger.debug("no decision at %s (%s): deny", point, e.code)
|
|
495
|
+
if e.code in _TRANSFORM_CODES:
|
|
496
|
+
return host_error(_TRANSFORM_CODES[e.code])
|
|
497
|
+
if e.code == errors.TIMEOUT:
|
|
498
|
+
return host_error(INTERCEPTOR_TIMEOUT)
|
|
499
|
+
if e.code == errors.INVALID_CONTEXT:
|
|
500
|
+
return host_error(CONTEXT_INVALID)
|
|
501
|
+
return host_error(INTERCEPTOR_FAILED)
|
|
502
|
+
except TimeoutError:
|
|
503
|
+
return host_error(INTERCEPTOR_TIMEOUT)
|
|
504
|
+
except Exception as e:
|
|
505
|
+
logger.debug("the interceptor raised %s: deny", type(e).__name__)
|
|
506
|
+
return host_error(INTERCEPTOR_FAILED)
|
|
507
|
+
try:
|
|
508
|
+
return check_verdict(_wire(raw))
|
|
509
|
+
except InvalidTransform as e:
|
|
510
|
+
return host_error(e.reason)
|
|
511
|
+
except InvalidResponse:
|
|
512
|
+
return host_error(VERDICT_INVALID)
|
|
513
|
+
|
|
514
|
+
async def _resolve(self, context: Mapping[str, Any], verdict: dict[str, Any]) -> dict[str, Any]:
|
|
515
|
+
if self.resolver is None:
|
|
516
|
+
return verdict
|
|
517
|
+
try:
|
|
518
|
+
request = self._hold_request(context, verdict)
|
|
519
|
+
except (TypeError, ValueError):
|
|
520
|
+
return host_error(CONTEXT_INVALID)
|
|
521
|
+
try:
|
|
522
|
+
resolution = await self.resolver.resolve(request)
|
|
523
|
+
except Exception as e:
|
|
524
|
+
logger.debug("the approval resolver raised %s: deny", type(e).__name__)
|
|
525
|
+
return host_error(APPROVAL_RESOLVER_FAILED)
|
|
526
|
+
return self._settled(request["context_identity"], resolution)
|
|
527
|
+
|
|
528
|
+
def _settled(self, identity: str, resolution: Any) -> dict[str, Any]:
|
|
529
|
+
"""The verdict a resolution gives, held to the approval seam's rules (else a deny)."""
|
|
530
|
+
try:
|
|
531
|
+
resolution = _wire(resolution)
|
|
532
|
+
outcome = _wire(_field(resolution, "outcome"))
|
|
533
|
+
echoed = _field(resolution, "context_identity")
|
|
534
|
+
lifted = _field(resolution, "verdict")
|
|
535
|
+
except Exception as e:
|
|
536
|
+
logger.debug("the approval resolution could not be read (%s): deny", type(e).__name__)
|
|
537
|
+
return host_error(APPROVAL_RESOLVER_FAILED)
|
|
538
|
+
if echoed != identity:
|
|
539
|
+
return host_error(APPROVAL_IDENTITY_MISMATCH)
|
|
540
|
+
outcome = getattr(outcome, "value", outcome)
|
|
541
|
+
if outcome not in ("approve", "reject") or lifted is None:
|
|
542
|
+
return host_error(APPROVAL_UNRESOLVED)
|
|
543
|
+
try:
|
|
544
|
+
checked = check_verdict(_wire(lifted))
|
|
545
|
+
except InvalidTransform as e:
|
|
546
|
+
return host_error(e.reason)
|
|
547
|
+
except InvalidResponse:
|
|
548
|
+
return host_error(VERDICT_INVALID)
|
|
549
|
+
# approve carries a permit (an allow, or a transform applied like an interceptor's), reject a deny
|
|
550
|
+
if (outcome == "approve") != permits(checked):
|
|
551
|
+
return host_error(VERDICT_INVALID)
|
|
552
|
+
return checked
|
|
553
|
+
|
|
554
|
+
def __repr__(self) -> str:
|
|
555
|
+
return f"HookSession(agent_id={self._agent['id']!r}, framework={self._agent['framework']!r})"
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _wire(value: Any) -> Any:
|
|
559
|
+
to_wire = getattr(value, "to_wire", None)
|
|
560
|
+
return to_wire() if callable(to_wire) else value
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _field(value: Any, name: str) -> Any:
|
|
564
|
+
if isinstance(value, Mapping):
|
|
565
|
+
return value.get(name)
|
|
566
|
+
return getattr(value, name, None)
|