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,623 @@
1
+ # Copyright 2026 Brutor AI Ltd. All rights reserved.
2
+ # SPDX-License-Identifier: LicenseRef-Brutor-Enterprise-SDK
3
+
4
+ """LangGraph (Python): a governed ``ToolNode`` and a governed invoke.
5
+
6
+ from brutor.runtime_hooks.adapters.langgraph import BrutorState, brutor_tool_node, governed_invoke
7
+
8
+ class State(MessagesState, BrutorState): ...
9
+
10
+ tools_node = brutor_tool_node(tools, interceptor, on_approval="interrupt") # in place of ToolNode(tools)
11
+ result = await governed_invoke(graph, inputs, config, interceptor, agent_id="loan-screening")
12
+
13
+ ``brutor_tool_node`` is a ``ToolNode`` whose per-call wrapper sends ``pre_tool_call`` before each
14
+ tool call and ``post_tool_call`` after it. A deny is a ``ToolMessage`` with ``status="error"`` and
15
+ the gateway's sentence (the tool does not run); a denied result is replaced. A ``transform``
16
+ (``TRANSFORMS``) is applied: the tool is called with the transformed arguments (and
17
+ ``post_tool_call`` carries them), and a transformed result replaces the tool's ``ToolMessage``
18
+ content. A hold either
19
+ interrupts the graph (``on_approval="interrupt"``, the default): the interrupt's value is
20
+ ``{"brutor_approval": {id, poll, expires_at, tool_call_id, resume}}``, and when the graph is
21
+ resumed (``Command(resume=...)``, any value) the node looks at the hold: approved, the same context
22
+ is evaluated again with the approval token; still pending, it interrupts again. Or it waits in the
23
+ node (``on_approval="block"``).
24
+
25
+ ``governed_invoke`` (or ``GovernedThread``, for ``input`` and ``output`` too) is the Agent Hooks
26
+ host: ``agent_startup`` before the first invoke of a thread, ``agent_shutdown`` when the graph
27
+ reaches its end (not at an interrupt). With a checkpointer the session survives checkpoints: the
28
+ ``brutor`` channel of ``BrutorState`` holds the session (its id, next sequence and run handle) and
29
+ a hold's interrupt holds what its re-evaluation needs, so a graph resumed in another process
30
+ continues the same session and the approval lifts the same decision. That state holds the run
31
+ handle: keep checkpoints as you keep the agent's credentials' state. The handle is bound to the
32
+ agent's principal and gives another credential nothing.
33
+
34
+ ``COVERS`` lists what the adapter sends itself; ``input`` and ``output`` are sent when the
35
+ application calls ``GovernedThread.input`` / ``.output``, which return the ``HookOutcome``: hand the
36
+ graph (or the caller) ``outcome.target["content"]``, the transformed text after a transform. Model
37
+ calls are not hooks of a graph: point the model client at the gateway to govern them. A plain
38
+ ``ToolNode`` in the graph runs tools the adapter cannot see: ``governed_invoke`` refuses the graph
39
+ (``UncoveredTools``) unless those tools are named in ``allow_uncovered``.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import copy
45
+ import json
46
+ from asyncio import CancelledError as _Cancelled
47
+ from collections import OrderedDict
48
+ from collections.abc import Callable, Mapping, Sequence
49
+ from dataclasses import dataclass
50
+ from typing import Annotated, Any
51
+
52
+ from langchain_core.messages import ToolMessage
53
+ from langgraph.prebuilt import ToolNode
54
+ from langgraph.prebuilt.tool_node import ToolCallRequest
55
+ from langgraph.pregel import Pregel
56
+ from langgraph.types import Command, interrupt
57
+ from typing_extensions import TypedDict # the one LangGraph states use, so the two combine
58
+
59
+ from brutor.runtime_hooks._verdict import is_liftable
60
+ from brutor.runtime_hooks.errors import HookDenied, UncoveredTools
61
+ from brutor.runtime_hooks.interceptor import BrutorInterceptor
62
+ from brutor.runtime_hooks.resolver import BrutorApprovalResolver
63
+ from brutor.runtime_hooks.session import HookOutcome, HookSession, host_error
64
+
65
+ COVERS = ("agent_startup", "pre_tool_call", "post_tool_call", "agent_shutdown")
66
+ HELPERS = ("input", "output")
67
+ NOT_COVERED = ("pre_model_call", "post_model_call")
68
+ FRAMEWORK = "langgraph"
69
+ # What becomes of a transform at each point the adapter sends.
70
+ TRANSFORMS = {"pre_tool_call": "applied", "post_tool_call": "applied"}
71
+ ON_APPROVAL = ("interrupt", "block")
72
+ CHANNEL = "brutor"
73
+ UNCOVERED_WHY = "a ToolNode that is not a Brutor tool node runs its tools without hooks"
74
+ _THREADS_KEPT = 4096
75
+
76
+
77
+ def deny_message(verdict: Mapping[str, Any]) -> str:
78
+ """The text the model is given for a deny: the gateway's sentence, else its reason."""
79
+ message = verdict.get("message")
80
+ if isinstance(message, str) and message:
81
+ return message
82
+ reason = str(verdict.get("reason") or "denied")
83
+ return reason if reason.startswith("host_error:") else f"Denied by Brutor: {reason}"
84
+
85
+
86
+ def merge_session(old: dict[str, Any] | None, new: dict[str, Any] | None) -> dict[str, Any] | None:
87
+ """The ``brutor`` channel's reducer: the latest state of the thread's session.
88
+
89
+ A new session replaces the old one; within a session the state with the higher next sequence
90
+ is the later one (parallel tool calls write in any order).
91
+ """
92
+ if new is None:
93
+ return old
94
+ if old is None or old.get("session_id") != new.get("session_id"):
95
+ return new
96
+ return new if int(new.get("next_sequence", 0)) >= int(old.get("next_sequence", 0)) else old
97
+
98
+
99
+ class BrutorState(TypedDict, total=False):
100
+ """Add to the graph's state (``class State(MessagesState, BrutorState)``) to checkpoint the session."""
101
+
102
+ brutor: Annotated[dict[str, Any] | None, merge_session]
103
+
104
+
105
+ # ------------------------------------------------------------------ live sessions, by thread
106
+
107
+
108
+ @dataclass
109
+ class _Hold:
110
+ """A hold a tool call is waiting on: what its approval needs, in this process or restored."""
111
+
112
+ call_id: str
113
+ approval: dict[str, Any]
114
+ sequence: int
115
+ timestamp: str
116
+ run: str
117
+ context: dict[str, Any] | None = None
118
+
119
+ def payload(self, session_id: str) -> dict[str, Any]:
120
+ return {
121
+ "brutor_approval": {
122
+ **{k: self.approval[k] for k in ("id", "poll", "expires_at") if k in self.approval},
123
+ "tool_call_id": self.call_id,
124
+ "resume": {
125
+ "session_id": session_id,
126
+ "sequence": self.sequence,
127
+ "timestamp": self.timestamp,
128
+ "run": self.run,
129
+ },
130
+ }
131
+ }
132
+
133
+
134
+ class _Live:
135
+ """A thread's open session in this process, and the holds its tool calls wait on."""
136
+
137
+ def __init__(self, session: HookSession) -> None:
138
+ self.session = session
139
+ self.holds: dict[str, _Hold] = {}
140
+
141
+
142
+ _LIVE: OrderedDict[tuple[int, str], _Live] = OrderedDict()
143
+
144
+
145
+ def _remember(interceptor: Any, live: _Live) -> None:
146
+ key = (id(interceptor), live.session.session_id)
147
+ _LIVE[key] = live
148
+ _LIVE.move_to_end(key)
149
+ while len(_LIVE) > _THREADS_KEPT:
150
+ _LIVE.popitem(last=False)
151
+
152
+
153
+ def _forget(interceptor: Any, session_id: str) -> None:
154
+ _LIVE.pop((id(interceptor), session_id), None)
155
+
156
+
157
+ # ------------------------------------------------------------------ the tool node
158
+
159
+
160
+ @dataclass(frozen=True)
161
+ class _NodeSettings:
162
+ interceptor: BrutorInterceptor
163
+ on_approval: str
164
+ resolver: Any
165
+
166
+
167
+ def brutor_tool_node(
168
+ tools: Sequence[Any],
169
+ interceptor: BrutorInterceptor,
170
+ *,
171
+ on_approval: str = "interrupt",
172
+ resolver: Any = None,
173
+ **tool_node_kwargs: Any,
174
+ ) -> ToolNode:
175
+ """A ``ToolNode`` over ``tools`` whose every call Brutor judges (use it in place of ``ToolNode``).
176
+
177
+ ``on_approval`` is ``"interrupt"`` (a hold interrupts the graph) or ``"block"`` (the node waits
178
+ for the approver). ``resolver`` defaults to a ``BrutorApprovalResolver``. Other keyword
179
+ arguments are ``ToolNode``'s. Run the graph with ``governed_invoke`` (or ``GovernedThread``):
180
+ the node finds its session there and refuses every call without one.
181
+ """
182
+ if on_approval not in ON_APPROVAL:
183
+ raise ValueError("on_approval must be 'interrupt' or 'block'")
184
+ for given in ("wrap_tool_call", "awrap_tool_call"):
185
+ if given in tool_node_kwargs:
186
+ raise ValueError(f"{given} is the adapter's: compose your wrapper inside a tool instead")
187
+ settings = _NodeSettings(
188
+ interceptor, on_approval, resolver if resolver is not None else BrutorApprovalResolver(interceptor)
189
+ )
190
+ box: dict[str, ToolNode] = {}
191
+
192
+ async def awrap(request: ToolCallRequest, execute: Callable[[ToolCallRequest], Any]) -> Any:
193
+ return await _govern_call(settings, box["node"], request, execute)
194
+
195
+ def refuse_sync(request: ToolCallRequest, _execute: Callable[[ToolCallRequest], Any]) -> Any:
196
+ # The decisions are asynchronous: a graph run synchronously never runs a governed tool.
197
+ call = request.tool_call
198
+ return ToolMessage(
199
+ content="host_error:interceptor_failed: run the graph with governed_invoke (asynchronously)",
200
+ name=call["name"],
201
+ tool_call_id=call["id"],
202
+ status="error",
203
+ )
204
+
205
+ node = ToolNode(tools, awrap_tool_call=awrap, wrap_tool_call=refuse_sync, **tool_node_kwargs)
206
+ # Marks the node as governed. ToolNode is untyped when langgraph is not installed
207
+ # (the release build), so the ignore is also allowed to be unused.
208
+ node._brutor = settings # type: ignore[attr-defined,unused-ignore]
209
+ box["node"] = node
210
+ return node
211
+
212
+
213
+ def _live_for(settings: _NodeSettings, request: ToolCallRequest) -> _Live:
214
+ config = getattr(request.runtime, "config", None) or {}
215
+ ours = (config.get("configurable") or {}).get(CHANNEL) if isinstance(config, Mapping) else None
216
+ session_id = ours.get("session_id") if isinstance(ours, Mapping) else None
217
+ live = _LIVE.get((id(settings.interceptor), session_id)) if isinstance(session_id, str) else None
218
+ if live is None or not live.session.is_open:
219
+ raise HookDenied(host_error("host_error:context_invalid") | {"message": "run the graph with governed_invoke"})
220
+ return live
221
+
222
+
223
+ async def _govern_call(
224
+ settings: _NodeSettings, node: ToolNode, request: ToolCallRequest, execute: Callable[[ToolCallRequest], Any]
225
+ ) -> Any:
226
+ call = request.tool_call
227
+ call_id, name = str(call["id"]), str(call["name"])
228
+ args = dict(call.get("args") or {})
229
+ try:
230
+ live = _live_for(settings, request)
231
+ except HookDenied as e:
232
+ return _denied(e.verdict, call_id, name)
233
+ session = live.session
234
+ if settings.on_approval == "block":
235
+ pre = await session.pre_tool_call(call_id, name, args)
236
+ else:
237
+ pre = session._outcome("pre_tool_call", await _judge_or_interrupt(settings, live, call_id, name, args), args)
238
+ if not pre.proceeds:
239
+ return _with_session(_denied(pre.verdict, call_id, name), request, node, session)
240
+ if pre.transformed:
241
+ # The tool runs with the arguments as transformed, and post_tool_call carries those.
242
+ args = pre.target
243
+ request = request.override(tool_call={**call, "args": copy.deepcopy(args)})
244
+ result = await execute(request)
245
+ message = _tool_message(result, call_id, node)
246
+ value = _json_value(message.content) if message is not None else None
247
+ is_error = message is not None and message.status == "error"
248
+ post = await session.post_tool_call(call_id, name, args, value, is_error=is_error)
249
+ if not post.proceeds:
250
+ result = _withheld(result, call_id, name, post.verdict, node)
251
+ elif post.transformed:
252
+ result = _replaced(result, call_id, node, post)
253
+ return _with_session(result, request, node, session)
254
+
255
+
256
+ async def _judge_or_interrupt(
257
+ settings: _NodeSettings, live: _Live, call_id: str, name: str, args: dict[str, Any]
258
+ ) -> dict[str, Any]:
259
+ session = live.session
260
+ hold = live.holds.get(call_id)
261
+ if hold is None:
262
+ verdict, context = await session._pre_tool_call_held(call_id, name, args)
263
+ if not is_liftable(verdict):
264
+ return verdict
265
+ run = settings.interceptor.run(session.session_id)
266
+ if run is None: # pragma: no cover - a hold always comes with the session's run
267
+ return host_error("host_error:context_invalid")
268
+ hold = _Hold(
269
+ call_id, dict(verdict["approval"]), int(context["sequence"]), str(context["timestamp"]), run, context
270
+ )
271
+ live.holds[call_id] = hold
272
+ if hold.context is None:
273
+ # Restored from a checkpoint in another process: rebuild the very context that was held.
274
+ call = {"id": call_id, "name": name, "args": args}
275
+ hold.context = session._context("pre_tool_call", {"tool_call": call}, args, hold.sequence, hold.timestamp)
276
+ await settings.interceptor._rehold(hold.context, hold.run)
277
+ held_verdict = {"decision": "deny", "reason": "approval_required", "approval": dict(hold.approval)}
278
+ request = session._hold_request(hold.context, held_verdict)
279
+ while True:
280
+ interrupt(hold.payload(session.session_id)) # returns once the graph is resumed
281
+ resolution = await settings.resolver.check(request)
282
+ if resolution is not None:
283
+ live.holds.pop(call_id, None)
284
+ return session._settled(request["context_identity"], resolution)
285
+
286
+
287
+ def _denied(verdict: Mapping[str, Any], call_id: str, name: str) -> ToolMessage:
288
+ return ToolMessage(content=deny_message(verdict), name=name, tool_call_id=call_id, status="error")
289
+
290
+
291
+ def _tool_message(result: Any, call_id: str, node: ToolNode) -> ToolMessage | None:
292
+ if isinstance(result, ToolMessage):
293
+ return result
294
+ if isinstance(result, Command) and isinstance(result.update, dict):
295
+ for message in result.update.get(node._messages_key, []):
296
+ if isinstance(message, ToolMessage) and message.tool_call_id == call_id:
297
+ return message
298
+ return None
299
+
300
+
301
+ def _withheld(result: Any, call_id: str, name: str, verdict: Mapping[str, Any], node: ToolNode) -> Any:
302
+ replacement = ToolMessage(
303
+ content=f"Brutor withheld this tool result: {deny_message(verdict)}",
304
+ name=name,
305
+ tool_call_id=call_id,
306
+ status="error",
307
+ )
308
+ return _swap(result, call_id, node, replacement)
309
+
310
+
311
+ def _content(value: Any) -> str | list[str | dict[str, Any]]:
312
+ """A transformed result as a ToolMessage's content: text, content blocks, else its JSON."""
313
+ if isinstance(value, str):
314
+ return value
315
+ if isinstance(value, list) and all(isinstance(v, (str, dict)) for v in value):
316
+ return value
317
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
318
+
319
+
320
+ def _replaced(result: Any, call_id: str, node: ToolNode, outcome: HookOutcome) -> Any:
321
+ """The tool's answer with its ToolMessage's content replaced by the transformed result."""
322
+ message = _tool_message(result, call_id, node)
323
+ if message is None: # pragma: no cover - a value was only judged when there was a message
324
+ return result
325
+ return _swap(result, call_id, node, message.model_copy(update={"content": _content(outcome.target)}))
326
+
327
+
328
+ def _swap(result: Any, call_id: str, node: ToolNode, replacement: ToolMessage) -> Any:
329
+ if isinstance(result, Command) and isinstance(result.update, dict):
330
+ update = dict(result.update)
331
+ update[node._messages_key] = [
332
+ replacement if isinstance(m, ToolMessage) and m.tool_call_id == call_id else m
333
+ for m in update.get(node._messages_key, [])
334
+ ]
335
+ return Command(graph=result.graph, update=update, resume=result.resume, goto=result.goto)
336
+ return replacement
337
+
338
+
339
+ def _with_session(result: Any, request: ToolCallRequest, node: ToolNode, session: HookSession) -> Any:
340
+ """The tool's answer, writing the session's state to the ``brutor`` channel when the graph has one."""
341
+ state = request.state
342
+ if not isinstance(state, Mapping) or CHANNEL not in state or not session.is_open:
343
+ return result
344
+ snapshot = session.snapshot()
345
+ if isinstance(result, ToolMessage):
346
+ return Command(update={node._messages_key: [result], CHANNEL: snapshot})
347
+ if isinstance(result, Command) and isinstance(result.update, dict) and result.graph is None:
348
+ return Command(update={**result.update, CHANNEL: snapshot}, resume=result.resume, goto=result.goto)
349
+ return result
350
+
351
+
352
+ def _json_value(value: Any) -> Any:
353
+ try:
354
+ return json.loads(json.dumps(value, ensure_ascii=False, allow_nan=False, default=str))
355
+ except (TypeError, ValueError):
356
+ return str(value)
357
+
358
+
359
+ # ------------------------------------------------------------------ the host
360
+
361
+
362
+ def _tool_nodes(graph: Any, seen: set[int] | None = None) -> list[ToolNode]:
363
+ seen = seen if seen is not None else set()
364
+ if id(graph) in seen:
365
+ return []
366
+ seen.add(id(graph))
367
+ out: list[ToolNode] = []
368
+ for node in getattr(graph, "nodes", {}).values():
369
+ bound = getattr(node, "bound", node)
370
+ if isinstance(bound, ToolNode):
371
+ out.append(bound)
372
+ elif isinstance(bound, Pregel):
373
+ out.extend(_tool_nodes(bound, seen))
374
+ return out
375
+
376
+
377
+ def _pending(state: Any) -> bool:
378
+ """Whether the thread has steps to run (an interrupt, a failure to retry): it is not at its end.
379
+
380
+ A task's pending interrupt counts too, whatever the runtime lists as its next nodes.
381
+ """
382
+ if getattr(state, "next", None):
383
+ return True
384
+ return any(getattr(task, "interrupts", ()) for task in getattr(state, "tasks", ()) or ())
385
+
386
+
387
+ class GovernedThread:
388
+ """One graph thread under Brutor's hooks.
389
+
390
+ async with GovernedThread(graph, config, interceptor, agent_id="loan-screening") as thread:
391
+ asked = await thread.input(prompt)
392
+ if asked.proceeds:
393
+ result = await thread.invoke({"messages": [("user", asked.target["content"])]})
394
+ answered = await thread.output(result["messages"][-1].content)
395
+
396
+ ``config`` is the graph's config (its ``configurable.thread_id`` names the thread). The other
397
+ arguments are as ``governed_invoke``'s. Inside ``async with``, ``agent_shutdown`` is sent when
398
+ the block ends with the graph at its end (so ``output`` can still be judged); without it, each
399
+ ``invoke`` that reaches the end sends it.
400
+ """
401
+
402
+ def __init__(
403
+ self,
404
+ graph: Any,
405
+ config: Mapping[str, Any] | None,
406
+ interceptor: BrutorInterceptor,
407
+ *,
408
+ agent_id: str,
409
+ resolver: Any = None,
410
+ allow_uncovered: Sequence[str] = (),
411
+ tools: Sequence[str] = (),
412
+ agent_name: str | None = None,
413
+ agent_version: str | None = None,
414
+ session_id: str | None = None,
415
+ delegation: Mapping[str, str] | None = None,
416
+ ) -> None:
417
+ if not agent_id:
418
+ raise ValueError("agent_id must name the agent")
419
+ self.graph = graph
420
+ self.config: dict[str, Any] = copy.deepcopy(dict(config or {}))
421
+ self.interceptor = interceptor
422
+ self.agent_id = agent_id
423
+ self.resolver = resolver if resolver is not None else BrutorApprovalResolver(interceptor)
424
+ self.allow_uncovered = list(allow_uncovered)
425
+ self.agent_name = agent_name
426
+ self.agent_version = agent_version
427
+ self.session_id = session_id
428
+ self.delegation = delegation
429
+ self._extra_tools = list(tools)
430
+ self._live: _Live | None = None
431
+ self._inject: dict[str, Any] | None = None
432
+ self._in_block = False
433
+ self._finished = False
434
+ self._registered, self._uncovered = self._inspect()
435
+ self._checkpointed = getattr(graph, "checkpointer", None) is not None
436
+ if self._checkpointed and CHANNEL not in (getattr(graph, "channels", None) or {}):
437
+ raise ValueError(
438
+ "a checkpointed graph needs the brutor channel to keep its session: add BrutorState to its state"
439
+ )
440
+
441
+ def _inspect(self) -> tuple[list[str], list[str]]:
442
+ registered: list[str] = []
443
+ uncovered: list[str] = []
444
+ for node in _tool_nodes(self.graph):
445
+ names = list(node.tools_by_name)
446
+ registered.extend(names)
447
+ if getattr(node, "_brutor", None) is None:
448
+ uncovered.extend(names)
449
+ refused = [n for n in dict.fromkeys(uncovered) if n not in self.allow_uncovered]
450
+ if refused:
451
+ raise UncoveredTools(refused, UNCOVERED_WHY)
452
+ registered.extend(self._extra_tools)
453
+ return list(dict.fromkeys(registered)), list(dict.fromkeys(uncovered))
454
+
455
+ @property
456
+ def hooks(self) -> HookSession | None:
457
+ """The thread's open session in this process, if any."""
458
+ return self._live.session if self._live is not None else None
459
+
460
+ # ------------------------------------------------------------------ the session
461
+
462
+ async def _thread_state(self) -> Any:
463
+ if not self._checkpointed:
464
+ return None
465
+ return await self.graph.aget_state(self.config)
466
+
467
+ async def _open(self) -> _Live:
468
+ if self._live is not None and self._live.session.is_open:
469
+ return self._live
470
+ state = await self._thread_state()
471
+ values = getattr(state, "values", None)
472
+ stored = values.get(CHANNEL) if isinstance(values, Mapping) else None
473
+ if state is not None and _pending(state) and isinstance(stored, Mapping):
474
+ self._live = self._resume(dict(stored), getattr(state, "interrupts", ()) or ())
475
+ return self._live
476
+ session = HookSession(
477
+ self.interceptor,
478
+ agent_id=self.agent_id,
479
+ framework=FRAMEWORK,
480
+ tools=self._registered,
481
+ resolver=self.resolver,
482
+ session_id=self.session_id,
483
+ agent_name=self.agent_name,
484
+ agent_version=self.agent_version,
485
+ delegation=self.delegation,
486
+ )
487
+ await session.__aenter__() # raises HookDenied: the graph is not invoked
488
+ live = _Live(session)
489
+ _remember(self.interceptor, live)
490
+ self._live = live
491
+ if self._checkpointed:
492
+ self._inject = session.snapshot()
493
+ if self._uncovered:
494
+ self.interceptor._local_warning(
495
+ session.session_id,
496
+ "agent_startup",
497
+ "uncovered_tools",
498
+ "these tools run without hooks: " + ", ".join(self._uncovered),
499
+ tools=list(self._uncovered),
500
+ )
501
+ return live
502
+
503
+ def _resume(self, stored: dict[str, Any], interrupts: Sequence[Any]) -> _Live:
504
+ known = _LIVE.get((id(self.interceptor), str(stored.get("session_id"))))
505
+ if known is not None and known.session.is_open:
506
+ return known
507
+ holds: dict[str, _Hold] = {}
508
+ next_sequence = int(stored.get("next_sequence", 1))
509
+ for pending in interrupts:
510
+ value = getattr(pending, "value", None)
511
+ approval = value.get("brutor_approval") if isinstance(value, Mapping) else None
512
+ resume = approval.get("resume") if isinstance(approval, Mapping) else None
513
+ if (
514
+ not isinstance(approval, Mapping)
515
+ or not isinstance(resume, Mapping)
516
+ or resume.get("session_id") != stored.get("session_id")
517
+ ):
518
+ continue
519
+ hold = _Hold(
520
+ str(approval["tool_call_id"]),
521
+ {k: approval[k] for k in ("id", "poll", "expires_at") if k in approval},
522
+ int(resume["sequence"]),
523
+ str(resume["timestamp"]),
524
+ str(resume["run"]),
525
+ )
526
+ holds[hold.call_id] = hold
527
+ next_sequence = max(next_sequence, hold.sequence + 1)
528
+ session = HookSession.restore(
529
+ self.interceptor,
530
+ {**stored, "next_sequence": next_sequence},
531
+ tools=self._registered,
532
+ resolver=self.resolver,
533
+ )
534
+ live = _Live(session)
535
+ live.holds = holds
536
+ _remember(self.interceptor, live)
537
+ return live
538
+
539
+ async def _close(self, reason: str) -> None:
540
+ live, self._live = self._live, None
541
+ if live is None:
542
+ return
543
+ _forget(self.interceptor, live.session.session_id)
544
+ ended: type[BaseException] | None = {"cancelled": _Cancelled, "error": RuntimeError}.get(reason)
545
+ await live.session.__aexit__(ended, None, None)
546
+
547
+ async def __aenter__(self) -> GovernedThread:
548
+ self._in_block = True
549
+ return self
550
+
551
+ async def __aexit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: Any) -> None:
552
+ self._in_block = False
553
+ if self._live is None:
554
+ return
555
+ if exc_type is not None and not self._checkpointed:
556
+ await self._close("cancelled" if issubclass(exc_type, _Cancelled) else "error")
557
+ elif self._finished or not self._checkpointed:
558
+ await self._close("completed")
559
+
560
+ # ------------------------------------------------------------------ the steps
561
+
562
+ async def input(self, content: Any, role: str = "user") -> HookOutcome:
563
+ """``input``: the application's prompt, judged before it reaches the graph."""
564
+ return await (await self._open()).session.input(content, role=role)
565
+
566
+ async def output(self, content: Any) -> HookOutcome:
567
+ """``output``: the graph's answer, judged before the application hands it on."""
568
+ return await (await self._open()).session.output(content)
569
+
570
+ async def invoke(self, inputs: Any, **kwargs: Any) -> Any:
571
+ """``graph.ainvoke(inputs, config, **kwargs)`` under Brutor's hooks."""
572
+ if self._checkpointed and not isinstance(inputs, (Mapping, Command)):
573
+ raise ValueError("a checkpointed graph's input must be a mapping (or a Command) to carry the session")
574
+ live = await self._open()
575
+ self._finished = False
576
+ config = copy.deepcopy(self.config)
577
+ config.setdefault("configurable", {})[CHANNEL] = {"session_id": live.session.session_id}
578
+ inputs = self._with_state(inputs)
579
+ try:
580
+ result = await self.graph.ainvoke(inputs, config, **kwargs)
581
+ except BaseException as e:
582
+ if not self._checkpointed and not self._in_block: # nothing to resume: the session ends
583
+ await self._close("cancelled" if isinstance(e, _Cancelled) else "error")
584
+ raise
585
+ state = await self._thread_state()
586
+ self._finished = state is None or not _pending(state)
587
+ if self._finished and not self._in_block:
588
+ await self._close("completed")
589
+ return result
590
+
591
+ def _with_state(self, inputs: Any) -> Any:
592
+ snapshot, self._inject = self._inject, None
593
+ if snapshot is None:
594
+ return inputs
595
+ if isinstance(inputs, Command):
596
+ update = inputs.update if isinstance(inputs.update, dict) else {}
597
+ return Command(
598
+ graph=inputs.graph, update={**update, CHANNEL: snapshot}, resume=inputs.resume, goto=inputs.goto
599
+ )
600
+ return {**inputs, CHANNEL: snapshot}
601
+
602
+ def __repr__(self) -> str:
603
+ return f"GovernedThread(agent_id={self.agent_id!r})"
604
+
605
+
606
+ async def governed_invoke(
607
+ graph: Any,
608
+ inputs: Any,
609
+ config: Mapping[str, Any] | None,
610
+ interceptor: BrutorInterceptor,
611
+ *,
612
+ agent_id: str,
613
+ **kwargs: Any,
614
+ ) -> Any:
615
+ """Invoke ``graph`` under Brutor's hooks (a ``GovernedThread`` for one invoke).
616
+
617
+ ``agent_startup`` before the thread's first invoke (a deny raises ``HookDenied`` and the graph
618
+ is not invoked), ``agent_shutdown`` when the graph reaches its end. Keyword arguments are
619
+ ``GovernedThread``'s: ``resolver``, ``allow_uncovered``, ``tools``, ``agent_name``,
620
+ ``agent_version``, ``session_id``, ``delegation`` (for a delegate: the headers it received).
621
+ """
622
+ invoke_kwargs = kwargs.pop("invoke_kwargs", None) or {}
623
+ return await GovernedThread(graph, config, interceptor, agent_id=agent_id, **kwargs).invoke(inputs, **invoke_kwargs)