Skip to main content

ag_ui/server/
transform.rs

1//! The one extension point: rewriting the event stream on its way out.
2//!
3//! Event observers, filters and rewriters implement [`StreamTransformer`].
4//! Built-in transformers include [`ToolResultToState`] and
5//! [`SubagentVisibility`].
6//!
7//! Transformers run in the order they were added, each seeing what the previous
8//! one produced, before the ordering verifier sees anything. That order is what
9//! makes [`FilterToolCalls`] safe: the verifier never sees the half of a tool
10//! call that was dropped.
11//!
12//! ```
13//! # use ag_ui::server::{FilterToolCalls, TransformerChain, ToolResultToState};
14//! let chain = TransformerChain::new()
15//!     .with(FilterToolCalls::deny(["internal_debug"]))
16//!     .with(ToolResultToState::snapshot("load_document").replacing());
17//! assert_eq!(chain.len(), 2);
18//! ```
19
20use std::collections::{HashMap, HashSet};
21
22use crate::{Event, MessageId, PatchOperation, SubagentRunId, ToolCallId};
23use serde_json::Value;
24
25/// Rewrites events on their way from an agent to the transport.
26///
27/// # Contract
28///
29/// Returning an empty `Vec` drops the event. Returning several events splices
30/// them in, in order. A transformer that drops the start of something must drop
31/// its continuation and terminator too. The verifier cannot identify every
32/// orphaned ID-less chunk after filtering. Normalize chunks first, or track
33/// the producer's open streams before deciding which chunks to drop.
34pub trait StreamTransformer: Send {
35    /// Rewrites one event into zero or more events.
36    fn transform(&mut self, event: Event) -> Vec<Event>;
37}
38
39/// Transformers applied in sequence.
40///
41/// An empty chain is free: the run skips it entirely rather than allocating a
42/// `Vec` per event.
43#[derive(Default)]
44pub struct TransformerChain {
45    transformers: Vec<Box<dyn StreamTransformer>>,
46}
47
48impl std::fmt::Debug for TransformerChain {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.debug_struct("TransformerChain")
51            .field("len", &self.transformers.len())
52            .finish()
53    }
54}
55
56impl TransformerChain {
57    /// An empty chain.
58    pub fn new() -> Self {
59        Self::default()
60    }
61
62    /// Appends a transformer, returning the chain for further building.
63    #[must_use]
64    pub fn with(mut self, transformer: impl StreamTransformer + 'static) -> Self {
65        self.push(transformer);
66        self
67    }
68
69    /// Appends a transformer.
70    pub fn push(&mut self, transformer: impl StreamTransformer + 'static) {
71        self.transformers.push(Box::new(transformer));
72    }
73
74    /// How many transformers are in the chain.
75    pub fn len(&self) -> usize {
76        self.transformers.len()
77    }
78
79    /// Whether the chain would pass every event through untouched.
80    pub fn is_empty(&self) -> bool {
81        self.transformers.is_empty()
82    }
83
84    /// Runs `event` through every transformer in order.
85    pub fn transform(&mut self, event: Event) -> Vec<Event> {
86        let mut current = vec![event];
87        for transformer in &mut self.transformers {
88            let mut next = Vec::with_capacity(current.len());
89            for event in current.drain(..) {
90                next.extend(transformer.transform(event));
91            }
92            current = next;
93            if current.is_empty() {
94                break;
95            }
96        }
97        current
98    }
99}
100
101impl StreamTransformer for TransformerChain {
102    fn transform(&mut self, event: Event) -> Vec<Event> {
103        Self::transform(self, event)
104    }
105}
106
107/// Which side of the list passes.
108#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
109enum FilterMode {
110    Allow,
111    Deny,
112}
113
114/// Drops whole tool calls by tool name.
115///
116/// Both halves of a call are removed — `TOOL_CALL_START`, its `TOOL_CALL_ARGS`,
117/// the `TOOL_CALL_END`, the `TOOL_CALL_RESULT` and any encrypted reasoning blob
118/// attached to it — so what reaches the client is a stream that never mentions
119/// the tool.
120///
121/// ```
122/// # use ag_ui::Event;
123/// # use ag_ui::server::{FilterToolCalls, StreamTransformer};
124/// let mut filter = FilterToolCalls::deny(["secret_tool"]);
125/// assert!(filter.transform(Event::tool_call_start("c1", "secret_tool")).is_empty());
126/// assert!(filter.transform(Event::tool_call_args("c1", "{}")).is_empty());
127/// assert_eq!(filter.transform(Event::tool_call_start("c2", "public")).len(), 1);
128/// ```
129#[derive(Clone, Debug)]
130pub struct FilterToolCalls {
131    mode: FilterMode,
132    names: HashSet<String>,
133    /// Every named call's verdict survives its end for a later result.
134    dropped: HashSet<ToolCallId>,
135    call_names: HashMap<ToolCallId, String>,
136    /// The producer's open streams, including calls removed from the output.
137    /// A bare chunk must be resolved here, before filtering can make it look
138    /// like a continuation of a different call to the consumer.
139    streams: Streams,
140}
141
142impl FilterToolCalls {
143    /// Passes only calls to the named tools.
144    pub fn allow<I, T>(names: I) -> Self
145    where
146        I: IntoIterator<Item = T>,
147        T: Into<String>,
148    {
149        Self::new(FilterMode::Allow, names)
150    }
151
152    /// Passes everything except calls to the named tools.
153    pub fn deny<I, T>(names: I) -> Self
154    where
155        I: IntoIterator<Item = T>,
156        T: Into<String>,
157    {
158        Self::new(FilterMode::Deny, names)
159    }
160
161    fn new<I, T>(mode: FilterMode, names: I) -> Self
162    where
163        I: IntoIterator<Item = T>,
164        T: Into<String>,
165    {
166        Self {
167            mode,
168            names: names.into_iter().map(Into::into).collect(),
169            dropped: HashSet::new(),
170            call_names: HashMap::new(),
171            streams: Streams::default(),
172        }
173    }
174
175    fn passes(&self, name: &str) -> bool {
176        match self.mode {
177            FilterMode::Allow => self.names.contains(name),
178            FilterMode::Deny => !self.names.contains(name),
179        }
180    }
181
182    /// Records the verdict for a call and reports whether it should be dropped.
183    fn judge(&mut self, id: &ToolCallId, name: &str) -> bool {
184        if let Some(original) = self.call_names.get(id) {
185            // The consumer keeps the name from the first chunk with this id.
186            // A later name cannot reclassify its arguments as another tool.
187            if original != name {
188                self.dropped.insert(id.clone());
189            }
190            return self.dropped.contains(id);
191        }
192        self.call_names.insert(id.clone(), name.to_owned());
193        let drop = !self.passes(name);
194        if drop {
195            self.dropped.insert(id.clone());
196        }
197        drop
198    }
199
200    fn dropped_or_unknown(&self, id: &ToolCallId) -> bool {
201        !self.call_names.contains_key(id) || self.dropped.contains(id)
202    }
203}
204
205impl StreamTransformer for FilterToolCalls {
206    fn transform(&mut self, event: Event) -> Vec<Event> {
207        let tag = event.subagent_run_id().cloned();
208        let bare_tool = match &event {
209            Event::ToolCallChunk(chunk) if chunk.tool_call_id.is_none() => self
210                .streams
211                .resolve(Family::Tool, &chunk.subagent_run_id)
212                .map(|(_, stream)| ToolCallId::new(stream.id)),
213            _ => None,
214        };
215        let drop = match &event {
216            Event::ToolCallStart(payload) => {
217                self.judge(&payload.tool_call_id, &payload.tool_call_name)
218            }
219            Event::ToolCallChunk(payload) => match (&payload.tool_call_id, &payload.tool_call_name)
220            {
221                (Some(id), Some(name)) => self.judge(id, name),
222                (Some(id), None) => self.dropped_or_unknown(id),
223                (None, name) => match bare_tool.as_ref() {
224                    Some(id) => {
225                        if name.as_ref().is_some_and(|name| {
226                            self.call_names
227                                .get(id)
228                                .is_none_or(|original| original != name)
229                        }) {
230                            self.dropped.insert(id.clone());
231                        }
232                        self.dropped_or_unknown(id)
233                    }
234                    None => true,
235                },
236            },
237            Event::ToolCallArgs(payload) => self.dropped_or_unknown(&payload.tool_call_id),
238            Event::ToolCallEnd(payload) => self.dropped_or_unknown(&payload.tool_call_id),
239            Event::ToolCallResult(payload) => self.dropped_or_unknown(&payload.tool_call_id),
240            Event::ReasoningEncryptedValue(payload) => {
241                payload.subtype == crate::ReasoningEncryptedValueSubtype::ToolCall && {
242                    let id = ToolCallId::new(&payload.entity_id);
243                    self.dropped_or_unknown(&id)
244                }
245            }
246            _ => false,
247        };
248
249        // Observe the unfiltered input. A removed start still changes where
250        // the producer's later ID-less chunks belong.
251        let owner = tag.clone().or_else(|| {
252            SubagentFilter::entity(&event)
253                .and_then(|(family, id)| self.streams.owner_of_open(family, id))
254        });
255        self.streams.observe(&event, &owner, &tag);
256
257        if drop { Vec::new() } else { vec![event] }
258    }
259}
260
261/// How a promoted tool result reaches the client's state.
262#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
263enum StateForm {
264    /// The result is the new state.
265    Snapshot,
266    /// The result is an RFC 6902 patch against the current state.
267    Delta,
268}
269
270/// Promotes a named tool's result into a state event.
271///
272/// A tool whose job is to produce state — `load_document`, `set_filters` —
273/// otherwise forces the agent to emit the result and then publish the state by
274/// hand. This transformer does it: when `tool_name` returns, its JSON content
275/// becomes a `STATE_SNAPSHOT` or a `STATE_DELTA`.
276///
277/// The result event is kept by default so the client still sees the tool
278/// completed; [`replacing`](Self::replacing) drops it instead. Content that is
279/// not JSON of the expected shape is left alone — a malformed result must not
280/// take down the run.
281///
282/// ```
283/// # use ag_ui::Event;
284/// # use ag_ui::server::{StreamTransformer, ToolResultToState};
285/// let mut promote = ToolResultToState::snapshot("load_document").replacing();
286/// promote.transform(Event::tool_call_start("c1", "load_document"));
287/// let out = promote.transform(Event::tool_call_result("m1", "c1", r#"{"title":"Notes"}"#));
288/// assert_eq!(out, vec![Event::state_snapshot(serde_json::json!({"title": "Notes"}))]);
289/// ```
290#[derive(Clone, Debug)]
291pub struct ToolResultToState {
292    tool_name: String,
293    form: StateForm,
294    keep_result: bool,
295    names: HashMap<ToolCallId, String>,
296}
297
298impl ToolResultToState {
299    /// Turns `tool_name`'s result into a `STATE_SNAPSHOT`.
300    pub fn snapshot(tool_name: impl Into<String>) -> Self {
301        Self::new(tool_name, StateForm::Snapshot)
302    }
303
304    /// Turns `tool_name`'s result into a `STATE_DELTA`. The result content must
305    /// be a JSON array of RFC 6902 operations.
306    pub fn delta(tool_name: impl Into<String>) -> Self {
307        Self::new(tool_name, StateForm::Delta)
308    }
309
310    fn new(tool_name: impl Into<String>, form: StateForm) -> Self {
311        Self {
312            tool_name: tool_name.into(),
313            form,
314            keep_result: true,
315            names: HashMap::new(),
316        }
317    }
318
319    /// Drops the `TOOL_CALL_RESULT` instead of emitting it alongside the state
320    /// event.
321    #[must_use]
322    pub fn replacing(mut self) -> Self {
323        self.keep_result = false;
324        self
325    }
326
327    fn state_event(&self, content: &str) -> Option<Event> {
328        match self.form {
329            StateForm::Snapshot => serde_json::from_str::<Value>(content)
330                .ok()
331                .map(Event::state_snapshot),
332            StateForm::Delta => serde_json::from_str::<Vec<PatchOperation>>(content)
333                .ok()
334                .map(Event::state_delta),
335        }
336    }
337}
338
339impl StreamTransformer for ToolResultToState {
340    fn transform(&mut self, event: Event) -> Vec<Event> {
341        match &event {
342            Event::ToolCallStart(payload) => {
343                if payload.tool_call_name == self.tool_name {
344                    self.names
345                        .insert(payload.tool_call_id.clone(), payload.tool_call_name.clone());
346                }
347            }
348            Event::ToolCallChunk(payload) => {
349                match (&payload.tool_call_id, &payload.tool_call_name) {
350                    (Some(id), Some(name)) if name == &self.tool_name => {
351                        self.names.insert(id.clone(), name.clone());
352                    }
353                    _ => {}
354                }
355            }
356            Event::ToolCallResult(payload) => {
357                let promoted = self
358                    .names
359                    .remove(&payload.tool_call_id)
360                    .and_then(|_| {
361                        payload
362                            .content
363                            .as_text()
364                            .and_then(|text| self.state_event(text))
365                    })
366                    .map(|mut state| {
367                        // Provenance travels with the state: a subagent's
368                        // result promoted is the subagent's publish.
369                        if let Some(id) = &payload.subagent_run_id {
370                            state.set_subagent_run_id(id.clone());
371                        }
372                        state
373                    });
374                if let Some(state) = promoted {
375                    return if self.keep_result {
376                        vec![event, state]
377                    } else {
378                        vec![state]
379                    };
380                }
381            }
382            _ => {}
383        }
384        vec![event]
385    }
386}
387
388/// What a consumer sees of an agent's subagents.
389///
390/// [`Attributed`](Self::Attributed) — the default, and no transformer at all —
391/// sends the stream as the agent emitted it. The other two exist because a
392/// client older than `@ag-ui/client` 0.0.59 rejects the `SUBAGENT_*` event
393/// *types* while decoding: an unknown field is tolerated, an unknown event
394/// type is not, and there is nothing a client can do about it after the
395/// fact. A producer with such consumers must not send them, and this is how
396/// it does not.
397///
398/// Upstream's integrations default to inline and make the full surface
399/// opt-in. This crate defaults the other way, because a transformer that
400/// rewrites the stream is opt-in here like every other: an agent that wrote
401/// `ctx.subagent(..)` meant it, and silently flattening that output would
402/// surprise the caller. Flip it per endpoint when
403/// your consumers are older:
404///
405/// ```
406/// # use ag_ui::RunOutcome;
407/// # use ag_ui::server::{Agent, Result, RunContext, Runner, SubagentVisibility};
408/// # struct MyAgent;
409/// # impl Agent for MyAgent {
410/// #     type State = ();
411/// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
412/// # }
413/// let runner = Runner::new(MyAgent).transformer(SubagentVisibility::inline());
414/// # let _ = runner;
415/// ```
416#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
417pub enum SubagentVisibility {
418    /// The full surface: the lifecycle events, and `subagentRunId` on
419    /// everything a subagent produced.
420    #[default]
421    Attributed,
422    /// The pre-subagent shape: no lifecycle events and no `subagentRunId`
423    /// anywhere — not on events, not on the messages inside
424    /// `MESSAGES_SNAPSHOT` or the `RUN_STARTED` input echo, not on the
425    /// interrupts a paused run reports. A subagent's own text arrives as the
426    /// parent's work. A `*_CHUNK` event that named no id is given the one its
427    /// attribution resolved to, since without the attribution the consumer
428    /// would resolve it differently.
429    ///
430    /// A subagent's steps are dropped rather than flattened. A step brackets
431    /// its own agent's graph, and as the parent's it would either collide
432    /// with an open step of the same name — the common shape: a parent
433    /// `tools` step wrapping the delegation and the child's own `tools`
434    /// inside it — or misdescribe the parent's graph. The lifecycle events
435    /// were the child's structure; so are its steps.
436    Inline,
437    /// Only the parent's own events. Everything a subagent produced is
438    /// dropped — including the result of a call it requested, even when the
439    /// parent executed it, since a result for a call the consumer never saw
440    /// is a protocol error. The converse holds too: a result answering the
441    /// *parent's* call is kept, untagged, whoever executed it — the consumer
442    /// saw the call, and a call left unanswered in the history is what the
443    /// next request would carry back.
444    ///
445    /// The one thing kept is the run's shared state. A `STATE_SNAPSHOT` or
446    /// `STATE_DELTA` a subagent published describes the *thread's* state,
447    /// not the subagent's work: a client that never saw it would mirror a
448    /// stale state and send that back on its next request. It goes out with
449    /// the tag cleared, as the parent's.
450    Hidden,
451}
452
453impl SubagentVisibility {
454    /// The transformer for this mode. [`Attributed`](Self::Attributed) passes
455    /// events through unchanged.
456    pub fn filter(self) -> SubagentFilter {
457        SubagentFilter::new(self)
458    }
459
460    /// The transformer for [`Inline`](Self::Inline).
461    pub fn inline() -> SubagentFilter {
462        Self::Inline.filter()
463    }
464
465    /// The transformer for [`Hidden`](Self::Hidden).
466    pub fn hidden() -> SubagentFilter {
467        Self::Hidden.filter()
468    }
469}
470
471/// The transformer behind [`SubagentVisibility`].
472///
473/// Both modes keep the consuming normalizer's model of the stream — one open
474/// chunk-continuable stream per owner — because a `*_CHUNK` event that names
475/// no id is resolved *through its attribution* on the consuming side, and
476/// stripping the attribution would send it to the wrong stream. Such a chunk
477/// is given the id it resolves to (and, for a tool call, the name the
478/// consumer needs to reopen it) before its tag goes.
479///
480/// [`Hidden`](SubagentVisibility::Hidden) additionally remembers what each
481/// subagent owns — messages, tool calls, activities — for the rest of the
482/// run, not only while they are open, so an untagged continuation, re-open,
483/// patch or result for a subagent's entity is dropped with the rest of it
484/// rather than leaking into the parent's stream. That is the owner-aware
485/// verifier's reading too: the first writer owns the id, and an absent tag
486/// agrees with any owner. An entity the consumer has seen opened keeps that
487/// visibility until it closes, whatever a snapshot says about its owner
488/// meanwhile — a consumer must never be left with a message it saw opened
489/// and never sees closed.
490#[derive(Debug)]
491pub struct SubagentFilter {
492    mode: SubagentVisibility,
493    /// The open streams, per owner.
494    streams: Streams,
495    /// Text message ids a subagent owns, and which.
496    hidden_text: HashMap<MessageId, SubagentRunId>,
497    /// Reasoning ids — the block and the message inside it — a subagent
498    /// owns. A bucket of its own, as the verifiers keep it, so a producer
499    /// that reuses an id across the two kinds is not misread.
500    hidden_reasoning: HashMap<MessageId, SubagentRunId>,
501    /// Tool call ids a subagent owns — or that sit in a message it owns.
502    hidden_tool_calls: HashMap<ToolCallId, SubagentRunId>,
503    /// Every activity seen, and whether a subagent owns it.
504    activities: HashMap<MessageId, bool>,
505    /// What is open, and whether the consumer saw it open.
506    open_visibility: HashMap<(Family, String), bool>,
507    /// Whether the consumer saw each tool call start, for the result that
508    /// may arrive long after the call closed.
509    call_visibility: HashMap<ToolCallId, bool>,
510}
511
512/// The families a `*_CHUNK` event may continue.
513#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
514enum Family {
515    Text,
516    Reasoning,
517    Tool,
518}
519
520/// One open stream, as the consuming normalizer models it.
521#[derive(Clone, Debug)]
522struct Stream {
523    family: Family,
524    id: String,
525    /// What a chunk reopening a tool call on the consuming side must carry.
526    tool_name: Option<String>,
527    parent_message_id: Option<MessageId>,
528}
529
530/// The open streams: one per owner, replaced by the next that owner opens,
531/// closed by a terminator or — for whoever executed it — by a tool result.
532#[derive(Clone, Debug, Default)]
533struct Streams {
534    parent: Option<Stream>,
535    subagents: HashMap<SubagentRunId, Stream>,
536}
537
538/// What a chunk naming no id turned out to be.
539enum Bare {
540    /// Not such a chunk.
541    No,
542    /// Resolved to a stream, and given its id.
543    Resolved {
544        owner: Option<SubagentRunId>,
545        family: Family,
546        id: String,
547    },
548    /// Nothing to resolve it against; the consumer will say so.
549    Unresolved,
550}
551
552impl Streams {
553    /// `owner` now has `stream` open, and nothing else — unless it is the
554    /// same stream, in which case what is known about it is kept.
555    fn open(&mut self, owner: &Option<SubagentRunId>, stream: Stream) {
556        let current = match owner {
557            None => &mut self.parent,
558            Some(owner) => match self.subagents.get_mut(owner) {
559                Some(current) => {
560                    Self::replace(current, stream);
561                    return;
562                }
563                None => {
564                    self.subagents.insert(owner.clone(), stream);
565                    return;
566                }
567            },
568        };
569        match current {
570            Some(current) => Self::replace(current, stream),
571            None => *current = Some(stream),
572        }
573    }
574
575    fn replace(current: &mut Stream, stream: Stream) {
576        if current.family == stream.family && current.id == stream.id {
577            if current.tool_name.is_none() {
578                current.tool_name = stream.tool_name;
579            }
580            if current.parent_message_id.is_none() {
581                current.parent_message_id = stream.parent_message_id;
582            }
583        } else {
584            *current = stream;
585        }
586    }
587
588    fn close_id(&mut self, family: Family, id: &str) {
589        if self
590            .parent
591            .as_ref()
592            .is_some_and(|open| open.family == family && open.id == id)
593        {
594            self.parent = None;
595        }
596        self.subagents
597            .retain(|_, open| !(open.family == family && open.id == id));
598    }
599
600    fn close_owner(&mut self, owner: &Option<SubagentRunId>) {
601        match owner {
602            None => self.parent = None,
603            Some(owner) => {
604                self.subagents.remove(owner);
605            }
606        }
607    }
608
609    fn clear(&mut self) {
610        self.parent = None;
611        self.subagents.clear();
612    }
613
614    /// The subagent under which `id` is open, if it is open under one.
615    fn owner_of_open(&self, family: Family, id: &str) -> Option<SubagentRunId> {
616        self.subagents
617            .iter()
618            .find(|(_, open)| open.family == family && open.id == id)
619            .map(|(owner, _)| owner.clone())
620    }
621
622    /// The stream a chunk naming no id continues — the normalizer's rule:
623    /// the tagged owner's open stream; untagged, the parent's, else the only
624    /// open one.
625    fn resolve(
626        &self,
627        family: Family,
628        tag: &Option<SubagentRunId>,
629    ) -> Option<(Option<SubagentRunId>, Stream)> {
630        let of_family = |open: &&Stream| open.family == family;
631        if let Some(owner) = tag {
632            return self
633                .subagents
634                .get(owner)
635                .filter(of_family)
636                .map(|open| (Some(owner.clone()), open.clone()));
637        }
638        if let Some(open) = self.parent.as_ref().filter(of_family) {
639            return Some((None, open.clone()));
640        }
641        let mut candidates = self
642            .subagents
643            .iter()
644            .filter(|(_, open)| open.family == family);
645        match (candidates.next(), candidates.next()) {
646            (Some((owner, open)), None) => Some((Some(owner.clone()), open.clone())),
647            _ => None,
648        }
649    }
650
651    /// Folds an event with an id into the model. `owner` is whose the event
652    /// is; `tag` is what it carries, which is what a result closes by.
653    fn observe(
654        &mut self,
655        event: &Event,
656        owner: &Option<SubagentRunId>,
657        tag: &Option<SubagentRunId>,
658    ) {
659        let text = |id: &MessageId| Stream {
660            family: Family::Text,
661            id: id.as_str().to_owned(),
662            tool_name: None,
663            parent_message_id: None,
664        };
665        let reasoning = |id: &MessageId| Stream {
666            family: Family::Reasoning,
667            id: id.as_str().to_owned(),
668            tool_name: None,
669            parent_message_id: None,
670        };
671        let tool = |id: &ToolCallId, name: Option<&String>, parent: Option<&MessageId>| Stream {
672            family: Family::Tool,
673            id: id.as_str().to_owned(),
674            tool_name: name.cloned(),
675            parent_message_id: parent.cloned(),
676        };
677        match event {
678            Event::TextMessageStart(e) => self.open(owner, text(&e.message_id)),
679            Event::TextMessageContent(e) => self.open(owner, text(&e.message_id)),
680            Event::TextMessageEnd(e) => self.close_id(Family::Text, e.message_id.as_str()),
681            Event::TextMessageChunk(e) => {
682                if let Some(id) = &e.message_id {
683                    self.open(owner, text(id));
684                }
685            }
686            Event::ReasoningMessageStart(e) => self.open(owner, reasoning(&e.message_id)),
687            Event::ReasoningMessageContent(e) => self.open(owner, reasoning(&e.message_id)),
688            Event::ReasoningMessageEnd(e) => {
689                self.close_id(Family::Reasoning, e.message_id.as_str());
690            }
691            Event::ReasoningEnd(e) => self.close_id(Family::Reasoning, e.message_id.as_str()),
692            Event::ReasoningMessageChunk(e) => {
693                if let Some(id) = &e.message_id {
694                    self.open(owner, reasoning(id));
695                }
696            }
697            Event::ToolCallStart(e) => self.open(
698                owner,
699                tool(
700                    &e.tool_call_id,
701                    Some(&e.tool_call_name),
702                    e.parent_message_id.as_ref(),
703                ),
704            ),
705            Event::ToolCallArgs(e) => self.open(owner, tool(&e.tool_call_id, None, None)),
706            Event::ToolCallEnd(e) => self.close_id(Family::Tool, e.tool_call_id.as_str()),
707            Event::ToolCallChunk(e) => {
708                if let Some(id) = &e.tool_call_id {
709                    self.open(
710                        owner,
711                        tool(id, e.tool_call_name.as_ref(), e.parent_message_id.as_ref()),
712                    );
713                }
714            }
715            // A result answers a call, so the call is over — and the party
716            // answering has moved on from whatever else it had open.
717            Event::ToolCallResult(e) => {
718                self.close_id(Family::Tool, e.tool_call_id.as_str());
719                self.close_owner(tag);
720            }
721            Event::RunFinished(_) | Event::RunError(_) => self.clear(),
722            _ => {}
723        }
724    }
725}
726
727impl SubagentFilter {
728    /// A filter for `mode`.
729    pub fn new(mode: SubagentVisibility) -> Self {
730        Self {
731            mode,
732            streams: Streams::default(),
733            hidden_text: HashMap::new(),
734            hidden_reasoning: HashMap::new(),
735            hidden_tool_calls: HashMap::new(),
736            activities: HashMap::new(),
737            open_visibility: HashMap::new(),
738            call_visibility: HashMap::new(),
739        }
740    }
741
742    /// The mode this filter applies.
743    pub fn mode(&self) -> SubagentVisibility {
744        self.mode
745    }
746
747    /// The stream a stream-bearing event belongs to, if it names one.
748    fn entity(event: &Event) -> Option<(Family, &str)> {
749        Some(match event {
750            Event::TextMessageStart(e) => (Family::Text, e.message_id.as_str()),
751            Event::TextMessageContent(e) => (Family::Text, e.message_id.as_str()),
752            Event::TextMessageEnd(e) => (Family::Text, e.message_id.as_str()),
753            Event::TextMessageChunk(e) => (Family::Text, e.message_id.as_ref()?.as_str()),
754            Event::ReasoningStart(e) => (Family::Reasoning, e.message_id.as_str()),
755            Event::ReasoningMessageStart(e) => (Family::Reasoning, e.message_id.as_str()),
756            Event::ReasoningMessageContent(e) => (Family::Reasoning, e.message_id.as_str()),
757            Event::ReasoningMessageEnd(e) => (Family::Reasoning, e.message_id.as_str()),
758            Event::ReasoningEnd(e) => (Family::Reasoning, e.message_id.as_str()),
759            Event::ReasoningMessageChunk(e) => (Family::Reasoning, e.message_id.as_ref()?.as_str()),
760            Event::ToolCallStart(e) => (Family::Tool, e.tool_call_id.as_str()),
761            Event::ToolCallArgs(e) => (Family::Tool, e.tool_call_id.as_str()),
762            Event::ToolCallEnd(e) => (Family::Tool, e.tool_call_id.as_str()),
763            Event::ToolCallResult(e) => (Family::Tool, e.tool_call_id.as_str()),
764            Event::ToolCallChunk(e) => (Family::Tool, e.tool_call_id.as_ref()?.as_str()),
765            _ => return None,
766        })
767    }
768
769    /// The message a tool call sits in, when the event says.
770    fn carrier(event: &Event) -> Option<&MessageId> {
771        match event {
772            Event::ToolCallStart(e) => e.parent_message_id.as_ref(),
773            Event::ToolCallChunk(e) => e.parent_message_id.as_ref(),
774            _ => None,
775        }
776    }
777
778    /// Whose an event is: its tag; else the recorded owner of its entity —
779    /// for a tool call, the owner of the message that carries it; else
780    /// whoever has that entity open; else the parent.
781    fn owner_for(&self, event: &Event, tag: &Option<SubagentRunId>) -> Option<SubagentRunId> {
782        if tag.is_some() {
783            return tag.clone();
784        }
785        let (family, id) = Self::entity(event)?;
786        let recorded = match family {
787            Family::Text => self.hidden_text.get(&MessageId::new(id)).cloned(),
788            Family::Reasoning => self.hidden_reasoning.get(&MessageId::new(id)).cloned(),
789            Family::Tool => Self::carrier(event)
790                .and_then(|parent| self.hidden_text.get(parent).cloned())
791                .or_else(|| self.hidden_tool_calls.get(&ToolCallId::new(id)).cloned()),
792        };
793        recorded.or_else(|| self.streams.owner_of_open(family, id))
794    }
795
796    /// Gives a chunk naming no id the id its attribution resolves to on the
797    /// consuming side, so that stripping the attribution afterwards cannot
798    /// send it to another stream.
799    fn fill_bare(&self, event: &mut Event, tag: &Option<SubagentRunId>) -> Bare {
800        let family = match event {
801            Event::TextMessageChunk(e) if e.message_id.is_none() => Family::Text,
802            Event::ReasoningMessageChunk(e) if e.message_id.is_none() => Family::Reasoning,
803            Event::ToolCallChunk(e) if e.tool_call_id.is_none() => Family::Tool,
804            _ => return Bare::No,
805        };
806        let Some((owner, stream)) = self.streams.resolve(family, tag) else {
807            return Bare::Unresolved;
808        };
809        let id = stream.id.clone();
810        match event {
811            Event::TextMessageChunk(e) => e.message_id = Some(MessageId::new(&id)),
812            Event::ReasoningMessageChunk(e) => e.message_id = Some(MessageId::new(&id)),
813            Event::ToolCallChunk(e) => {
814                e.tool_call_id = Some(ToolCallId::new(&id));
815                if e.tool_call_name.is_none() {
816                    e.tool_call_name = stream.tool_name;
817                }
818                if e.parent_message_id.is_none() {
819                    e.parent_message_id = stream.parent_message_id;
820                }
821            }
822            _ => unreachable!("matched above"),
823        }
824        Bare::Resolved { owner, family, id }
825    }
826
827    /// Strips the subagent surface from an event, or drops it entirely when
828    /// it *is* the subagent surface — the lifecycle, and a subagent's steps.
829    fn inline(&mut self, mut event: Event) -> Vec<Event> {
830        let tag = event.subagent_run_id().cloned();
831        if let Bare::No = self.fill_bare(&mut event, &tag) {
832            let owner = self.owner_for(&event, &tag);
833            self.streams.observe(&event, &owner, &tag);
834        }
835        let subagents_step =
836            matches!(event, Event::StepStarted(_) | Event::StepFinished(_)) && tag.is_some();
837        if subagents_step {
838            return Vec::new();
839        }
840        match &mut event {
841            Event::SubagentStarted(_) | Event::SubagentFinished(_) | Event::SubagentError(_) => {
842                return Vec::new();
843            }
844            Event::MessagesSnapshot(snapshot) => {
845                for message in &mut snapshot.messages {
846                    message.set_subagent_run_id(None);
847                }
848            }
849            Event::RunStarted(started) => {
850                if let Some(input) = &mut started.input {
851                    for message in &mut input.messages {
852                        message.set_subagent_run_id(None);
853                    }
854                }
855            }
856            Event::RunFinished(finished) => Self::strip_interrupt_tags(finished),
857            _ => {
858                event.clear_subagent_run_id();
859            }
860        }
861        vec![event]
862    }
863
864    /// The interrupts a paused run reports name the subagent that raised
865    /// them, and a consumer that never saw that subagent has no group to
866    /// file them under. The question still stands, so the interrupt stays;
867    /// only the tag goes.
868    fn strip_interrupt_tags(finished: &mut crate::RunFinishedEvent) {
869        if let Some(crate::RunOutcome::Interrupt { interrupts }) = &mut finished.outcome {
870            for interrupt in interrupts {
871                interrupt.subagent_run_id = None;
872            }
873        }
874    }
875
876    /// Keeps the parent's events and drops a subagent's, remembering what
877    /// each subagent owns so that an untagged event is judged by its opener.
878    fn hidden(&mut self, mut event: Event) -> Vec<Event> {
879        let tag = event.subagent_run_id().cloned();
880        let owned = tag.is_some();
881        let keep = match self.fill_bare(&mut event, &tag) {
882            // The chunk continues a stream: it goes where the stream went.
883            Bare::Resolved { owner, family, id } => self
884                .open_visibility
885                .get(&(family, id))
886                .copied()
887                .unwrap_or(owner.is_none()),
888            Bare::Unresolved => !owned,
889            Bare::No => {
890                let owner = self.owner_for(&event, &tag);
891                self.streams.observe(&event, &owner, &tag);
892                self.judge(&event, &tag, owner.as_ref())
893            }
894        };
895        if !keep {
896            return Vec::new();
897        }
898        match &mut event {
899            // Authoritative: the snapshot restates the conversation, so what
900            // it carries is re-read — and what it does not carry is left as
901            // the run established it, as the verifiers leave it.
902            Event::MessagesSnapshot(snapshot) => {
903                self.seed_hidden(&snapshot.messages, true);
904                let hidden_calls = &self.hidden_tool_calls;
905                snapshot
906                    .messages
907                    .retain_mut(|message| Self::show_message(message, hidden_calls));
908            }
909            // History, not a rewrite: what it carries is remembered alongside
910            // what the run has already shown.
911            Event::RunStarted(started) => {
912                if let Some(input) = &mut started.input {
913                    self.seed_hidden(&input.messages, false);
914                    let hidden_calls = &self.hidden_tool_calls;
915                    input
916                        .messages
917                        .retain_mut(|message| Self::show_message(message, hidden_calls));
918                }
919            }
920            Event::StateSnapshot(_)
921            | Event::StateDelta(_)
922            | Event::ToolCallResult(_)
923            | Event::ActivitySnapshot(_)
924            | Event::ActivityDelta(_) => {
925                event.clear_subagent_run_id();
926            }
927            Event::RunFinished(finished) => Self::strip_interrupt_tags(finished),
928            _ => {}
929        }
930        vec![event]
931    }
932
933    /// Whether the consumer sees an event with an id, by who owns it.
934    fn judge(
935        &mut self,
936        event: &Event,
937        tag: &Option<SubagentRunId>,
938        owner: Option<&SubagentRunId>,
939    ) -> bool {
940        let owned = tag.is_some();
941        match event {
942            Event::SubagentStarted(_) | Event::SubagentFinished(_) | Event::SubagentError(_) => {
943                false
944            }
945
946            Event::TextMessageStart(e) => self.opened(Family::Text, &e.message_id, owner),
947            Event::TextMessageChunk(e) => match &e.message_id {
948                Some(id) => self.opened(Family::Text, id, owner),
949                None => unreachable!("a bare chunk was resolved or passed through"),
950            },
951            Event::TextMessageContent(e) => self.continued(Family::Text, &e.message_id, owned),
952            Event::TextMessageEnd(e) => self.closed(Family::Text, &e.message_id, owned),
953
954            Event::ReasoningStart(e) => self.opened(Family::Reasoning, &e.message_id, owner),
955            Event::ReasoningMessageStart(e) => self.opened(Family::Reasoning, &e.message_id, owner),
956            Event::ReasoningMessageChunk(e) => match &e.message_id {
957                Some(id) => self.opened(Family::Reasoning, id, owner),
958                None => unreachable!("a bare chunk was resolved or passed through"),
959            },
960            Event::ReasoningMessageContent(e) => {
961                self.continued(Family::Reasoning, &e.message_id, owned)
962            }
963            Event::ReasoningMessageEnd(e) => self.closed(Family::Reasoning, &e.message_id, owned),
964            Event::ReasoningEnd(e) => self.closed(Family::Reasoning, &e.message_id, owned),
965
966            Event::ToolCallStart(e) => self.call_opened(&e.tool_call_id, owner),
967            Event::ToolCallChunk(e) => match &e.tool_call_id {
968                Some(id) => self.call_opened(id, owner),
969                None => unreachable!("a bare chunk was resolved or passed through"),
970            },
971            Event::ToolCallArgs(e) => self.call_continued(&e.tool_call_id, owned),
972            Event::ToolCallEnd(e) => {
973                let keep = self.call_continued(&e.tool_call_id, owned);
974                self.open_visibility
975                    .remove(&(Family::Tool, e.tool_call_id.as_str().to_owned()));
976                keep
977            }
978            // A result goes where its call went, whoever executed it: one for
979            // a call the consumer never saw is a protocol error, and one for
980            // a call it did see is owed.
981            Event::ToolCallResult(e) => self
982                .call_visibility
983                .get(&e.tool_call_id)
984                .copied()
985                .unwrap_or_else(|| !self.hidden_tool_calls.contains_key(&e.tool_call_id)),
986
987            // An activity is owned by the snapshot that minted it, and only a
988            // replacing snapshot re-mints it — the verifiers' rule. A merge
989            // into a visible activity is kept whoever wrote it, as a result
990            // for a visible call is: the entity is the consumer's to keep
991            // whole.
992            Event::ActivitySnapshot(e) => {
993                let existing = self.activities.get(&e.message_id).copied();
994                let hidden = match existing {
995                    Some(hidden) if !e.replace => hidden,
996                    _ => owned,
997                };
998                self.activities.insert(e.message_id.clone(), hidden);
999                !hidden
1000            }
1001            Event::ActivityDelta(e) => {
1002                !self.activities.get(&e.message_id).copied().unwrap_or(false)
1003            }
1004
1005            // An opaque blob for an entity the consumer never saw goes with
1006            // the entity, as `FilterToolCalls` drops one for a dropped call.
1007            Event::ReasoningEncryptedValue(e) => {
1008                !owned
1009                    && match e.subtype {
1010                        crate::ReasoningEncryptedValueSubtype::ToolCall => !self
1011                            .hidden_tool_calls
1012                            .contains_key(&ToolCallId::new(e.entity_id.clone())),
1013                        crate::ReasoningEncryptedValueSubtype::Message => {
1014                            let id = MessageId::new(e.entity_id.clone());
1015                            !self.hidden_text.contains_key(&id)
1016                                && !self.hidden_reasoning.contains_key(&id)
1017                        }
1018                    }
1019            }
1020
1021            // The thread's state, whoever published it.
1022            Event::StateSnapshot(_) | Event::StateDelta(_) => true,
1023
1024            Event::RunFinished(_) | Event::RunError(_) => {
1025                self.open_visibility.clear();
1026                true
1027            }
1028
1029            _ => !owned,
1030        }
1031    }
1032
1033    fn owners_mut(&mut self, family: Family) -> &mut HashMap<MessageId, SubagentRunId> {
1034        match family {
1035            Family::Text => &mut self.hidden_text,
1036            Family::Reasoning => &mut self.hidden_reasoning,
1037            Family::Tool => unreachable!("tool calls have their own map"),
1038        }
1039    }
1040
1041    fn is_hidden(&self, family: Family, id: &str) -> bool {
1042        match family {
1043            Family::Text => self.hidden_text.contains_key(&MessageId::new(id)),
1044            Family::Reasoning => self.hidden_reasoning.contains_key(&MessageId::new(id)),
1045            Family::Tool => self.hidden_tool_calls.contains_key(&ToolCallId::new(id)),
1046        }
1047    }
1048
1049    /// A message opens under `owner` — the first writer keeps it — and the
1050    /// consumer sees it iff the owner is the parent, unless it is already
1051    /// open, in which case it keeps the visibility it was opened with.
1052    fn opened(&mut self, family: Family, id: &MessageId, owner: Option<&SubagentRunId>) -> bool {
1053        if let Some(owner) = owner {
1054            self.owners_mut(family)
1055                .entry(id.clone())
1056                .or_insert_with(|| owner.clone());
1057        }
1058        *self
1059            .open_visibility
1060            .entry((family, id.as_str().to_owned()))
1061            .or_insert(owner.is_none())
1062    }
1063
1064    fn continued(&self, family: Family, id: &MessageId, owned: bool) -> bool {
1065        !owned
1066            && self
1067                .open_visibility
1068                .get(&(family, id.as_str().to_owned()))
1069                .copied()
1070                .unwrap_or_else(|| !self.is_hidden(family, id.as_str()))
1071    }
1072
1073    fn closed(&mut self, family: Family, id: &MessageId, owned: bool) -> bool {
1074        let keep = self.continued(family, id, owned);
1075        self.open_visibility
1076            .remove(&(family, id.as_str().to_owned()));
1077        keep
1078    }
1079
1080    fn call_opened(&mut self, id: &ToolCallId, owner: Option<&SubagentRunId>) -> bool {
1081        if let Some(owner) = owner {
1082            self.hidden_tool_calls
1083                .entry(id.clone())
1084                .or_insert_with(|| owner.clone());
1085        }
1086        let visible = *self
1087            .open_visibility
1088            .entry((Family::Tool, id.as_str().to_owned()))
1089            .or_insert(owner.is_none());
1090        self.call_visibility.insert(id.clone(), visible);
1091        visible
1092    }
1093
1094    fn call_continued(&self, id: &ToolCallId, owned: bool) -> bool {
1095        !owned
1096            && self
1097                .open_visibility
1098                .get(&(Family::Tool, id.as_str().to_owned()))
1099                .copied()
1100                .unwrap_or_else(|| !self.hidden_tool_calls.contains_key(id))
1101    }
1102
1103    /// Re-reads what a replay says about ownership. Authoritatively — a
1104    /// `MESSAGES_SNAPSHOT` — an untagged message takes its id back for the
1105    /// parent; as history — the `RUN_STARTED` echo — only the subagents'
1106    /// messages are added. A tool message goes where its call went, so one
1107    /// answering a visible call is not hidden however it is tagged.
1108    fn seed_hidden(&mut self, messages: &[crate::Message], authoritative: bool) {
1109        for message in messages {
1110            let id = message.id().clone();
1111            if let crate::Message::Activity(_) = message {
1112                if authoritative || !self.activities.contains_key(&id) {
1113                    self.activities
1114                        .insert(id, message.subagent_run_id().is_some());
1115                }
1116                continue;
1117            }
1118            let owner = match message {
1119                crate::Message::Tool(tool) => {
1120                    self.hidden_tool_calls.get(&tool.tool_call_id).cloned()
1121                }
1122                _ => message.subagent_run_id().cloned(),
1123            };
1124            let calls: Vec<ToolCallId> = match message {
1125                crate::Message::Assistant(assistant) => assistant
1126                    .tool_calls
1127                    .iter()
1128                    .flatten()
1129                    .map(|call| call.id.clone())
1130                    .collect(),
1131                _ => Vec::new(),
1132            };
1133            let family = match message {
1134                crate::Message::Reasoning(_) => Family::Reasoning,
1135                _ => Family::Text,
1136            };
1137            match owner {
1138                Some(owner) => {
1139                    for call in calls {
1140                        self.hidden_tool_calls.insert(call, owner.clone());
1141                    }
1142                    self.owners_mut(family).insert(id, owner);
1143                }
1144                None if authoritative => {
1145                    self.owners_mut(family).remove(&id);
1146                    for call in &calls {
1147                        self.hidden_tool_calls.remove(call);
1148                    }
1149                }
1150                None => {}
1151            }
1152        }
1153    }
1154
1155    /// Whether a replayed message reaches the consumer, stripping the tag
1156    /// from the one kind that may carry one there: a tool message answering
1157    /// a call the consumer saw is the parent's, whoever executed it.
1158    fn show_message(
1159        message: &mut crate::Message,
1160        hidden_calls: &HashMap<ToolCallId, SubagentRunId>,
1161    ) -> bool {
1162        match message {
1163            crate::Message::Tool(tool) => {
1164                if hidden_calls.contains_key(&tool.tool_call_id) {
1165                    return false;
1166                }
1167                tool.subagent_run_id = None;
1168                true
1169            }
1170            _ => message.subagent_run_id().is_none(),
1171        }
1172    }
1173}
1174
1175impl StreamTransformer for SubagentFilter {
1176    fn transform(&mut self, event: Event) -> Vec<Event> {
1177        match self.mode {
1178            SubagentVisibility::Attributed => vec![event],
1179            SubagentVisibility::Inline => self.inline(event),
1180            SubagentVisibility::Hidden => self.hidden(event),
1181        }
1182    }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    use super::*;
1188    use crate::{ReasoningEncryptedValueSubtype, TextMessageRole};
1189    use serde_json::json;
1190
1191    #[test]
1192    fn allow_list_drops_everything_unlisted() {
1193        let mut filter = FilterToolCalls::allow(["search"]);
1194        assert_eq!(
1195            filter
1196                .transform(Event::tool_call_start("c1", "search"))
1197                .len(),
1198            1
1199        );
1200        assert!(
1201            filter
1202                .transform(Event::tool_call_start("c2", "delete_everything"))
1203                .is_empty()
1204        );
1205        assert!(
1206            filter
1207                .transform(Event::tool_call_args("c2", "{}"))
1208                .is_empty()
1209        );
1210        assert!(
1211            filter
1212                .transform(Event::tool_call_result("m1", "c2", "gone"))
1213                .is_empty()
1214        );
1215        assert_eq!(filter.transform(Event::tool_call_args("c1", "{}")).len(), 1);
1216    }
1217
1218    #[test]
1219    fn filter_leaves_unrelated_events_alone() {
1220        let mut filter = FilterToolCalls::deny(["nope"]);
1221        let event = Event::text_message_start("m1", TextMessageRole::Assistant);
1222        assert_eq!(filter.transform(event.clone()), vec![event]);
1223    }
1224
1225    #[test]
1226    fn filter_drops_encrypted_reasoning_for_a_dropped_call() {
1227        let mut filter = FilterToolCalls::deny(["nope"]);
1228        filter.transform(Event::tool_call_start("c1", "nope"));
1229        let blob = Event::reasoning_encrypted_value(
1230            ReasoningEncryptedValueSubtype::ToolCall,
1231            "c1",
1232            "opaque",
1233        );
1234        assert!(filter.transform(blob).is_empty());
1235    }
1236
1237    #[test]
1238    fn promoting_keeps_the_result_by_default() {
1239        let mut promote = ToolResultToState::snapshot("load");
1240        promote.transform(Event::tool_call_start("c1", "load"));
1241        let result = Event::tool_call_result("m1", "c1", r#"{"a":1}"#);
1242        assert_eq!(
1243            promote.transform(result.clone()),
1244            vec![result, Event::state_snapshot(json!({"a": 1}))]
1245        );
1246    }
1247
1248    #[test]
1249    fn promoting_a_patch_emits_a_delta() {
1250        let mut promote = ToolResultToState::delta("patch_state").replacing();
1251        promote.transform(Event::tool_call_start("c1", "patch_state"));
1252        let content = r#"[{"op":"replace","path":"/step","value":2}]"#;
1253        assert_eq!(
1254            promote.transform(Event::tool_call_result("m1", "c1", content)),
1255            vec![Event::state_delta(vec![PatchOperation::replace(
1256                "/step", 2
1257            )])]
1258        );
1259    }
1260
1261    #[test]
1262    fn unparseable_content_passes_through_untouched() {
1263        let mut promote = ToolResultToState::snapshot("load").replacing();
1264        promote.transform(Event::tool_call_start("c1", "load"));
1265        let result = Event::tool_call_result("m1", "c1", "not json");
1266        assert_eq!(promote.transform(result.clone()), vec![result]);
1267    }
1268
1269    #[test]
1270    fn multimodal_result_is_not_promoted_to_state() {
1271        let mut promote = ToolResultToState::snapshot("load").replacing();
1272        promote.transform(Event::tool_call_start("c1", "load"));
1273        let result =
1274            Event::tool_call_result("m1", "c1", vec![crate::InputContent::text(r#"{"a":1}"#)]);
1275        assert_eq!(promote.transform(result.clone()), vec![result]);
1276    }
1277
1278    #[test]
1279    fn other_tools_are_not_promoted() {
1280        let mut promote = ToolResultToState::snapshot("load");
1281        promote.transform(Event::tool_call_start("c1", "something_else"));
1282        let result = Event::tool_call_result("m1", "c1", r#"{"a":1}"#);
1283        assert_eq!(promote.transform(result.clone()), vec![result]);
1284    }
1285
1286    #[test]
1287    fn chain_runs_transformers_in_order() {
1288        let mut chain = TransformerChain::new()
1289            .with(FilterToolCalls::deny(["load"]))
1290            .with(ToolResultToState::snapshot("load"));
1291        // The filter removes the call first, so the promoter never sees it.
1292        assert!(
1293            chain
1294                .transform(Event::tool_call_start("c1", "load"))
1295                .is_empty()
1296        );
1297        assert!(
1298            chain
1299                .transform(Event::tool_call_result("m1", "c1", r#"{"a":1}"#))
1300                .is_empty()
1301        );
1302    }
1303}