Skip to main content

rusty_agent_runtime/
middleware.rs

1//! Middleware / Interceptor SDK: ordered layers around execution.
2//!
3//! A [`Middleware`] is an async, object-safe interception layer with six
4//! hooks — before/after at three points: **node run** ([`NodeCall`]),
5//! **model call** ([`ModelCall`]), and **tool call** ([`ToolInvocation`]).
6//! Every hook returns a [`Decision`]: continue (with any mutations applied
7//! to the context in place), reject with a structured [`Rejection`], or
8//! short-circuit with a substitute result.
9//!
10//! Layers compose into a [`MiddlewareChain`] with tower-style onion
11//! semantics:
12//!
13//! - before-hooks run in **registration order** on the way in, after-hooks
14//!   in **reverse order** on the way out;
15//! - a before-hook short-circuit at layer *i* skips the remaining
16//!   before-hooks and the operation itself; the after-hooks of the layers
17//!   that already entered (`0..i`) unwind over the substitute result;
18//! - a rejection is terminal: no after-hooks run, and the rejection surfaces
19//!   through the crate's existing error taxonomy — node-run rejections as
20//!   [`RustyError::Node`], model rejections as [`RustyError::Llm`], tool
21//!   rejections as [`RustyError::Tool`] (which the
22//!   [`crate::tool::ToolExecutor`] renders into an `ERROR:` tool message the
23//!   model can observe). The message is the [`Rejection`]'s canonical
24//!   [`Display`](std::fmt::Display) form; the typed `Rejection` itself is
25//!   the contract at the middleware API. Never a panic;
26//! - after-hooks run on the success path only; operation errors propagate
27//!   untouched. An after-hook short-circuit replaces the result and skips
28//!   the remaining (outer) after-hooks.
29//!
30//! Wiring:
31//!
32//! - **Node runs** — attach layers to the [`crate::executor::Executor`] with
33//!   `.layer(...)`; the chain wraps every node invocation at the super-step
34//!   boundary. The same chain reaches node code through
35//!   [`crate::node::NodeContext::middleware`].
36//! - **Tool calls** — hand the chain to
37//!   [`crate::tool::ToolExecutor::with_middleware`]; every dispatched call is
38//!   wrapped. A tool-level rejection follows the executor's
39//!   failure-isolation contract and becomes an `ERROR:` tool message the
40//!   model can observe and recover from.
41//! - **Model calls** — wrap a [`crate::llm::ChatModel`] in
42//!   [`MiddlewareChatModel`]; every `chat` (and, via the default fallback,
43//!   `chat_stream`) is intercepted.
44//!
45//! Two reference layers ship here: [`RequestLogger`] (tracing-based
46//! observation) and [`ToolCallBlocklist`] (reject-by-policy).
47
48use std::collections::HashSet;
49use std::future::Future;
50use std::sync::Arc;
51
52use async_trait::async_trait;
53use serde::{Deserialize, Serialize};
54use serde_json::Value;
55
56use crate::error::{Result, RustyError};
57use crate::llm::{ChatMessage, ChatModel, ChatResponse, ToolCall};
58use crate::node::NodeOutput;
59use crate::state::State;
60
61/// The interception point a [`Rejection`] originated at.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum InterceptPoint {
65    /// A node run at the super-step boundary.
66    NodeRun,
67    /// A [`crate::llm::ChatModel`] call.
68    ModelCall,
69    /// A tool call dispatched through [`crate::tool::ToolExecutor`].
70    ToolCall,
71}
72
73impl std::fmt::Display for InterceptPoint {
74    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75        let s = match self {
76            InterceptPoint::NodeRun => "node_run",
77            InterceptPoint::ModelCall => "model_call",
78            InterceptPoint::ToolCall => "tool_call",
79        };
80        f.write_str(s)
81    }
82}
83
84/// A structured middleware rejection: which layer, at which point, and why.
85///
86/// The typed contract at the middleware API. When a rejection leaves the
87/// chain it maps onto the crate's string-payload error taxonomy by
88/// interception point (node run → [`RustyError::Node`], model call →
89/// [`RustyError::Llm`], tool call → [`RustyError::Tool`]), with this
90/// struct's canonical [`Display`](std::fmt::Display) as the message —
91/// keeping `RustyError` additive-free for downstream exhaustive matches.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93pub struct Rejection {
94    /// The rejecting layer ([`Middleware::name`]).
95    pub middleware: String,
96    /// The interception point that rejected.
97    pub point: InterceptPoint,
98    /// Machine-readable reason code (e.g. `"tool_blocked"`).
99    pub reason: String,
100    /// Optional human-readable detail.
101    #[serde(default, skip_serializing_if = "Option::is_none")]
102    pub detail: Option<String>,
103}
104
105impl Rejection {
106    /// A rejection by `middleware` at `point` with reason code `reason`.
107    pub fn new(
108        middleware: impl Into<String>,
109        point: InterceptPoint,
110        reason: impl Into<String>,
111    ) -> Self {
112        Self {
113            middleware: middleware.into(),
114            point,
115            reason: reason.into(),
116            detail: None,
117        }
118    }
119
120    /// Builder-style: attach human-readable detail.
121    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
122        self.detail = Some(detail.into());
123        self
124    }
125}
126
127impl std::fmt::Display for Rejection {
128    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
129        write!(
130            f,
131            "rejected by middleware `{}` at {}: {}",
132            self.middleware, self.point, self.reason
133        )
134    }
135}
136
137impl Rejection {
138    /// Map onto the crate's error taxonomy by interception point; see the
139    /// struct docs.
140    pub(crate) fn into_error(self) -> RustyError {
141        let message = self.to_string();
142        match self.point {
143            InterceptPoint::NodeRun => RustyError::Node(message),
144            InterceptPoint::ModelCall => RustyError::Llm(message),
145            InterceptPoint::ToolCall => RustyError::Tool(message),
146        }
147    }
148}
149
150/// The verdict a middleware hook returns.
151///
152/// `R` is the result type of the intercepted operation: [`NodeOutput`] for
153/// node runs, [`ChatResponse`] for model calls, [`Value`] for tool calls.
154#[derive(Debug, Clone, PartialEq)]
155pub enum Decision<R> {
156    /// Continue through the chain (any mutations applied to the context in
157    /// place propagate to the next layer and the operation).
158    Continue,
159    /// Stop the chain and fail the operation with a structured reason.
160    Reject(Rejection),
161    /// Before-hook: skip the remaining before-hooks and the operation
162    /// itself; `R` stands in for its result while the entered layers unwind.
163    /// After-hook: replace the result with `R` and skip the remaining
164    /// (outer) after-hooks.
165    ShortCircuit(R),
166}
167
168/// Node-run interception context: the invocation a node is about to run with.
169///
170/// The `state` snapshot is the payload before-hooks may mutate; mutations
171/// propagate into the [`crate::node::NodeContext`] the node receives.
172#[derive(Debug, Clone)]
173pub struct NodeCall {
174    thread_id: String,
175    node: String,
176    step: usize,
177    state: State,
178}
179
180impl NodeCall {
181    /// A context for `node` at super-step `step` of thread `thread_id`.
182    pub fn new(
183        thread_id: impl Into<String>,
184        node: impl Into<String>,
185        step: usize,
186        state: State,
187    ) -> Self {
188        Self {
189            thread_id: thread_id.into(),
190            node: node.into(),
191            step,
192            state,
193        }
194    }
195
196    /// The thread (run) this invocation belongs to.
197    pub fn thread_id(&self) -> &str {
198        &self.thread_id
199    }
200
201    /// The node about to run.
202    pub fn node(&self) -> &str {
203        &self.node
204    }
205
206    /// The current super-step index.
207    pub fn step(&self) -> usize {
208        self.step
209    }
210
211    /// The invocation's state snapshot.
212    pub fn state(&self) -> &State {
213        &self.state
214    }
215
216    /// Mutable access to the snapshot the node will receive.
217    pub fn state_mut(&mut self) -> &mut State {
218        &mut self.state
219    }
220
221    /// Convenience: insert a channel into the snapshot.
222    pub fn insert(&mut self, channel: impl Into<String>, value: Value) {
223        self.state.insert(channel, value);
224    }
225}
226
227/// Model-call interception context: the request a [`ChatModel`] is about to
228/// receive. Mutations to the messages or tool schemas propagate to the model.
229#[derive(Debug, Clone)]
230pub struct ModelCall {
231    thread_id: String,
232    node: String,
233    messages: Vec<ChatMessage>,
234    tools: Vec<Value>,
235}
236
237impl ModelCall {
238    /// A context for a model call with `messages` and tool schemas `tools`.
239    pub fn new(
240        thread_id: impl Into<String>,
241        node: impl Into<String>,
242        messages: Vec<ChatMessage>,
243        tools: Vec<Value>,
244    ) -> Self {
245        Self {
246            thread_id: thread_id.into(),
247            node: node.into(),
248            messages,
249            tools,
250        }
251    }
252
253    /// The thread (run) this call belongs to, or empty when unknown.
254    pub fn thread_id(&self) -> &str {
255        &self.thread_id
256    }
257
258    /// The node making the call, or empty when unknown.
259    pub fn node(&self) -> &str {
260        &self.node
261    }
262
263    /// The conversation about to be sent.
264    pub fn messages(&self) -> &[ChatMessage] {
265        &self.messages
266    }
267
268    /// Mutable access to the conversation (inject, redact, rewrite).
269    pub fn messages_mut(&mut self) -> &mut Vec<ChatMessage> {
270        &mut self.messages
271    }
272
273    /// The OpenAI-format tool schemas about to be sent.
274    pub fn tools(&self) -> &[Value] {
275        &self.tools
276    }
277
278    /// Mutable access to the tool schemas.
279    pub fn tools_mut(&mut self) -> &mut Vec<Value> {
280        &mut self.tools
281    }
282}
283
284/// Tool-call interception context: one tool call about to be dispatched.
285///
286/// The registry lookup happens **after** before-hooks, so a layer may
287/// rewrite the arguments — or the target tool name itself.
288#[derive(Debug, Clone)]
289pub struct ToolInvocation {
290    thread_id: String,
291    node: String,
292    call: ToolCall,
293}
294
295impl ToolInvocation {
296    /// A context wrapping one [`ToolCall`].
297    pub fn new(thread_id: impl Into<String>, node: impl Into<String>, call: ToolCall) -> Self {
298        Self {
299            thread_id: thread_id.into(),
300            node: node.into(),
301            call,
302        }
303    }
304
305    /// The thread (run) this call belongs to, or empty when unknown.
306    pub fn thread_id(&self) -> &str {
307        &self.thread_id
308    }
309
310    /// The node dispatching the call, or empty when unknown.
311    pub fn node(&self) -> &str {
312        &self.node
313    }
314
315    /// The tool call about to be dispatched.
316    pub fn call(&self) -> &ToolCall {
317        &self.call
318    }
319
320    /// Mutable access to the tool call (id, name, arguments).
321    pub fn call_mut(&mut self) -> &mut ToolCall {
322        &mut self.call
323    }
324
325    /// The provider-assigned call id.
326    pub fn id(&self) -> &str {
327        &self.call.id
328    }
329
330    /// The target tool name.
331    pub fn name(&self) -> &str {
332        &self.call.name
333    }
334
335    /// The model-supplied arguments.
336    pub fn arguments(&self) -> &Value {
337        &self.call.arguments
338    }
339
340    /// Convenience: replace the arguments.
341    pub fn set_arguments(&mut self, arguments: Value) {
342        self.call.arguments = arguments;
343    }
344}
345
346/// The interception layer: async, object-safe hooks around execution.
347///
348/// Implement any subset of hooks; every default passes through unchanged.
349/// `Send + Sync` because layers are shared across concurrent node
350/// invocations and tool calls within a run.
351#[async_trait]
352pub trait Middleware: Send + Sync {
353    /// Human/log-friendly name, recorded on rejections.
354    fn name(&self) -> &str;
355
356    /// Node run, inbound (registration order).
357    async fn before_node(&self, call: &mut NodeCall) -> Decision<NodeOutput> {
358        let _ = call;
359        Decision::Continue
360    }
361
362    /// Node run, outbound (reverse registration order). Success path only.
363    async fn after_node(&self, call: &NodeCall, output: &mut NodeOutput) -> Decision<NodeOutput> {
364        let _ = (call, output);
365        Decision::Continue
366    }
367
368    /// Model call, inbound (registration order).
369    async fn before_model(&self, call: &mut ModelCall) -> Decision<ChatResponse> {
370        let _ = call;
371        Decision::Continue
372    }
373
374    /// Model call, outbound (reverse registration order). Success path only.
375    async fn after_model(
376        &self,
377        call: &ModelCall,
378        response: &mut ChatResponse,
379    ) -> Decision<ChatResponse> {
380        let _ = (call, response);
381        Decision::Continue
382    }
383
384    /// Tool call, inbound (registration order).
385    async fn before_tool(&self, call: &mut ToolInvocation) -> Decision<Value> {
386        let _ = call;
387        Decision::Continue
388    }
389
390    /// Tool call, outbound (reverse registration order). Success path only.
391    async fn after_tool(&self, call: &ToolInvocation, result: &mut Value) -> Decision<Value> {
392        let _ = (call, result);
393        Decision::Continue
394    }
395}
396
397/// An ordered stack of middleware layers with onion semantics.
398///
399/// Cheap to clone (`Arc` layers); empty by default, and every consumer
400/// (executor, tool executor, model wrapper) takes its original code path
401/// when the chain is empty.
402#[derive(Clone, Default)]
403pub struct MiddlewareChain {
404    layers: Vec<Arc<dyn Middleware>>,
405}
406
407impl std::fmt::Debug for MiddlewareChain {
408    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
409        f.debug_struct("MiddlewareChain")
410            .field(
411                "layers",
412                &self.layers.iter().map(|l| l.name()).collect::<Vec<_>>(),
413            )
414            .finish()
415    }
416}
417
418impl MiddlewareChain {
419    /// An empty chain.
420    pub fn new() -> Self {
421        Self::default()
422    }
423
424    /// Builder-style: append a layer (runs after the already-added layers on
425    /// the way in, before them on the way out).
426    pub fn layer<M: Middleware + 'static>(mut self, middleware: M) -> Self {
427        self.push(Arc::new(middleware));
428        self
429    }
430
431    /// Append a pre-shared layer.
432    pub fn push(&mut self, middleware: Arc<dyn Middleware>) -> &mut Self {
433        self.layers.push(middleware);
434        self
435    }
436
437    /// `true` if no layers are attached.
438    pub fn is_empty(&self) -> bool {
439        self.layers.is_empty()
440    }
441
442    /// Number of attached layers.
443    pub fn len(&self) -> usize {
444        self.layers.len()
445    }
446
447    /// The layer names, in registration order.
448    pub fn names(&self) -> impl Iterator<Item = &str> {
449        self.layers.iter().map(|l| l.name())
450    }
451
452    /// The layers, in registration order, as shared handles — the form
453    /// the executor's `layer_shared` wiring takes them in when a resolved
454    /// composition attaches to a run (R0.11 wave 4).
455    pub fn layers(&self) -> &[Arc<dyn Middleware>] {
456        &self.layers
457    }
458
459    /// Run the onion around a node invocation: before-hooks inward, `op`,
460    /// after-hooks outward. See the module docs for the full contract.
461    pub async fn run_node<F, Fut>(&self, call: &mut NodeCall, op: F) -> Result<NodeOutput>
462    where
463        F: FnOnce(&NodeCall) -> Fut + Send,
464        Fut: Future<Output = Result<NodeOutput>> + Send,
465    {
466        let mut entered = 0;
467        let mut substitute = None;
468        for layer in &self.layers {
469            match layer.before_node(call).await {
470                Decision::Continue => entered += 1,
471                Decision::Reject(rejection) => return Err(rejection.into_error()),
472                Decision::ShortCircuit(output) => {
473                    substitute = Some(output);
474                    break;
475                }
476            }
477        }
478        let mut result = match substitute {
479            Some(output) => output,
480            None => {
481                entered = self.layers.len();
482                op(call).await?
483            }
484        };
485        for layer in self.layers[..entered].iter().rev() {
486            match layer.after_node(call, &mut result).await {
487                Decision::Continue => {}
488                Decision::Reject(rejection) => return Err(rejection.into_error()),
489                Decision::ShortCircuit(output) => {
490                    result = output;
491                    break;
492                }
493            }
494        }
495        Ok(result)
496    }
497
498    /// Run the onion around a model call. Same contract as
499    /// [`MiddlewareChain::run_node`].
500    pub async fn run_model<F, Fut>(&self, call: &mut ModelCall, op: F) -> Result<ChatResponse>
501    where
502        F: FnOnce(&ModelCall) -> Fut + Send,
503        Fut: Future<Output = Result<ChatResponse>> + Send,
504    {
505        let mut entered = 0;
506        let mut substitute = None;
507        for layer in &self.layers {
508            match layer.before_model(call).await {
509                Decision::Continue => entered += 1,
510                Decision::Reject(rejection) => return Err(rejection.into_error()),
511                Decision::ShortCircuit(response) => {
512                    substitute = Some(response);
513                    break;
514                }
515            }
516        }
517        let mut result = match substitute {
518            Some(response) => response,
519            None => {
520                entered = self.layers.len();
521                op(call).await?
522            }
523        };
524        for layer in self.layers[..entered].iter().rev() {
525            match layer.after_model(call, &mut result).await {
526                Decision::Continue => {}
527                Decision::Reject(rejection) => return Err(rejection.into_error()),
528                Decision::ShortCircuit(response) => {
529                    result = response;
530                    break;
531                }
532            }
533        }
534        Ok(result)
535    }
536
537    /// Run the onion around a tool call. Same contract as
538    /// [`MiddlewareChain::run_node`].
539    pub async fn run_tool<F, Fut>(&self, call: &mut ToolInvocation, op: F) -> Result<Value>
540    where
541        F: FnOnce(&ToolInvocation) -> Fut + Send,
542        Fut: Future<Output = Result<Value>> + Send,
543    {
544        let mut entered = 0;
545        let mut substitute = None;
546        for layer in &self.layers {
547            match layer.before_tool(call).await {
548                Decision::Continue => entered += 1,
549                Decision::Reject(rejection) => return Err(rejection.into_error()),
550                Decision::ShortCircuit(value) => {
551                    substitute = Some(value);
552                    break;
553                }
554            }
555        }
556        let mut result = match substitute {
557            Some(value) => value,
558            None => {
559                entered = self.layers.len();
560                op(call).await?
561            }
562        };
563        for layer in self.layers[..entered].iter().rev() {
564            match layer.after_tool(call, &mut result).await {
565                Decision::Continue => {}
566                Decision::Reject(rejection) => return Err(rejection.into_error()),
567                Decision::ShortCircuit(value) => {
568                    result = value;
569                    break;
570                }
571            }
572        }
573        Ok(result)
574    }
575}
576
577/// A [`ChatModel`] wrapper that runs every call through a
578/// [`MiddlewareChain`]'s model hooks.
579///
580/// Construct per node (or per invocation) — typically with the chain from
581/// [`crate::node::NodeContext::middleware`]. The optional `thread`/`node`
582/// labels flow into the [`ModelCall`] context.
583///
584/// `chat_stream` needs no override: the [`ChatModel`] default falls back to
585/// `chat`, so streamed calls are intercepted identically.
586#[derive(Clone)]
587pub struct MiddlewareChatModel {
588    inner: Arc<dyn ChatModel>,
589    chain: MiddlewareChain,
590    thread_id: String,
591    node: String,
592}
593
594impl MiddlewareChatModel {
595    /// A middleware wrapper around `inner`, intercepting through `chain`.
596    pub fn new(inner: Arc<dyn ChatModel>, chain: MiddlewareChain) -> Self {
597        Self {
598            inner,
599            chain,
600            thread_id: String::new(),
601            node: String::new(),
602        }
603    }
604
605    /// Builder-style: the thread (run) label for the [`ModelCall`] context.
606    pub fn thread(mut self, thread_id: impl Into<String>) -> Self {
607        self.thread_id = thread_id.into();
608        self
609    }
610
611    /// Builder-style: the node label for the [`ModelCall`] context.
612    pub fn node(mut self, node: impl Into<String>) -> Self {
613        self.node = node.into();
614        self
615    }
616}
617
618#[async_trait]
619impl ChatModel for MiddlewareChatModel {
620    async fn chat(&self, messages: &[ChatMessage], tools: &[Value]) -> Result<ChatResponse> {
621        if self.chain.is_empty() {
622            return self.inner.chat(messages, tools).await;
623        }
624        let mut call = ModelCall::new(
625            self.thread_id.clone(),
626            self.node.clone(),
627            messages.to_vec(),
628            tools.to_vec(),
629        );
630        self.chain
631            .run_model(&mut call, |call| {
632                let inner = Arc::clone(&self.inner);
633                let messages = call.messages().to_vec();
634                let tools = call.tools().to_vec();
635                async move { inner.chat(&messages, &tools).await }
636            })
637            .await
638    }
639
640    fn effect(&self) -> crate::record::Effect {
641        self.inner.effect()
642    }
643}
644
645/// Tracing-based observation middleware: emits an INFO event at every
646/// interception point and passes everything through unchanged.
647///
648/// Payloads are deliberately not logged — counts and ids only. Logging full
649/// model or tool payloads is a data-leak footgun; compose a redaction layer
650/// first if you need them.
651#[derive(Debug, Default)]
652pub struct RequestLogger;
653
654impl RequestLogger {
655    /// A logger layer.
656    pub fn new() -> Self {
657        Self
658    }
659}
660
661#[async_trait]
662impl Middleware for RequestLogger {
663    fn name(&self) -> &str {
664        "request_logger"
665    }
666
667    async fn before_node(&self, call: &mut NodeCall) -> Decision<NodeOutput> {
668        tracing::info!(
669            thread_id = %call.thread_id(),
670            node = %call.node(),
671            step = call.step(),
672            "middleware: node run started"
673        );
674        Decision::Continue
675    }
676
677    async fn after_node(&self, call: &NodeCall, output: &mut NodeOutput) -> Decision<NodeOutput> {
678        tracing::info!(
679            thread_id = %call.thread_id(),
680            node = %call.node(),
681            step = call.step(),
682            channels = output.updates.len(),
683            "middleware: node run completed"
684        );
685        Decision::Continue
686    }
687
688    async fn before_model(&self, call: &mut ModelCall) -> Decision<ChatResponse> {
689        tracing::info!(
690            thread_id = %call.thread_id(),
691            node = %call.node(),
692            messages = call.messages().len(),
693            tools = call.tools().len(),
694            "middleware: model call started"
695        );
696        Decision::Continue
697    }
698
699    async fn after_model(
700        &self,
701        call: &ModelCall,
702        response: &mut ChatResponse,
703    ) -> Decision<ChatResponse> {
704        tracing::info!(
705            thread_id = %call.thread_id(),
706            node = %call.node(),
707            total_tokens = response.usage.map(|u| u.total_tokens),
708            "middleware: model call completed"
709        );
710        Decision::Continue
711    }
712
713    async fn before_tool(&self, call: &mut ToolInvocation) -> Decision<Value> {
714        tracing::info!(
715            thread_id = %call.thread_id(),
716            node = %call.node(),
717            tool = %call.name(),
718            call_id = %call.id(),
719            "middleware: tool call started"
720        );
721        Decision::Continue
722    }
723
724    async fn after_tool(&self, call: &ToolInvocation, result: &mut Value) -> Decision<Value> {
725        let _ = result;
726        tracing::info!(
727            thread_id = %call.thread_id(),
728            node = %call.node(),
729            tool = %call.name(),
730            call_id = %call.id(),
731            "middleware: tool call completed"
732        );
733        Decision::Continue
734    }
735}
736
737/// Reject-by-policy middleware: tool calls to blocklisted tools never
738/// execute; each is rejected with a structured [`Rejection`] (reason
739/// `"tool_blocked"` by default) that surfaces as an `ERROR:` tool message
740/// under the [`crate::tool::ToolExecutor`] failure-isolation contract.
741#[derive(Debug, Clone)]
742pub struct ToolCallBlocklist {
743    blocked: HashSet<String>,
744    reason: String,
745}
746
747impl ToolCallBlocklist {
748    /// Block the named tools with the default reason code.
749    pub fn new<I, S>(tools: I) -> Self
750    where
751        I: IntoIterator<Item = S>,
752        S: Into<String>,
753    {
754        Self {
755            blocked: tools.into_iter().map(Into::into).collect(),
756            reason: "tool_blocked".to_owned(),
757        }
758    }
759
760    /// Builder-style: override the rejection reason code.
761    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
762        self.reason = reason.into();
763        self
764    }
765
766    /// `true` if calls to `tool` are rejected.
767    pub fn contains(&self, tool: &str) -> bool {
768        self.blocked.contains(tool)
769    }
770}
771
772#[async_trait]
773impl Middleware for ToolCallBlocklist {
774    fn name(&self) -> &str {
775        "tool_call_blocklist"
776    }
777
778    async fn before_tool(&self, call: &mut ToolInvocation) -> Decision<Value> {
779        if self.blocked.contains(call.name()) {
780            Decision::Reject(
781                Rejection::new(self.name(), InterceptPoint::ToolCall, self.reason.clone())
782                    .with_detail(format!("tool `{}` is blocked by policy", call.name())),
783            )
784        } else {
785            Decision::Continue
786        }
787    }
788}
789
790/// Instantiate a journaled [`crate::learn::MiddlewareLayerConfig`] composition
791/// into a live [`MiddlewareChain`].
792///
793/// The composition is evidence: a run pins its digest in the manifest and the
794/// resolved layer order in the journal, so instantiation must be a pure,
795/// deterministic function of the journaled value against the **compiled-in
796/// layer vocabulary** — the same names [`MiddlewareChain::names`] reports.
797/// Two layers are in the vocabulary today:
798///
799/// - `request_logger` — zero-config; a `config` payload is refused (a config
800///   the layer ignores would be evidence the chain cannot honor);
801/// - `tool_call_blocklist` — requires `{"blocked": ["tool.name", ...],
802///   "reason": "..."?}`; `reason` defaults to the layer's own reason code.
803///
804/// An unknown layer name, a config on a config-free layer, or a malformed
805/// config is an error naming the vocabulary — the set NEVER grows by
806/// accepting unknown names at resolution time (R0.11 wave 4, closed-set
807/// extension; design doc §Middleware).
808pub fn instantiate_composition(
809    layers: &[crate::learn::MiddlewareLayerConfig],
810) -> Result<MiddlewareChain> {
811    /// The `tool_call_blocklist` layer's config payload. Unknown keys are
812    /// ignored (forward-compatible); the two governed keys are pinned by
813    /// golden evidence.
814    #[derive(Deserialize)]
815    struct BlocklistConfig {
816        blocked: Vec<String>,
817        #[serde(default)]
818        reason: Option<String>,
819    }
820
821    let mut chain = MiddlewareChain::new();
822    for entry in layers {
823        match entry.layer.as_str() {
824            "request_logger" => {
825                if entry.config.is_some() {
826                    return Err(RustyError::Graph(
827                        "middleware layer `request_logger` takes no config payload".to_owned(),
828                    ));
829                }
830                chain.push(Arc::new(RequestLogger::new()));
831            }
832            "tool_call_blocklist" => {
833                let config = entry.config.as_ref().ok_or_else(|| {
834                    RustyError::Graph(
835                        "middleware layer `tool_call_blocklist` requires a config payload: \
836                         {\"blocked\": [\"tool.name\"], \"reason\"?}"
837                            .to_owned(),
838                    )
839                })?;
840                let parsed: BlocklistConfig =
841                    serde_json::from_value(config.clone()).map_err(|e| {
842                        RustyError::Graph(format!(
843                            "middleware layer `tool_call_blocklist` config is malformed: {e}"
844                        ))
845                    })?;
846                let mut layer = ToolCallBlocklist::new(parsed.blocked);
847                if let Some(reason) = parsed.reason {
848                    layer = layer.with_reason(reason);
849                }
850                chain.push(Arc::new(layer));
851            }
852            other => {
853                return Err(RustyError::Graph(format!(
854                    "unknown middleware layer `{other}`: the compiled-in vocabulary is \
855                     [request_logger, tool_call_blocklist]"
856                )));
857            }
858        }
859    }
860    Ok(chain)
861}
862
863#[cfg(test)]
864mod tests {
865    use super::*;
866    use crate::learn::MiddlewareLayerConfig;
867    use serde_json::json;
868    use std::sync::Mutex;
869
870    /// Shared, thread-safe record of hook invocations, for order proofs.
871    #[derive(Clone, Default)]
872    struct Trace(Arc<Mutex<Vec<String>>>);
873
874    impl Trace {
875        fn record(&self, entry: impl Into<String>) {
876            self.0.lock().expect("trace lock").push(entry.into());
877        }
878
879        fn entries(&self) -> Vec<String> {
880            self.0.lock().expect("trace lock").clone()
881        }
882    }
883
884    /// Records before/after node hooks as `Lx:before|after:<node>`.
885    struct Recorder {
886        id: &'static str,
887        trace: Trace,
888    }
889
890    #[async_trait]
891    impl Middleware for Recorder {
892        fn name(&self) -> &str {
893            self.id
894        }
895
896        async fn before_node(&self, call: &mut NodeCall) -> Decision<NodeOutput> {
897            self.trace
898                .record(format!("{}:before:{}", self.id, call.node()));
899            Decision::Continue
900        }
901
902        async fn after_node(
903            &self,
904            call: &NodeCall,
905            _output: &mut NodeOutput,
906        ) -> Decision<NodeOutput> {
907            self.trace
908                .record(format!("{}:after:{}", self.id, call.node()));
909            Decision::Continue
910        }
911    }
912
913    #[tokio::test]
914    async fn empty_chain_passes_through() {
915        let chain = MiddlewareChain::new();
916        assert!(chain.is_empty());
917        let mut call = NodeCall::new("t-1", "node-a", 0, State::new());
918        let result = chain
919            .run_node(&mut call, |_call| async {
920                Ok(NodeOutput::update("x", json!(1)))
921            })
922            .await
923            .unwrap();
924        assert_eq!(result.updates.get("x"), Some(&json!(1)));
925    }
926
927    #[tokio::test]
928    async fn before_hooks_run_in_registration_order_after_hooks_in_reverse() {
929        let trace = Trace::default();
930        let chain = MiddlewareChain::new()
931            .layer(Recorder {
932                id: "L1",
933                trace: trace.clone(),
934            })
935            .layer(Recorder {
936                id: "L2",
937                trace: trace.clone(),
938            })
939            .layer(Recorder {
940                id: "L3",
941                trace: trace.clone(),
942            });
943        assert_eq!(chain.len(), 3);
944        assert_eq!(chain.names().collect::<Vec<_>>(), ["L1", "L2", "L3"]);
945
946        let op_trace = trace.clone();
947        let mut call = NodeCall::new("t-1", "node-a", 0, State::new());
948        let result = chain
949            .run_node(&mut call, |_call| {
950                let op_trace = op_trace.clone();
951                async move {
952                    op_trace.record("op");
953                    Ok(NodeOutput::update("x", json!(1)))
954                }
955            })
956            .await
957            .unwrap();
958
959        assert_eq!(result.updates.get("x"), Some(&json!(1)));
960        assert_eq!(
961            trace.entries(),
962            vec![
963                "L1:before:node-a",
964                "L2:before:node-a",
965                "L3:before:node-a",
966                "op",
967                "L3:after:node-a",
968                "L2:after:node-a",
969                "L1:after:node-a",
970            ]
971        );
972    }
973
974    /// Injects state inbound, rewrites the output outbound.
975    struct Mutate;
976
977    #[async_trait]
978    impl Middleware for Mutate {
979        fn name(&self) -> &str {
980            "mutate"
981        }
982
983        async fn before_node(&self, call: &mut NodeCall) -> Decision<NodeOutput> {
984            call.insert("injected", json!(true));
985            Decision::Continue
986        }
987
988        async fn after_node(
989            &self,
990            _call: &NodeCall,
991            output: &mut NodeOutput,
992        ) -> Decision<NodeOutput> {
993            output.updates.insert("x".into(), json!("rewritten"));
994            Decision::Continue
995        }
996    }
997
998    #[tokio::test]
999    async fn mutations_propagate_inward_and_outward() {
1000        let chain = MiddlewareChain::new().layer(Mutate);
1001        let mut call = NodeCall::new("t-1", "node-a", 0, State::new());
1002        let result = chain
1003            .run_node(&mut call, |call| {
1004                // The before-hook's state mutation is visible to the node.
1005                assert_eq!(call.state().get("injected"), Some(&json!(true)));
1006                async move { Ok(NodeOutput::update("x", json!("original"))) }
1007            })
1008            .await
1009            .unwrap();
1010        // The after-hook's rewrite is visible to the caller.
1011        assert_eq!(result.updates.get("x"), Some(&json!("rewritten")));
1012    }
1013
1014    struct PolicyReject {
1015        reason: &'static str,
1016    }
1017
1018    #[async_trait]
1019    impl Middleware for PolicyReject {
1020        fn name(&self) -> &str {
1021            "policy_reject"
1022        }
1023
1024        async fn before_node(&self, _call: &mut NodeCall) -> Decision<NodeOutput> {
1025            Decision::Reject(
1026                Rejection::new(self.name(), InterceptPoint::NodeRun, self.reason)
1027                    .with_detail("denied by test policy"),
1028            )
1029        }
1030    }
1031
1032    #[tokio::test]
1033    async fn reject_skips_operation_and_all_after_hooks() {
1034        let trace = Trace::default();
1035        let chain = MiddlewareChain::new()
1036            .layer(Recorder {
1037                id: "L1",
1038                trace: trace.clone(),
1039            })
1040            .layer(PolicyReject { reason: "policy" })
1041            .layer(Recorder {
1042                id: "L3",
1043                trace: trace.clone(),
1044            });
1045
1046        let op_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
1047        let op_flag = op_ran.clone();
1048        let mut call = NodeCall::new("t-1", "node-b", 2, State::new());
1049        let err = chain
1050            .run_node(&mut call, |_call| {
1051                let op_flag = op_flag.clone();
1052                async move {
1053                    op_flag.store(true, std::sync::atomic::Ordering::SeqCst);
1054                    Ok(NodeOutput::empty())
1055                }
1056            })
1057            .await
1058            .unwrap_err();
1059
1060        match err {
1061            RustyError::Node(message) => {
1062                // Node-run rejections map onto RustyError::Node carrying the
1063                // Rejection's canonical Display form.
1064                assert!(
1065                    message.contains("rejected by middleware `policy_reject` at node_run: policy"),
1066                    "got: {message}"
1067                );
1068            }
1069            other => panic!("expected RustyError::Node, got {other:?}"),
1070        }
1071        assert!(!op_ran.load(std::sync::atomic::Ordering::SeqCst));
1072        // L1 entered (before ran), L3 never ran at all, and no after-hooks
1073        // unwind a rejection.
1074        assert_eq!(trace.entries(), vec!["L1:before:node-b"]);
1075    }
1076
1077    /// Short-circuits node `victim` with a substitute output.
1078    struct Skip;
1079
1080    #[async_trait]
1081    impl Middleware for Skip {
1082        fn name(&self) -> &str {
1083            "skip"
1084        }
1085
1086        async fn before_node(&self, call: &mut NodeCall) -> Decision<NodeOutput> {
1087            if call.node() == "victim" {
1088                Decision::ShortCircuit(NodeOutput::update("sub", json!("substitute")))
1089            } else {
1090                Decision::Continue
1091            }
1092        }
1093    }
1094
1095    #[tokio::test]
1096    async fn short_circuit_returns_substitute_and_unwinds_entered_layers() {
1097        let trace = Trace::default();
1098        let chain = MiddlewareChain::new()
1099            .layer(Recorder {
1100                id: "L1",
1101                trace: trace.clone(),
1102            })
1103            .layer(Skip)
1104            .layer(Recorder {
1105                id: "L3",
1106                trace: trace.clone(),
1107            });
1108
1109        let op_ran = Arc::new(std::sync::atomic::AtomicBool::new(false));
1110        let op_flag = op_ran.clone();
1111        let mut call = NodeCall::new("t-1", "victim", 1, State::new());
1112        let result = chain
1113            .run_node(&mut call, |_call| {
1114                let op_flag = op_flag.clone();
1115                async move {
1116                    op_flag.store(true, std::sync::atomic::Ordering::SeqCst);
1117                    Ok(NodeOutput::empty())
1118                }
1119            })
1120            .await
1121            .unwrap();
1122
1123        assert_eq!(result.updates.get("sub"), Some(&json!("substitute")));
1124        assert!(!op_ran.load(std::sync::atomic::Ordering::SeqCst));
1125        // Only the layers that entered before the short-circuit unwind;
1126        // neither the short-circuiting layer nor the ones past it run
1127        // after-hooks.
1128        assert_eq!(trace.entries(), vec!["L1:before:victim", "L1:after:victim"]);
1129    }
1130
1131    /// After-hook short-circuits with a replacement result.
1132    struct Replace;
1133
1134    #[async_trait]
1135    impl Middleware for Replace {
1136        fn name(&self) -> &str {
1137            "replace"
1138        }
1139
1140        async fn after_node(
1141            &self,
1142            _call: &NodeCall,
1143            _output: &mut NodeOutput,
1144        ) -> Decision<NodeOutput> {
1145            Decision::ShortCircuit(NodeOutput::update("x", json!("replaced")))
1146        }
1147    }
1148
1149    #[tokio::test]
1150    async fn after_hook_short_circuit_replaces_result_and_skips_outer_layers() {
1151        let trace = Trace::default();
1152        let chain = MiddlewareChain::new()
1153            .layer(Recorder {
1154                id: "L1",
1155                trace: trace.clone(),
1156            })
1157            .layer(Replace);
1158
1159        let mut call = NodeCall::new("t-1", "node-a", 0, State::new());
1160        let result = chain
1161            .run_node(&mut call, |_call| async {
1162                Ok(NodeOutput::update("x", json!("original")))
1163            })
1164            .await
1165            .unwrap();
1166
1167        assert_eq!(result.updates.get("x"), Some(&json!("replaced")));
1168        // L2's after-hook replaced the result; L1's after-hook never ran.
1169        assert_eq!(trace.entries(), vec!["L1:before:node-a"]);
1170    }
1171
1172    /// A mock model that reports how many messages it received.
1173    struct CountingModel {
1174        seen: Arc<Mutex<Option<usize>>>,
1175    }
1176
1177    #[async_trait]
1178    impl ChatModel for CountingModel {
1179        async fn chat(&self, messages: &[ChatMessage], _tools: &[Value]) -> Result<ChatResponse> {
1180            *self.seen.lock().unwrap() = Some(messages.len());
1181            Ok(ChatResponse {
1182                message: ChatMessage::assistant(format!("saw {} messages", messages.len())),
1183                model: None,
1184                usage: None,
1185            })
1186        }
1187    }
1188
1189    /// Injects a system message inbound, rewrites content outbound.
1190    struct ModelMutate;
1191
1192    #[async_trait]
1193    impl Middleware for ModelMutate {
1194        fn name(&self) -> &str {
1195            "model_mutate"
1196        }
1197
1198        async fn before_model(&self, call: &mut ModelCall) -> Decision<ChatResponse> {
1199            call.messages_mut().insert(0, ChatMessage::system("rules"));
1200            Decision::Continue
1201        }
1202
1203        async fn after_model(
1204            &self,
1205            _call: &ModelCall,
1206            response: &mut ChatResponse,
1207        ) -> Decision<ChatResponse> {
1208            response.message.content = Some("intercepted".into());
1209            Decision::Continue
1210        }
1211    }
1212
1213    #[tokio::test]
1214    async fn model_chain_mutates_request_and_response() {
1215        let seen = Arc::new(Mutex::new(None));
1216        let model = MiddlewareChatModel::new(
1217            Arc::new(CountingModel { seen: seen.clone() }),
1218            MiddlewareChain::new().layer(ModelMutate),
1219        )
1220        .thread("t-1")
1221        .node("agent");
1222
1223        let response = model.chat(&[ChatMessage::user("hi")], &[]).await.unwrap();
1224
1225        // The injected system message reached the inner model; the
1226        // after-hook rewrite reached the caller.
1227        assert_eq!(*seen.lock().unwrap(), Some(2));
1228        assert_eq!(response.message.content.as_deref(), Some("intercepted"));
1229    }
1230
1231    /// Rejects every model call.
1232    struct ModelReject;
1233
1234    #[async_trait]
1235    impl Middleware for ModelReject {
1236        fn name(&self) -> &str {
1237            "model_reject"
1238        }
1239
1240        async fn before_model(&self, _call: &mut ModelCall) -> Decision<ChatResponse> {
1241            Decision::Reject(Rejection::new(
1242                self.name(),
1243                InterceptPoint::ModelCall,
1244                "model_blocked",
1245            ))
1246        }
1247    }
1248
1249    #[tokio::test]
1250    async fn model_reject_skips_inner_model() {
1251        let seen = Arc::new(Mutex::new(None));
1252        let model = MiddlewareChatModel::new(
1253            Arc::new(CountingModel { seen: seen.clone() }),
1254            MiddlewareChain::new().layer(ModelReject),
1255        );
1256
1257        let err = model.chat(&[], &[]).await.unwrap_err();
1258        match err {
1259            RustyError::Llm(message) => {
1260                assert!(
1261                    message.contains(
1262                        "rejected by middleware `model_reject` at model_call: model_blocked"
1263                    ),
1264                    "got: {message}"
1265                );
1266            }
1267            other => panic!("expected RustyError::Llm, got {other:?}"),
1268        }
1269        assert_eq!(*seen.lock().unwrap(), None);
1270    }
1271
1272    /// Short-circuits every model call with a canned response.
1273    struct ModelCache;
1274
1275    #[async_trait]
1276    impl Middleware for ModelCache {
1277        fn name(&self) -> &str {
1278            "model_cache"
1279        }
1280
1281        async fn before_model(&self, _call: &mut ModelCall) -> Decision<ChatResponse> {
1282            Decision::ShortCircuit(ChatResponse {
1283                message: ChatMessage::assistant("cached"),
1284                model: None,
1285                usage: None,
1286            })
1287        }
1288    }
1289
1290    #[tokio::test]
1291    async fn model_short_circuit_returns_substitute_response() {
1292        let seen = Arc::new(Mutex::new(None));
1293        let model = MiddlewareChatModel::new(
1294            Arc::new(CountingModel { seen: seen.clone() }),
1295            MiddlewareChain::new().layer(ModelCache),
1296        );
1297
1298        let response = model.chat(&[], &[]).await.unwrap();
1299        assert_eq!(response.message.content.as_deref(), Some("cached"));
1300        assert_eq!(*seen.lock().unwrap(), None);
1301    }
1302
1303    /// A wrapper with an empty chain must delegate untouched.
1304    #[tokio::test]
1305    async fn model_wrapper_with_empty_chain_delegates() {
1306        let seen = Arc::new(Mutex::new(None));
1307        let model = MiddlewareChatModel::new(
1308            Arc::new(CountingModel { seen: seen.clone() }),
1309            MiddlewareChain::new(),
1310        );
1311        let response = model.chat(&[ChatMessage::user("hi")], &[]).await.unwrap();
1312        assert_eq!(response.message.content.as_deref(), Some("saw 1 messages"));
1313        assert_eq!(*seen.lock().unwrap(), Some(1));
1314    }
1315
1316    struct EchoTool;
1317
1318    #[async_trait]
1319    impl crate::tool::Tool for EchoTool {
1320        fn name(&self) -> &str {
1321            "echo"
1322        }
1323        fn description(&self) -> &str {
1324            "Echoes its `text` argument."
1325        }
1326        fn parameters_schema(&self) -> Value {
1327            json!({"type": "object", "properties": {"text": {"type": "string"}}})
1328        }
1329        async fn call(&self, args: Value) -> Result<Value> {
1330            Ok(json!(args.get("text").cloned().unwrap_or(Value::Null)))
1331        }
1332    }
1333
1334    struct DangerTool;
1335
1336    #[async_trait]
1337    impl crate::tool::Tool for DangerTool {
1338        fn name(&self) -> &str {
1339            "danger"
1340        }
1341        fn description(&self) -> &str {
1342            "Must never run."
1343        }
1344        fn parameters_schema(&self) -> Value {
1345            json!({"type": "object"})
1346        }
1347        async fn call(&self, _args: Value) -> Result<Value> {
1348            panic!("blocklisted tool executed");
1349        }
1350    }
1351
1352    fn echo_registry() -> crate::tool::ToolRegistry {
1353        let mut registry = crate::tool::ToolRegistry::new();
1354        registry.register(EchoTool);
1355        registry.register(DangerTool);
1356        registry
1357    }
1358
1359    #[tokio::test]
1360    async fn blocklist_rejects_blocked_tool_and_passes_allowed() {
1361        let executor = crate::tool::ToolExecutor::new(echo_registry())
1362            .with_middleware(MiddlewareChain::new().layer(ToolCallBlocklist::new(["danger"])));
1363
1364        let calls = vec![
1365            ToolCall::new("c1", "echo", json!({"text": "hello"})),
1366            ToolCall::new("c2", "danger", json!({})),
1367        ];
1368        let results = executor.execute_batch(&calls).await;
1369
1370        assert_eq!(results.len(), 2);
1371        assert_eq!(results[0].content.as_deref(), Some("hello"));
1372        let blocked = results[1].content.as_deref().unwrap();
1373        assert!(blocked.starts_with("ERROR:"), "got: {blocked}");
1374        assert!(blocked.contains("tool_call_blocklist"), "got: {blocked}");
1375        assert!(blocked.contains("tool_blocked"), "got: {blocked}");
1376    }
1377
1378    /// Rewrites tool arguments inbound.
1379    struct ArgsRewrite;
1380
1381    #[async_trait]
1382    impl Middleware for ArgsRewrite {
1383        fn name(&self) -> &str {
1384            "args_rewrite"
1385        }
1386
1387        async fn before_tool(&self, call: &mut ToolInvocation) -> Decision<Value> {
1388            call.set_arguments(json!({"text": "mutated"}));
1389            Decision::Continue
1390        }
1391    }
1392
1393    #[tokio::test]
1394    async fn tool_argument_mutation_propagates_to_tool() {
1395        let executor = crate::tool::ToolExecutor::new(echo_registry())
1396            .with_middleware(MiddlewareChain::new().layer(ArgsRewrite));
1397
1398        let calls = vec![ToolCall::new("c1", "echo", json!({"text": "original"}))];
1399        let results = executor.execute_batch(&calls).await;
1400        assert_eq!(results[0].content.as_deref(), Some("mutated"));
1401    }
1402
1403    /// Answers tool calls from a cache without executing them.
1404    struct ToolCache;
1405
1406    #[async_trait]
1407    impl Middleware for ToolCache {
1408        fn name(&self) -> &str {
1409            "tool_cache"
1410        }
1411
1412        async fn before_tool(&self, _call: &mut ToolInvocation) -> Decision<Value> {
1413            Decision::ShortCircuit(json!("cached"))
1414        }
1415    }
1416
1417    #[tokio::test]
1418    async fn tool_short_circuit_returns_substitute_result() {
1419        let executor = crate::tool::ToolExecutor::new(echo_registry())
1420            .with_middleware(MiddlewareChain::new().layer(ToolCache));
1421
1422        let calls = vec![ToolCall::new("c1", "echo", json!({"text": "ignored"}))];
1423        let results = executor.execute_batch(&calls).await;
1424        assert_eq!(results[0].content.as_deref(), Some("cached"));
1425    }
1426
1427    /// Rewrites the tool result outbound.
1428    struct ResultRewrite;
1429
1430    #[async_trait]
1431    impl Middleware for ResultRewrite {
1432        fn name(&self) -> &str {
1433            "result_rewrite"
1434        }
1435
1436        async fn after_tool(&self, _call: &ToolInvocation, result: &mut Value) -> Decision<Value> {
1437            *result = json!("rewritten");
1438            Decision::Continue
1439        }
1440    }
1441
1442    #[tokio::test]
1443    async fn tool_result_mutation_propagates_to_caller() {
1444        let executor = crate::tool::ToolExecutor::new(echo_registry())
1445            .with_middleware(MiddlewareChain::new().layer(ResultRewrite));
1446
1447        let calls = vec![ToolCall::new("c1", "echo", json!({"text": "original"}))];
1448        let results = executor.execute_batch(&calls).await;
1449        assert_eq!(results[0].content.as_deref(), Some("rewritten"));
1450    }
1451
1452    /// Records tool hooks for order proofs.
1453    struct ToolRecorder {
1454        id: &'static str,
1455        trace: Trace,
1456    }
1457
1458    #[async_trait]
1459    impl Middleware for ToolRecorder {
1460        fn name(&self) -> &str {
1461            self.id
1462        }
1463
1464        async fn before_tool(&self, call: &mut ToolInvocation) -> Decision<Value> {
1465            self.trace
1466                .record(format!("{}:before:{}", self.id, call.name()));
1467            Decision::Continue
1468        }
1469
1470        async fn after_tool(&self, call: &ToolInvocation, _result: &mut Value) -> Decision<Value> {
1471            self.trace
1472                .record(format!("{}:after:{}", self.id, call.name()));
1473            Decision::Continue
1474        }
1475    }
1476
1477    #[tokio::test]
1478    async fn tool_hooks_follow_onion_order() {
1479        let trace = Trace::default();
1480        let executor = crate::tool::ToolExecutor::new(echo_registry()).with_middleware(
1481            MiddlewareChain::new()
1482                .layer(ToolRecorder {
1483                    id: "L1",
1484                    trace: trace.clone(),
1485                })
1486                .layer(ToolRecorder {
1487                    id: "L2",
1488                    trace: trace.clone(),
1489                }),
1490        );
1491
1492        let calls = vec![ToolCall::new("c1", "echo", json!({"text": "hi"}))];
1493        let results = executor.execute_batch(&calls).await;
1494        assert_eq!(results[0].content.as_deref(), Some("hi"));
1495        assert_eq!(
1496            trace.entries(),
1497            vec![
1498                "L1:before:echo",
1499                "L2:before:echo",
1500                "L2:after:echo",
1501                "L1:after:echo"
1502            ]
1503        );
1504    }
1505
1506    #[tokio::test]
1507    async fn request_logger_passes_everything_through() {
1508        let chain = MiddlewareChain::new().layer(RequestLogger::new());
1509
1510        let mut node_call = NodeCall::new("t-1", "node-a", 0, State::new());
1511        let node_result = chain
1512            .run_node(&mut node_call, |_call| async {
1513                Ok(NodeOutput::update("x", json!(1)))
1514            })
1515            .await
1516            .unwrap();
1517        assert_eq!(node_result.updates.get("x"), Some(&json!(1)));
1518
1519        let mut model_call = ModelCall::new("t-1", "agent", vec![ChatMessage::user("hi")], vec![]);
1520        let model_result = chain
1521            .run_model(&mut model_call, |_call| async {
1522                Ok(ChatResponse {
1523                    message: ChatMessage::assistant("hello"),
1524                    model: None,
1525                    usage: None,
1526                })
1527            })
1528            .await
1529            .unwrap();
1530        assert_eq!(model_result.message.content.as_deref(), Some("hello"));
1531
1532        let mut tool_call =
1533            ToolInvocation::new("t-1", "tools", ToolCall::new("c1", "echo", json!({})));
1534        let tool_result = chain
1535            .run_tool(&mut tool_call, |_call| async { Ok(json!("done")) })
1536            .await
1537            .unwrap();
1538        assert_eq!(tool_result, json!("done"));
1539    }
1540
1541    #[test]
1542    fn rejection_serde_roundtrip_display_and_error_mapping() {
1543        let rejection = Rejection::new(
1544            "tool_call_blocklist",
1545            InterceptPoint::ToolCall,
1546            "tool_blocked",
1547        )
1548        .with_detail("tool `rm_rf` is blocked by policy");
1549        let back: Rejection =
1550            serde_json::from_str(&serde_json::to_string(&rejection).unwrap()).unwrap();
1551        assert_eq!(rejection, back);
1552
1553        let msg = rejection.to_string();
1554        assert!(msg.contains("tool_call_blocklist"), "got: {msg}");
1555        assert!(msg.contains("tool_call"), "got: {msg}");
1556        assert!(msg.contains("tool_blocked"), "got: {msg}");
1557        assert_eq!(format!("{}", rejection.point), "tool_call");
1558
1559        // The taxonomy mapping: each interception point lands on its
1560        // existing error variant, carrying the canonical Display form.
1561        for (point, expect) in [
1562            (InterceptPoint::NodeRun, "node error"),
1563            (InterceptPoint::ModelCall, "llm error"),
1564            (InterceptPoint::ToolCall, "tool error"),
1565        ] {
1566            let err = Rejection::new("m", point, "r").into_error();
1567            assert!(
1568                err.to_string().starts_with(expect),
1569                "{point}: expected prefix `{expect}`, got: {err}"
1570            );
1571            assert!(err.to_string().contains("rejected by middleware `m`"));
1572        }
1573    }
1574
1575    #[test]
1576    fn chain_debug_lists_layer_names() {
1577        let chain = MiddlewareChain::new()
1578            .layer(RequestLogger::new())
1579            .layer(ToolCallBlocklist::new(["danger"]));
1580        let debug = format!("{chain:?}");
1581        assert!(debug.contains("request_logger"), "got: {debug}");
1582        assert!(debug.contains("tool_call_blocklist"), "got: {debug}");
1583    }
1584
1585    // ---------- instantiate_composition (R0.11 wave 4) ----------
1586
1587    fn layer(name: &str, config: Option<Value>) -> MiddlewareLayerConfig {
1588        MiddlewareLayerConfig {
1589            layer: name.to_owned(),
1590            config,
1591        }
1592    }
1593
1594    #[test]
1595    fn instantiate_builds_the_journaled_order() {
1596        let chain = instantiate_composition(&[
1597            layer("request_logger", None),
1598            layer(
1599                "tool_call_blocklist",
1600                Some(json!({"blocked": ["shell", "fs_write"], "reason": "policy_denied"})),
1601            ),
1602        ])
1603        .unwrap();
1604        assert_eq!(
1605            chain.names().collect::<Vec<_>>(),
1606            ["request_logger", "tool_call_blocklist"]
1607        );
1608        // The order *is* the artifact: the reversed composition builds the
1609        // reversed chain.
1610        let reversed = instantiate_composition(&[
1611            layer("tool_call_blocklist", Some(json!({"blocked": ["shell"]}))),
1612            layer("request_logger", None),
1613        ])
1614        .unwrap();
1615        assert_eq!(
1616            reversed.names().collect::<Vec<_>>(),
1617            ["tool_call_blocklist", "request_logger"]
1618        );
1619        // An empty composition instantiates an empty chain — pass-through,
1620        // not an error.
1621        assert!(instantiate_composition(&[]).unwrap().is_empty());
1622    }
1623
1624    #[tokio::test]
1625    async fn instantiated_blocklist_enforces_its_config() {
1626        // The chain is not a name list: the instantiated layer enforces
1627        // the config the composition declared.
1628        let chain = instantiate_composition(&[layer(
1629            "tool_call_blocklist",
1630            Some(json!({"blocked": ["shell"]})),
1631        )])
1632        .unwrap();
1633        let mut call = ToolInvocation::new(
1634            "t-1",
1635            "node-a",
1636            ToolCall {
1637                id: "c-1".into(),
1638                name: "shell".into(),
1639                arguments: json!({}),
1640            },
1641        );
1642        let err = chain
1643            .run_tool(&mut call, |_call| async { Ok(json!("ran")) })
1644            .await
1645            .unwrap_err();
1646        // Tool rejections surface through the taxonomy as RustyError::Tool
1647        // carrying the Rejection's canonical Display (the typed Rejection's
1648        // `detail` stays at the middleware API).
1649        assert!(
1650            err.to_string().contains(
1651                "rejected by middleware `tool_call_blocklist` at tool_call: tool_blocked"
1652            ),
1653            "got: {err}"
1654        );
1655    }
1656
1657    #[test]
1658    fn instantiate_refuses_what_the_vocabulary_cannot_honor() {
1659        // Unknown layer: the closed set never grows by accepting unknown
1660        // names at resolution time.
1661        let err = instantiate_composition(&[layer("otel_tracer", None)]).unwrap_err();
1662        assert!(err.to_string().contains("otel_tracer"), "got: {err}");
1663        assert!(
1664            err.to_string().contains("compiled-in vocabulary"),
1665            "got: {err}"
1666        );
1667
1668        // A config on the config-free layer: evidence the chain cannot
1669        // honor, refused rather than silently ignored.
1670        let err =
1671            instantiate_composition(&[layer("request_logger", Some(json!({"level": "debug"})))])
1672                .unwrap_err();
1673        assert!(err.to_string().contains("request_logger"), "got: {err}");
1674
1675        // The blocklist without its config: the policy is the config, so
1676        // a config-free blocklist blocks nothing and means nothing.
1677        let err = instantiate_composition(&[layer("tool_call_blocklist", None)]).unwrap_err();
1678        assert!(err.to_string().contains("requires a config"), "got: {err}");
1679
1680        // Malformed config: `blocked` must be a string list.
1681        let err = instantiate_composition(&[layer(
1682            "tool_call_blocklist",
1683            Some(json!({"blocked": "shell"})),
1684        )])
1685        .unwrap_err();
1686        assert!(err.to_string().contains("malformed"), "got: {err}");
1687    }
1688}