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::streams::{Kind, Opener, Stream, Streams};
23use crate::{Event, Message, MessageId, PatchOperation, SubagentRunId, ToolCallId};
24use serde_json::Value;
25
26/// Rewrites events on their way from an agent to the transport.
27///
28/// # Contract
29///
30/// Returning an empty `Vec` drops the event. Returning several events splices
31/// them in, in order. A transformer that drops the start of something must drop
32/// its continuation and terminator too. The verifier cannot identify every
33/// orphaned ID-less chunk after filtering. Normalize chunks first, or track
34/// the producer's open streams before deciding which chunks to drop.
35///
36/// An emit whose output is filtered out returns `Ok`. At the end of a
37/// hosted run the driver checks whether the consumer received a terminal
38/// event. If the chain removed it, the driver sends a final `RUN_ERROR`
39/// directly to the event queue.
40pub trait StreamTransformer: Send {
41    /// Rewrites one event into zero or more events.
42    fn transform(&mut self, event: Event) -> Vec<Event>;
43
44    /// Learns the conversation the run continues — the request's `messages` —
45    /// once, before the run's first event.
46    ///
47    /// Called whether or not `RUN_STARTED` echoes the input, which is optional
48    /// and off by default. A transformer that judges an event by the id it
49    /// names needs it: a resumed run may answer a tool call the interrupted
50    /// run opened, and that call is in the history, not in this run's events.
51    /// The default ignores it.
52    fn seed(&mut self, history: &[Message]) {
53        let _ = history;
54    }
55
56    /// Learns the events the run has already sent, once, after
57    /// [`seed`](Self::seed) and before the first event of a driver that
58    /// continues the run: [`Runner::continue_run`].
59    ///
60    /// `sent` is what a consumer holds: the output of the chain the earlier
61    /// driver ran, not what its agent emitted. An event that chain dropped is
62    /// not in it, and one it rewrote is there as rewritten. It may begin with
63    /// the runs that came before on the same stream.
64    ///
65    /// A transformer that judges an event by the id it names needs it, as it
66    /// needs the history: a continuation finishes and answers calls the
67    /// earlier driver opened. The default ignores it.
68    ///
69    /// [`Runner::continue_run`]: crate::server::Runner::continue_run
70    fn replay(&mut self, sent: &[Event]) {
71        let _ = sent;
72    }
73}
74
75/// Transformers applied in sequence.
76///
77/// An empty chain is free: the run skips it entirely rather than allocating a
78/// `Vec` per event.
79#[derive(Default)]
80pub struct TransformerChain {
81    transformers: Vec<Box<dyn StreamTransformer>>,
82}
83
84impl std::fmt::Debug for TransformerChain {
85    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86        f.debug_struct("TransformerChain")
87            .field("len", &self.transformers.len())
88            .finish()
89    }
90}
91
92impl TransformerChain {
93    /// An empty chain.
94    pub fn new() -> Self {
95        Self::default()
96    }
97
98    /// Appends a transformer, returning the chain for further building.
99    #[must_use]
100    pub fn with(mut self, transformer: impl StreamTransformer + 'static) -> Self {
101        self.push(transformer);
102        self
103    }
104
105    /// Appends a transformer.
106    pub fn push(&mut self, transformer: impl StreamTransformer + 'static) {
107        self.transformers.push(Box::new(transformer));
108    }
109
110    /// How many transformers are in the chain.
111    pub fn len(&self) -> usize {
112        self.transformers.len()
113    }
114
115    /// Whether the chain would pass every event through untouched.
116    pub fn is_empty(&self) -> bool {
117        self.transformers.is_empty()
118    }
119
120    /// Runs `event` through every transformer in order.
121    pub fn transform(&mut self, event: Event) -> Vec<Event> {
122        let mut current = vec![event];
123        for transformer in &mut self.transformers {
124            let mut next = Vec::with_capacity(current.len());
125            for event in current.drain(..) {
126                next.extend(transformer.transform(event));
127            }
128            current = next;
129            if current.is_empty() {
130                break;
131            }
132        }
133        current
134    }
135}
136
137impl StreamTransformer for TransformerChain {
138    fn transform(&mut self, event: Event) -> Vec<Event> {
139        Self::transform(self, event)
140    }
141
142    /// Every transformer in the chain learns the history as the request
143    /// carries it: what one transformer would do to the history is a rewrite
144    /// of the stream, and the history is not part of the stream.
145    fn seed(&mut self, history: &[Message]) {
146        for transformer in &mut self.transformers {
147            transformer.seed(history);
148        }
149    }
150
151    /// Every transformer in the chain is shown the same events: what was
152    /// sent is the output of the whole chain, whichever of its transformers
153    /// shaped it.
154    fn replay(&mut self, sent: &[Event]) {
155        for transformer in &mut self.transformers {
156            transformer.replay(sent);
157        }
158    }
159}
160
161/// Which side of the list passes.
162#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
163enum FilterMode {
164    Allow,
165    Deny,
166}
167
168/// What a filter makes of a tool call id.
169#[derive(Clone, Copy, Debug, PartialEq, Eq)]
170enum Verdict {
171    /// The call passes: what belongs to it goes out.
172    Pass,
173    /// The call is filtered: what belongs to it is dropped.
174    Drop,
175    /// Nothing has named the tool this id calls. What belongs to it is
176    /// dropped too: see the type docs.
177    Unknown,
178}
179
180/// Drops whole tool calls by tool name.
181///
182/// Both halves of a filtered call are removed — `TOOL_CALL_START`, its
183/// `TOOL_CALL_ARGS` or `TOOL_CALL_CHUNK`s, the `TOOL_CALL_END`, the
184/// `TOOL_CALL_RESULT` and the `REASONING_ENCRYPTED_VALUE` attached to the
185/// call — and so is the call where a conversation is restated: in a
186/// `MESSAGES_SNAPSHOT` and in the request echoed on `RUN_STARTED`.
187///
188/// That is what the filter covers. It does not look into `RAW` or `CUSTOM`
189/// events, into the `rawEvent` payload of an event it sends, or into an
190/// interrupt that names a filtered call's id. Keep the tool out of those
191/// where they are made.
192///
193/// ```
194/// # use ag_ui::Event;
195/// # use ag_ui::server::{FilterToolCalls, StreamTransformer};
196/// let mut filter = FilterToolCalls::deny(["secret_tool"]);
197/// assert!(filter.transform(Event::tool_call_start("c1", "secret_tool")).is_empty());
198/// assert!(filter.transform(Event::tool_call_args("c1", "{}")).is_empty());
199/// assert_eq!(filter.transform(Event::tool_call_start("c2", "public")).len(), 1);
200/// ```
201///
202/// # A conversation the stream restates
203///
204/// A `MESSAGES_SNAPSHOT`, and the request echoed on `RUN_STARTED`, carry
205/// tool calls too, and are filtered by the same names. A filtered call is
206/// taken out of the assistant message that made it, with the encrypted value
207/// it carries, and the tool message that answers it is taken out of the
208/// list. So is:
209///
210/// - an assistant message that is left with neither content nor calls. It
211///   was there to carry the call, and a client that read the run's events
212///   never held it: the events that would have made it were dropped.
213///   Whatever else it carried goes with it;
214/// - a tool message that answers a call nothing named. It has no tool name
215///   of its own to judge it by.
216///
217/// The calls a restated conversation carries are judged as they are met,
218/// like a `TOOL_CALL_START`, so a result that follows one goes where the
219/// call went.
220///
221/// ```
222/// # use ag_ui::{AssistantMessage, Event, Message, ToolCall};
223/// # use ag_ui::server::{FilterToolCalls, StreamTransformer};
224/// let restated = Event::messages_snapshot(vec![
225///     Message::Assistant(AssistantMessage {
226///         id: "msg-1".into(),
227///         content: Some("Looking.".into()),
228///         tool_calls: Some(vec![
229///             ToolCall::new("c1", "search", "{}"),
230///             ToolCall::new("c2", "secret_tool", "{}"),
231///         ]),
232///         ..Default::default()
233///     }),
234///     Message::tool("msg-2", "c2", "the result"),
235/// ]);
236///
237/// let mut filter = FilterToolCalls::deny(["secret_tool"]);
238/// let Some(Event::MessagesSnapshot(snapshot)) = filter.transform(restated).pop() else {
239///     unreachable!("the snapshot is kept");
240/// };
241/// let [Message::Assistant(assistant)] = snapshot.messages.as_slice() else {
242///     unreachable!("the tool message went with its call");
243/// };
244/// assert_eq!(assistant.tool_calls.as_ref().unwrap().len(), 1);
245/// ```
246///
247/// # How a call is named
248///
249/// A call is judged by the name of its tool, and only what opens a call
250/// names it. The filter learns the names from four places:
251///
252/// - this run's events: a `TOOL_CALL_START`, or the `TOOL_CALL_CHUNK` that
253///   opens a call;
254/// - the request's messages ([`seed`](StreamTransformer::seed)), for a
255///   result a resumed run reports;
256/// - in a run that another driver began, the events already sent
257///   ([`replay`](StreamTransformer::replay)), for a call that driver left
258///   open;
259/// - a conversation restated in a `MESSAGES_SNAPSHOT` or the `RUN_STARTED`
260///   echo.
261///
262/// An event of a call none of these named is dropped, and the emit that
263/// produced it returns `Ok`: arguments, an end, a result, an encrypted
264/// value, a chunk that names no tool. The filter cannot tell such a call
265/// from one that was filtered where this filter could not see it: by the
266/// filter of an earlier run, so that the client never held the call and
267/// the request's messages do not either, or by the filter of the earlier
268/// driver of this run, so that the events sent do not. The result a resumed
269/// run reports for such a call, and the end a continuation gives it, go the
270/// way the call went.
271///
272/// In a run that another driver began, the filter does not take up the
273/// chunk streams the events sent left open. The earlier driver may have
274/// been streaming a call its filter removed in the same lane, and the
275/// events sent do not show it, so a chunk that names no id cannot be told
276/// from one meant for that call. A continuation that keeps streaming a call
277/// by chunks names the call's id on its first chunk, and the chunks after it
278/// continue that call, as within any single run. A chunk that names no id
279/// before that is dropped.
280#[derive(Clone, Debug)]
281pub struct FilterToolCalls {
282    mode: FilterMode,
283    names: HashSet<String>,
284    /// Every named call's verdict survives its end for a later result.
285    dropped: HashSet<ToolCallId>,
286    call_names: HashMap<ToolCallId, String>,
287    /// The producer's open streams, including calls removed from the output.
288    /// A bare chunk must be resolved here, before filtering can make it look
289    /// like a continuation of a different call to the consumer. In a run
290    /// another driver began, they start empty: the events sent are not the
291    /// producer's stream.
292    streams: Streams,
293}
294
295impl FilterToolCalls {
296    /// Passes only calls to the named tools.
297    pub fn allow<I, T>(names: I) -> Self
298    where
299        I: IntoIterator<Item = T>,
300        T: Into<String>,
301    {
302        Self::new(FilterMode::Allow, names)
303    }
304
305    /// Passes everything except calls to the named tools.
306    pub fn deny<I, T>(names: I) -> Self
307    where
308        I: IntoIterator<Item = T>,
309        T: Into<String>,
310    {
311        Self::new(FilterMode::Deny, names)
312    }
313
314    fn new<I, T>(mode: FilterMode, names: I) -> Self
315    where
316        I: IntoIterator<Item = T>,
317        T: Into<String>,
318    {
319        Self {
320            mode,
321            names: names.into_iter().map(Into::into).collect(),
322            dropped: HashSet::new(),
323            call_names: HashMap::new(),
324            streams: Streams::default(),
325        }
326    }
327
328    fn passes(&self, name: &str) -> bool {
329        match self.mode {
330            FilterMode::Allow => self.names.contains(name),
331            FilterMode::Deny => !self.names.contains(name),
332        }
333    }
334
335    /// Records what names a call, and gives the verdict on the call.
336    fn judge(&mut self, id: &ToolCallId, name: &str) -> Verdict {
337        match self.call_names.get(id) {
338            // The consumer keeps the name from the first chunk with this id.
339            // A later name cannot reclassify its arguments as another tool.
340            Some(original) => {
341                if original != name {
342                    self.dropped.insert(id.clone());
343                }
344            }
345            None => {
346                self.call_names.insert(id.clone(), name.to_owned());
347                if !self.passes(name) {
348                    self.dropped.insert(id.clone());
349                }
350            }
351        }
352        self.verdict(id)
353    }
354
355    fn verdict(&self, id: &ToolCallId) -> Verdict {
356        if self.dropped.contains(id) {
357            Verdict::Drop
358        } else if self.call_names.contains_key(id) {
359            Verdict::Pass
360        } else {
361            Verdict::Unknown
362        }
363    }
364
365    /// Judges every call a restated conversation carries.
366    fn learn(&mut self, messages: &[Message]) {
367        for message in messages {
368            if let Message::Assistant(assistant) = message {
369                for call in assistant.tool_calls.iter().flatten() {
370                    self.judge(&call.id, &call.function.name);
371                }
372            }
373        }
374    }
375
376    /// Takes the filtered calls out of a restated conversation, and what
377    /// only made sense with them. The type docs say what goes and why.
378    fn prune(&self, messages: &mut Vec<Message>) {
379        messages.retain_mut(|message| match message {
380            Message::Assistant(assistant) => {
381                let Some(calls) = &mut assistant.tool_calls else {
382                    return true;
383                };
384                let carried = calls.len();
385                calls.retain(|call| self.verdict(&call.id) == Verdict::Pass);
386                // Untouched, or still carrying a call that passes.
387                if calls.len() == carried || !calls.is_empty() {
388                    return true;
389                }
390                // Every call it carried was filtered. It stays for what it
391                // says, if it says anything.
392                assistant.tool_calls = None;
393                assistant
394                    .content
395                    .as_deref()
396                    .is_some_and(|content| !content.is_empty())
397            }
398            Message::Tool(tool) => self.verdict(&tool.tool_call_id) == Verdict::Pass,
399            _ => true,
400        });
401    }
402
403    /// Whether an event is dropped: it belongs to a call that is filtered,
404    /// or to one nothing named.
405    fn drops(&mut self, event: &Event) -> bool {
406        match event {
407            Event::ToolCallStart(e) => {
408                self.judge(&e.tool_call_id, &e.tool_call_name) != Verdict::Pass
409            }
410            Event::ToolCallChunk(e) => match (&e.tool_call_id, &e.tool_call_name) {
411                (Some(id), Some(name)) => self.judge(id, name) != Verdict::Pass,
412                // It continues a call, or opens one without naming its tool.
413                (Some(id), None) => self.verdict(id) != Verdict::Pass,
414                (None, name) => {
415                    // A chunk that continues nothing belongs to no call.
416                    let Ok(stream) = self.streams.continued(Kind::Tool, &e.subagent_run_id) else {
417                        return true;
418                    };
419                    let id = ToolCallId::new(&stream.id);
420                    let renamed = name.as_ref().is_some_and(|name| {
421                        self.call_names
422                            .get(&id)
423                            .is_none_or(|original| original != name)
424                    });
425                    if renamed {
426                        self.dropped.insert(id.clone());
427                    }
428                    self.verdict(&id) != Verdict::Pass
429                }
430            },
431            Event::ToolCallArgs(e) => self.verdict(&e.tool_call_id) != Verdict::Pass,
432            Event::ToolCallEnd(e) => self.verdict(&e.tool_call_id) != Verdict::Pass,
433            Event::ToolCallResult(e) => self.verdict(&e.tool_call_id) != Verdict::Pass,
434            Event::ReasoningEncryptedValue(e)
435                if e.subtype == crate::ReasoningEncryptedValueSubtype::ToolCall =>
436            {
437                self.verdict(&ToolCallId::new(&e.entity_id)) != Verdict::Pass
438            }
439            Event::MessagesSnapshot(e) => {
440                self.learn(&e.messages);
441                false
442            }
443            Event::RunStarted(e) => {
444                if let Some(input) = &e.input {
445                    self.learn(&input.messages);
446                }
447                false
448            }
449            _ => false,
450        }
451    }
452
453    /// Follows the producer's open streams through an event.
454    ///
455    /// A chunk that names a call and not its tool, in a lane that is not
456    /// assembling that call, is taken to open the call's stream there: it
457    /// is how a continuation takes up a call the events sent left open, and
458    /// the chunks with no id after it are that call's, whatever the lane
459    /// held before. The open-stream model opens no stream without a tool's
460    /// name, so the one the filter knows is filled in, or an empty one for
461    /// a call nothing named, whose chunks are dropped all the same.
462    fn follow(&mut self, event: &Event) {
463        if let Event::ToolCallChunk(chunk) = event {
464            if let (Some(id), None) = (&chunk.tool_call_id, &chunk.tool_call_name) {
465                let tag = &chunk.subagent_run_id;
466                if assembling(&self.streams, Kind::Tool, id.as_str(), tag).is_none() {
467                    let mut opening = chunk.clone();
468                    let name = self.call_names.get(id).cloned().unwrap_or_default();
469                    opening.tool_call_name = Some(name);
470                    self.streams.track(&Event::ToolCallChunk(opening));
471                    return;
472                }
473            }
474        }
475        self.streams.track(event);
476    }
477}
478
479impl StreamTransformer for FilterToolCalls {
480    /// A call an earlier run made is judged by its name like a new one, so the
481    /// result a resumed run reports for it goes the way the call went.
482    fn seed(&mut self, history: &[Message]) {
483        self.learn(history);
484    }
485
486    /// A call the earlier driver of the run opened is judged by its name
487    /// like a new one, so a continuation can finish and answer it.
488    ///
489    /// The chunk streams the events sent left open are not taken up: what
490    /// was sent is not what the earlier producer had open. A chunk that
491    /// names no id is dropped until a chunk of this driver names the call it
492    /// continues.
493    fn replay(&mut self, sent: &[Event]) {
494        for event in sent {
495            match event {
496                Event::ToolCallStart(e) => {
497                    self.judge(&e.tool_call_id, &e.tool_call_name);
498                }
499                Event::ToolCallChunk(e) => {
500                    if let (Some(id), Some(name)) = (&e.tool_call_id, &e.tool_call_name) {
501                        self.judge(id, name);
502                    }
503                }
504                Event::MessagesSnapshot(e) => self.learn(&e.messages),
505                Event::RunStarted(e) => {
506                    if let Some(input) = &e.input {
507                        self.learn(&input.messages);
508                    }
509                }
510                _ => {}
511            }
512        }
513    }
514
515    fn transform(&mut self, mut event: Event) -> Vec<Event> {
516        let drop = self.drops(&event);
517
518        // Observe the unfiltered input. A removed start still changes where
519        // the producer's later ID-less chunks belong.
520        self.follow(&event);
521
522        if drop {
523            return Vec::new();
524        }
525        match &mut event {
526            Event::MessagesSnapshot(snapshot) => self.prune(&mut snapshot.messages),
527            Event::RunStarted(started) => {
528                if let Some(input) = &mut started.input {
529                    self.prune(&mut input.messages);
530                }
531            }
532            _ => {}
533        }
534        vec![event]
535    }
536}
537
538/// How a promoted tool result reaches the client's state.
539#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
540enum StateForm {
541    /// The result is the new state.
542    Snapshot,
543    /// The result is an RFC 6902 patch against the current state.
544    Delta,
545}
546
547/// Promotes a named tool's result into a state event.
548///
549/// A tool whose job is to produce state — `load_document`, `set_filters` —
550/// otherwise forces the agent to emit the result and then publish the state by
551/// hand. This transformer does it: when `tool_name` returns, its JSON content
552/// becomes a `STATE_SNAPSHOT` or a `STATE_DELTA`.
553///
554/// The result event is kept by default so the client still sees the tool
555/// completed; [`replacing`](Self::replacing) drops it instead. Content that is
556/// not JSON of the expected shape is left alone — a malformed result must not
557/// take down the run. For [`delta`](Self::delta) the expected shape is a JSON
558/// Patch a consumer can read: an array of RFC 6902 operations whose `path`
559/// and `from` are JSON Pointers. A patch that is well formed and does not
560/// apply to the state is still promoted; a consumer reports that and keeps
561/// the state it has.
562///
563/// ```
564/// # use ag_ui::Event;
565/// # use ag_ui::server::{StreamTransformer, ToolResultToState};
566/// let mut promote = ToolResultToState::snapshot("load_document").replacing();
567/// promote.transform(Event::tool_call_start("c1", "load_document"));
568/// let out = promote.transform(Event::tool_call_result("m1", "c1", r#"{"title":"Notes"}"#));
569/// assert_eq!(out, vec![Event::state_snapshot(serde_json::json!({"title": "Notes"}))]);
570/// ```
571///
572/// The call need not have started in this run. One the request's history
573/// holds unanswered, one a restated conversation carries, and in a run that
574/// another driver began one the events already sent opened, are all calls
575/// whose result is promoted.
576#[derive(Clone, Debug)]
577pub struct ToolResultToState {
578    tool_name: String,
579    form: StateForm,
580    keep_result: bool,
581    /// The calls to the tool that have no result yet.
582    awaiting: HashSet<ToolCallId>,
583}
584
585impl ToolResultToState {
586    /// Turns `tool_name`'s result into a `STATE_SNAPSHOT`.
587    pub fn snapshot(tool_name: impl Into<String>) -> Self {
588        Self::new(tool_name, StateForm::Snapshot)
589    }
590
591    /// Turns `tool_name`'s result into a `STATE_DELTA`. The result content must
592    /// be a JSON array of RFC 6902 operations.
593    pub fn delta(tool_name: impl Into<String>) -> Self {
594        Self::new(tool_name, StateForm::Delta)
595    }
596
597    fn new(tool_name: impl Into<String>, form: StateForm) -> Self {
598        Self {
599            tool_name: tool_name.into(),
600            form,
601            keep_result: true,
602            awaiting: HashSet::new(),
603        }
604    }
605
606    /// Drops the `TOOL_CALL_RESULT` instead of emitting it alongside the state
607    /// event.
608    #[must_use]
609    pub fn replacing(mut self) -> Self {
610        self.keep_result = false;
611        self
612    }
613
614    fn state_event(&self, content: &str) -> Option<Event> {
615        match self.form {
616            StateForm::Snapshot => serde_json::from_str::<Value>(content)
617                .ok()
618                .map(Event::state_snapshot),
619            // A patch a consumer could not read is no more the expected
620            // shape than content that is not JSON.
621            StateForm::Delta => {
622                // Validate the original tool output before the SDK's compatibility
623                // decoder supplies a missing value. Decode it again into the wire
624                // type to keep RFC 6902 extension members on the emitted delta.
625                serde_json::from_str::<json_patch::Patch>(content).ok()?;
626                serde_json::from_str::<Vec<PatchOperation>>(content)
627                    .ok()
628                    .map(Event::state_delta)
629            }
630        }
631    }
632
633    /// Learns the calls to the tool that a conversation holds unanswered.
634    fn learn(&mut self, messages: &[Message]) {
635        for message in messages {
636            if let Message::Assistant(assistant) = message {
637                for call in assistant.tool_calls.iter().flatten() {
638                    if call.function.name == self.tool_name {
639                        self.awaiting.insert(call.id.clone());
640                    }
641                }
642            }
643        }
644        // A call the conversation answers is not waiting for a result.
645        for message in messages {
646            if let Message::Tool(tool) = message {
647                self.awaiting.remove(&tool.tool_call_id);
648            }
649        }
650    }
651
652    /// Learns from an event which calls are to the tool.
653    fn note(&mut self, event: &Event) {
654        match event {
655            Event::ToolCallStart(e) if e.tool_call_name == self.tool_name => {
656                self.awaiting.insert(e.tool_call_id.clone());
657            }
658            Event::ToolCallChunk(e) => {
659                if let (Some(id), Some(name)) = (&e.tool_call_id, &e.tool_call_name) {
660                    if name == &self.tool_name {
661                        self.awaiting.insert(id.clone());
662                    }
663                }
664            }
665            Event::MessagesSnapshot(e) => self.learn(&e.messages),
666            Event::RunStarted(e) => {
667                if let Some(input) = &e.input {
668                    self.learn(&input.messages);
669                }
670            }
671            _ => {}
672        }
673    }
674}
675
676impl StreamTransformer for ToolResultToState {
677    /// A call to the tool that an earlier run left unanswered is one whose
678    /// result a resumed run reports, and it is promoted like any other.
679    fn seed(&mut self, history: &[Message]) {
680        self.learn(history);
681    }
682
683    /// The same for a call the earlier driver of the run opened.
684    fn replay(&mut self, sent: &[Event]) {
685        for event in sent {
686            self.note(event);
687            if let Event::ToolCallResult(result) = event {
688                self.awaiting.remove(&result.tool_call_id);
689            }
690        }
691    }
692
693    fn transform(&mut self, event: Event) -> Vec<Event> {
694        self.note(&event);
695        let Event::ToolCallResult(payload) = &event else {
696            return vec![event];
697        };
698        if !self.awaiting.remove(&payload.tool_call_id) {
699            return vec![event];
700        }
701        let promoted = payload
702            .content
703            .as_text()
704            .and_then(|text| self.state_event(text));
705        let Some(mut state) = promoted else {
706            return vec![event];
707        };
708        // Provenance travels with the state: a subagent's result promoted
709        // is the subagent's publish.
710        if let Some(id) = &payload.subagent_run_id {
711            state.set_subagent_run_id(id.clone());
712        }
713        if self.keep_result {
714            vec![event, state]
715        } else {
716            vec![state]
717        }
718    }
719}
720
721/// What a consumer sees of an agent's subagents.
722///
723/// [`Attributed`](Self::Attributed) — the default, and no transformer at all —
724/// sends the stream as the agent emitted it. The other two exist because a
725/// client older than `@ag-ui/client` 0.0.59 rejects the `SUBAGENT_*` event
726/// *types* while decoding: an unknown field is tolerated, an unknown event
727/// type is not, and there is nothing a client can do about it after the
728/// fact. A producer with such consumers must not send them, and this is how
729/// it does not.
730///
731/// Upstream's integrations default to inline and make the full surface
732/// opt-in. This crate defaults the other way, because a transformer that
733/// rewrites the stream is opt-in here like every other: an agent that wrote
734/// `ctx.subagent(..)` meant it, and silently flattening that output would
735/// surprise the caller. Flip it per endpoint when
736/// your consumers are older:
737///
738/// ```
739/// # use ag_ui::RunOutcome;
740/// # use ag_ui::server::{Agent, Result, RunContext, Runner, SubagentVisibility};
741/// # struct MyAgent;
742/// # impl Agent for MyAgent {
743/// #     type State = ();
744/// #     async fn run(&self, _ctx: &mut RunContext<()>) -> Result<RunOutcome> { Ok(RunOutcome::Success) }
745/// # }
746/// let runner = Runner::new(MyAgent).transformer(SubagentVisibility::inline());
747/// # let _ = runner;
748/// ```
749///
750/// The list of modes is `#[non_exhaustive]`: another way to show subagents
751/// to a consumer can be added without a breaking release.
752#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
753#[non_exhaustive]
754pub enum SubagentVisibility {
755    /// The full surface: the lifecycle events, and `subagentRunId` on
756    /// everything a subagent produced.
757    #[default]
758    Attributed,
759    /// The pre-subagent shape: no lifecycle events and no `subagentRunId`
760    /// anywhere — not on events, not on the messages inside
761    /// `MESSAGES_SNAPSHOT` or the `RUN_STARTED` input echo, not on the
762    /// interrupts a paused run reports. A subagent's own text arrives as the
763    /// parent's work. A `*_CHUNK` event that named no id is given the one its
764    /// attribution resolved to, since without the attribution the consumer
765    /// would resolve it differently.
766    ///
767    /// A subagent's steps are dropped rather than flattened. A step brackets
768    /// its own agent's graph, and as the parent's it would either collide
769    /// with an open step of the same name — the common shape: a parent
770    /// `tools` step wrapping the delegation and the child's own `tools`
771    /// inside it — or misdescribe the parent's graph. The lifecycle events
772    /// were the child's structure; so are its steps.
773    Inline,
774    /// Only the parent's own events. Everything a subagent produced is
775    /// dropped — including the result of a call it requested, even when the
776    /// parent executed it, since a result for a call the consumer never saw
777    /// is a protocol error. The converse holds too: a result answering the
778    /// *parent's* call is kept, untagged, whoever executed it — the consumer
779    /// saw the call, and a call left unanswered in the history is what the
780    /// next request would carry back.
781    ///
782    /// The one thing kept is the run's shared state. A `STATE_SNAPSHOT` or
783    /// `STATE_DELTA` a subagent published describes the *thread's* state,
784    /// not the subagent's work: a client that never saw it would mirror a
785    /// stale state and send that back on its next request. It goes out with
786    /// the tag cleared, as the parent's.
787    Hidden,
788}
789
790impl SubagentVisibility {
791    /// The transformer for this mode. [`Attributed`](Self::Attributed) passes
792    /// events through unchanged.
793    pub fn filter(self) -> SubagentFilter {
794        SubagentFilter::new(self)
795    }
796
797    /// The transformer for [`Inline`](Self::Inline).
798    pub fn inline() -> SubagentFilter {
799        Self::Inline.filter()
800    }
801
802    /// The transformer for [`Hidden`](Self::Hidden).
803    pub fn hidden() -> SubagentFilter {
804        Self::Hidden.filter()
805    }
806}
807
808/// The transformer behind [`SubagentVisibility`].
809///
810/// Both modes keep the model of the stream a consumer expands chunks by — one
811/// chunk stream per owner, ended by what AG-UI 1.0 says ends it — because a
812/// `*_CHUNK` event that names no id is resolved *through its attribution* on
813/// the consuming side, and stripping the attribution would send it to the
814/// wrong stream. Such a chunk is given the id it resolves to before its tag
815/// goes.
816///
817/// They keep that model twice: once for the stream the agent emits, and once
818/// for the stream the filter sends, which is the one a consumer follows. The
819/// two differ, because an event that leaves its subagent's lane ends a chunk
820/// stream in the lane it arrives in. Two subagents that stream at once take
821/// turns ending each other's stream once [`Inline`](SubagentVisibility::Inline)
822/// has put both in the parent's lane, and the state a subagent publishes,
823/// which [`Hidden`](SubagentVisibility::Hidden) keeps as the parent's, ends
824/// the parent's. The agent's stream is still open then, so its next chunk
825/// says only what a continuation says, and on the consuming side that chunk
826/// opens the item again. It is given what opens it, from what the agent
827/// opened the stream with: `toolCallName` and `parentMessageId` for a tool
828/// call, `role` and `name` for a message. A chunk whose stream the consumer
829/// still holds is sent as it is.
830///
831/// [`Hidden`](SubagentVisibility::Hidden) additionally remembers what each
832/// subagent owns — messages, tool calls, activities — for the rest of the
833/// run, not only while they are open, so an untagged continuation, re-open,
834/// patch or result for a subagent's entity is dropped with the rest of it
835/// rather than leaking into the parent's stream. That is the owner-aware
836/// verifier's reading too: the first writer owns the id, and an absent tag
837/// agrees with any owner. An entity the consumer has seen opened keeps that
838/// visibility until it closes, whatever a snapshot says about its owner
839/// meanwhile — a consumer must never be left with a message it saw opened
840/// and never sees closed.
841#[derive(Debug)]
842pub struct SubagentFilter {
843    mode: SubagentVisibility,
844    /// The chunk streams the agent has open, per owner: what it emitted.
845    streams: Streams,
846    /// The chunk streams a consumer has open: what this filter sent.
847    output: Streams,
848    /// Text message ids a subagent owns, and which.
849    hidden_text: HashMap<MessageId, SubagentRunId>,
850    /// Reasoning ids — the block and the message inside it — a subagent
851    /// owns. A bucket of its own, as the verifiers keep it, so a producer
852    /// that reuses an id across the two kinds is not misread.
853    hidden_reasoning: HashMap<MessageId, SubagentRunId>,
854    /// Tool call ids a subagent owns — or that sit in a message it owns.
855    hidden_tool_calls: HashMap<ToolCallId, SubagentRunId>,
856    /// Every activity seen, and whether a subagent owns it.
857    activities: HashMap<MessageId, bool>,
858    /// What is open, and whether the consumer saw it open.
859    open_visibility: HashMap<(Kind, String), bool>,
860    /// Whether the consumer saw each tool call start, for the result that
861    /// may arrive long after the call closed.
862    call_visibility: HashMap<ToolCallId, bool>,
863    // Only Hidden projects the messages actually sent to the consumer.
864    visible_messages: Option<Box<crate::client::apply::Applier>>,
865}
866
867/// What a chunk naming no id turned out to be.
868enum Bare {
869    /// Not such a chunk.
870    No,
871    /// Resolved to a stream, and given its id.
872    Resolved {
873        owner: Option<SubagentRunId>,
874        kind: Kind,
875        id: String,
876    },
877    /// Nothing to resolve it against; the consumer will say so.
878    Unresolved,
879}
880
881impl SubagentFilter {
882    /// A filter for `mode`.
883    pub fn new(mode: SubagentVisibility) -> Self {
884        Self {
885            mode,
886            streams: Streams::default(),
887            output: Streams::default(),
888            hidden_text: HashMap::new(),
889            hidden_reasoning: HashMap::new(),
890            hidden_tool_calls: HashMap::new(),
891            activities: HashMap::new(),
892            open_visibility: HashMap::new(),
893            call_visibility: HashMap::new(),
894            visible_messages: (mode == SubagentVisibility::Hidden).then(Default::default),
895        }
896    }
897
898    /// The mode this filter applies.
899    pub fn mode(&self) -> SubagentVisibility {
900        self.mode
901    }
902
903    /// The stream a stream-bearing event belongs to, if it names one.
904    fn entity(event: &Event) -> Option<(Kind, &str)> {
905        Some(match event {
906            Event::TextMessageStart(e) => (Kind::Text, e.message_id.as_str()),
907            Event::TextMessageContent(e) => (Kind::Text, e.message_id.as_str()),
908            Event::TextMessageEnd(e) => (Kind::Text, e.message_id.as_str()),
909            Event::TextMessageChunk(e) => (Kind::Text, e.message_id.as_ref()?.as_str()),
910            Event::ReasoningStart(e) => (Kind::Reasoning, e.message_id.as_str()),
911            Event::ReasoningMessageStart(e) => (Kind::Reasoning, e.message_id.as_str()),
912            Event::ReasoningMessageContent(e) => (Kind::Reasoning, e.message_id.as_str()),
913            Event::ReasoningMessageEnd(e) => (Kind::Reasoning, e.message_id.as_str()),
914            Event::ReasoningEnd(e) => (Kind::Reasoning, e.message_id.as_str()),
915            Event::ReasoningMessageChunk(e) => (Kind::Reasoning, e.message_id.as_ref()?.as_str()),
916            Event::ToolCallStart(e) => (Kind::Tool, e.tool_call_id.as_str()),
917            Event::ToolCallArgs(e) => (Kind::Tool, e.tool_call_id.as_str()),
918            Event::ToolCallEnd(e) => (Kind::Tool, e.tool_call_id.as_str()),
919            Event::ToolCallResult(e) => (Kind::Tool, e.tool_call_id.as_str()),
920            Event::ToolCallChunk(e) => (Kind::Tool, e.tool_call_id.as_ref()?.as_str()),
921            _ => return None,
922        })
923    }
924
925    /// The message a tool call sits in, when the event says.
926    fn carrier(event: &Event) -> Option<&MessageId> {
927        match event {
928            Event::ToolCallStart(e) => e.parent_message_id.as_ref(),
929            Event::ToolCallChunk(e) => e.parent_message_id.as_ref(),
930            _ => None,
931        }
932    }
933
934    /// Whose an event is: its tag; else the recorded owner of its entity —
935    /// for a tool call, the owner of the message that carries it; else
936    /// whoever has that entity open; else the parent.
937    fn owner_for(&self, event: &Event, tag: &Option<SubagentRunId>) -> Option<SubagentRunId> {
938        if tag.is_some() {
939            return tag.clone();
940        }
941        let (kind, id) = Self::entity(event)?;
942        let recorded = match kind {
943            Kind::Text => self.hidden_text.get(&MessageId::new(id)).cloned(),
944            Kind::Reasoning => self.hidden_reasoning.get(&MessageId::new(id)).cloned(),
945            Kind::Tool => Self::carrier(event)
946                .and_then(|parent| self.hidden_text.get(parent).cloned())
947                .or_else(|| self.hidden_tool_calls.get(&ToolCallId::new(id)).cloned()),
948        };
949        // Untagged, it continues whatever chunk stream is assembling its id.
950        recorded.or_else(|| {
951            let holder = self.streams.holder(kind, id)?;
952            holder.owner.clone()
953        })
954    }
955
956    /// Gives a chunk naming no id the id its attribution resolves to on the
957    /// consuming side, so that stripping the attribution afterwards cannot
958    /// send it to another stream.
959    fn fill_bare(&self, event: &mut Event, tag: &Option<SubagentRunId>) -> Bare {
960        let kind = match event {
961            Event::TextMessageChunk(e) if e.message_id.is_none() => Kind::Text,
962            Event::ReasoningMessageChunk(e) if e.message_id.is_none() => Kind::Reasoning,
963            Event::ToolCallChunk(e) if e.tool_call_id.is_none() => Kind::Tool,
964            _ => return Bare::No,
965        };
966        let Ok(stream) = self.streams.continued(kind, tag) else {
967            return Bare::Unresolved;
968        };
969        let (owner, id) = (stream.owner.clone(), stream.id.clone());
970        match event {
971            Event::TextMessageChunk(e) => e.message_id = Some(MessageId::new(&id)),
972            Event::ReasoningMessageChunk(e) => e.message_id = Some(MessageId::new(&id)),
973            Event::ToolCallChunk(e) => e.tool_call_id = Some(ToolCallId::new(&id)),
974            _ => unreachable!("matched above"),
975        }
976        Bare::Resolved { owner, kind, id }
977    }
978
979    /// What the agent opened the stream a chunk continues with.
980    ///
981    /// Read once the chunk has its id and before it is tracked. `None` for
982    /// a chunk that continues nothing the agent has open: it opens its own
983    /// stream, and carries what opens it or is malformed as emitted.
984    fn opener(&self, event: &Event, tag: &Option<SubagentRunId>) -> Option<Opener> {
985        let (kind, id) = chunk_item(event)?;
986        assembling(&self.streams, kind, id, tag).map(|stream| stream.opener.clone())
987    }
988
989    /// Sends an event on, as the last thing either mode does with it.
990    ///
991    /// `opener` is what [`opener`](Self::opener) read for it. A chunk that
992    /// continues a stream the consumer no longer holds is given the fields
993    /// that open its item there, and the consumer's streams are followed
994    /// with what is sent.
995    fn send(&mut self, mut event: Event, opener: Option<Opener>) -> Vec<Event> {
996        if let Some(opener) = opener {
997            self.reopen(&mut event, opener);
998        }
999        self.record_output(&event);
1000        vec![event]
1001    }
1002
1003    fn record_output(&mut self, event: &Event) {
1004        let expanded = self.output.track(event);
1005        let Some(visible) = &mut self.visible_messages else {
1006            return;
1007        };
1008        for update in expanded {
1009            let _ = visible.apply(&update);
1010        }
1011        match event {
1012            Event::RunStarted(started) => {
1013                if let Some(input) = &started.input {
1014                    **visible =
1015                        crate::client::apply::Applier::new().with_messages(input.messages.clone());
1016                }
1017            }
1018            Event::RunFinished(_) | Event::RunError(_) => **visible = Default::default(),
1019            Event::TextMessageStart(_)
1020            | Event::TextMessageContent(_)
1021            | Event::TextMessageEnd(_)
1022            | Event::ReasoningMessageStart(_)
1023            | Event::ReasoningMessageContent(_)
1024            | Event::ReasoningMessageEnd(_)
1025            | Event::ToolCallStart(_)
1026            | Event::ToolCallArgs(_)
1027            | Event::ToolCallEnd(_)
1028            | Event::ToolCallResult(_)
1029            | Event::ReasoningEncryptedValue(_)
1030            | Event::MessagesSnapshot(_) => {
1031                let _ = visible.apply(event);
1032            }
1033            _ => {}
1034        }
1035    }
1036
1037    /// Fills in what opens a chunk's item, unless the consumer has the
1038    /// chunk's stream open and so reads the chunk as a continuation.
1039    fn reopen(&self, event: &mut Event, opener: Opener) {
1040        let tag = event.subagent_run_id().cloned();
1041        let continues = chunk_item(event)
1042            .is_some_and(|(kind, id)| assembling(&self.output, kind, id, &tag).is_some());
1043        if continues {
1044            return;
1045        }
1046        match (event, opener) {
1047            (Event::TextMessageChunk(chunk), Opener::Text { role, name }) => {
1048                chunk.role.get_or_insert(role);
1049                if chunk.name.is_none() {
1050                    chunk.name = name;
1051                }
1052            }
1053            (
1054                Event::ToolCallChunk(chunk),
1055                Opener::Tool {
1056                    name,
1057                    parent_message_id,
1058                },
1059            ) => {
1060                chunk.tool_call_name.get_or_insert(name);
1061                if chunk.parent_message_id.is_none() {
1062                    chunk.parent_message_id = parent_message_id;
1063                }
1064            }
1065            // A reasoning message is opened by its id alone.
1066            _ => {}
1067        }
1068    }
1069
1070    /// Strips the subagent surface from an event, or drops it entirely when
1071    /// it *is* the subagent surface — the lifecycle, and a subagent's steps.
1072    fn inline(&mut self, mut event: Event) -> Vec<Event> {
1073        let tag = event.subagent_run_id().cloned();
1074        // Filled before it is tracked: with its id a chunk continues the
1075        // stream it resolved to, which is what the consumer will see.
1076        self.fill_bare(&mut event, &tag);
1077        let opener = self.opener(&event, &tag);
1078        self.streams.track(&event);
1079        let subagents_step =
1080            matches!(event, Event::StepStarted(_) | Event::StepFinished(_)) && tag.is_some();
1081        if subagents_step {
1082            return Vec::new();
1083        }
1084        match &mut event {
1085            Event::SubagentStarted(_) | Event::SubagentFinished(_) | Event::SubagentError(_) => {
1086                return Vec::new();
1087            }
1088            Event::MessagesSnapshot(snapshot) => {
1089                for message in &mut snapshot.messages {
1090                    message.set_subagent_run_id(None);
1091                }
1092            }
1093            Event::RunStarted(started) => {
1094                if let Some(input) = &mut started.input {
1095                    for message in &mut input.messages {
1096                        message.set_subagent_run_id(None);
1097                    }
1098                }
1099            }
1100            Event::RunFinished(finished) => Self::strip_interrupt_tags(finished),
1101            _ => {
1102                event.clear_subagent_run_id();
1103            }
1104        }
1105        self.send(event, opener)
1106    }
1107
1108    /// The interrupts a paused run reports name the subagent that raised
1109    /// them, and a consumer that never saw that subagent has no group to
1110    /// file them under. The question still stands, so the interrupt stays;
1111    /// only the tag goes.
1112    fn strip_interrupt_tags(finished: &mut crate::RunFinishedEvent) {
1113        if let Some(crate::RunOutcome::Interrupt { interrupts }) = &mut finished.outcome {
1114            for interrupt in interrupts {
1115                interrupt.subagent_run_id = None;
1116            }
1117        }
1118    }
1119
1120    /// Keeps the parent's events and drops a subagent's, remembering what
1121    /// each subagent owns so that an untagged event is judged by its opener.
1122    fn hidden(&mut self, mut event: Event) -> Vec<Event> {
1123        let tag = event.subagent_run_id().cloned();
1124        let owned = tag.is_some();
1125        let bare = self.fill_bare(&mut event, &tag);
1126        let opener = self.opener(&event, &tag);
1127        let mut expanded = Vec::new();
1128        let keep = match bare {
1129            // The chunk continues a stream: it goes where the stream went.
1130            Bare::Resolved { owner, kind, id } => self
1131                .open_visibility
1132                .get(&(kind, id))
1133                .copied()
1134                .unwrap_or(owner.is_none()),
1135            Bare::Unresolved => !owned,
1136            Bare::No => {
1137                // Before the event is tracked: it may end the stream that
1138                // says whose it is.
1139                let owner = self.owner_for(&event, &tag);
1140                expanded = self.streams.track(&event);
1141                self.judge(&event, &tag, owner.as_ref())
1142            }
1143        };
1144        // An implicit end releases the visibility of that chunked item. A
1145        // snapshot still filters against the visibility immediately before it.
1146        if !matches!(event, Event::MessagesSnapshot(_)) {
1147            self.forget_chunk_ends(&expanded);
1148        }
1149        if !keep
1150            || (owned
1151                && matches!(
1152                    event,
1153                    Event::TextMessageStart(_)
1154                        | Event::TextMessageChunk(_)
1155                        | Event::ReasoningStart(_)
1156                        | Event::ReasoningMessageStart(_)
1157                        | Event::ReasoningMessageChunk(_)
1158                ))
1159        {
1160            return Vec::new();
1161        }
1162        match &mut event {
1163            // Authoritative: the snapshot restates the conversation, so what
1164            // it carries is re-read — and what it does not carry is left as
1165            // the run established it, as the verifiers leave it.
1166            Event::MessagesSnapshot(snapshot) => {
1167                self.seed_hidden(&snapshot.messages, true);
1168                let mut present = HashSet::new();
1169                snapshot.messages.retain_mut(|message| {
1170                    // A result's visibility follows the final list of calls,
1171                    // including any restored with an open parent below.
1172                    let keep = matches!(message, Message::Tool(_)) || self.show_message(message);
1173                    if keep {
1174                        present.insert(message.id().clone());
1175                    }
1176                    keep
1177                });
1178                if let Some(visible) = &self.visible_messages {
1179                    for message in visible.open_messages() {
1180                        if present.contains(message.id()) {
1181                            continue;
1182                        }
1183                        if let Message::Assistant(assistant) = message {
1184                            for call in assistant.tool_calls.iter().flatten() {
1185                                self.hidden_tool_calls.remove(&call.id);
1186                                self.call_visibility.insert(call.id.clone(), true);
1187                            }
1188                        }
1189                        snapshot.messages.push(message.clone());
1190                    }
1191                }
1192                snapshot.messages.retain_mut(|message| {
1193                    let Message::Tool(tool) = message else {
1194                        return true;
1195                    };
1196                    if self.hidden_tool_calls.contains_key(&tool.tool_call_id) {
1197                        return false;
1198                    }
1199                    self.hidden_text.remove(&tool.id);
1200                    tool.subagent_run_id = None;
1201                    true
1202                });
1203                self.forget_chunk_ends(&expanded);
1204            }
1205            // History, not a rewrite: what it carries is remembered alongside
1206            // what the run has already shown.
1207            Event::RunStarted(started) => {
1208                if let Some(input) = &mut started.input {
1209                    self.seed_hidden(&input.messages, false);
1210                    input
1211                        .messages
1212                        .retain_mut(|message| self.show_message(message));
1213                }
1214            }
1215            Event::StateSnapshot(_)
1216            | Event::StateDelta(_)
1217            | Event::ToolCallResult(_)
1218            | Event::ActivitySnapshot(_)
1219            | Event::ActivityDelta(_) => {
1220                event.clear_subagent_run_id();
1221            }
1222            Event::RunFinished(finished) => Self::strip_interrupt_tags(finished),
1223            _ => {}
1224        }
1225        self.send(event, opener)
1226    }
1227
1228    fn forget_chunk_ends(&mut self, expanded: &[Event]) {
1229        for end in expanded {
1230            if matches!(
1231                end,
1232                Event::TextMessageEnd(_) | Event::ReasoningMessageEnd(_) | Event::ToolCallEnd(_)
1233            ) {
1234                if let Some((kind, id)) = Self::entity(end) {
1235                    self.open_visibility.remove(&(kind, id.to_owned()));
1236                }
1237            }
1238        }
1239    }
1240
1241    /// Whether the consumer sees an event with an id, by who owns it.
1242    fn judge(
1243        &mut self,
1244        event: &Event,
1245        tag: &Option<SubagentRunId>,
1246        owner: Option<&SubagentRunId>,
1247    ) -> bool {
1248        let owned = tag.is_some();
1249        match event {
1250            Event::SubagentStarted(_) | Event::SubagentFinished(_) | Event::SubagentError(_) => {
1251                false
1252            }
1253
1254            Event::TextMessageStart(e) => self.opened(Kind::Text, &e.message_id, owner),
1255            Event::TextMessageChunk(e) => match &e.message_id {
1256                Some(id) => self.opened(Kind::Text, id, owner),
1257                None => unreachable!("a bare chunk was resolved or passed through"),
1258            },
1259            Event::TextMessageContent(e) => self.continued(Kind::Text, &e.message_id, owned),
1260            Event::TextMessageEnd(e) => self.closed(Kind::Text, &e.message_id, owned),
1261
1262            Event::ReasoningStart(e) => self.opened(Kind::Reasoning, &e.message_id, owner),
1263            Event::ReasoningMessageStart(e) => self.opened(Kind::Reasoning, &e.message_id, owner),
1264            Event::ReasoningMessageChunk(e) => match &e.message_id {
1265                Some(id) => self.opened(Kind::Reasoning, id, owner),
1266                None => unreachable!("a bare chunk was resolved or passed through"),
1267            },
1268            Event::ReasoningMessageContent(e) => {
1269                self.continued(Kind::Reasoning, &e.message_id, owned)
1270            }
1271            Event::ReasoningMessageEnd(e) => self.closed(Kind::Reasoning, &e.message_id, owned),
1272            Event::ReasoningEnd(e) => self.closed(Kind::Reasoning, &e.message_id, owned),
1273
1274            Event::ToolCallStart(e) => self.call_opened(&e.tool_call_id, owner),
1275            Event::ToolCallChunk(e) => match &e.tool_call_id {
1276                Some(id) => self.call_opened(id, owner),
1277                None => unreachable!("a bare chunk was resolved or passed through"),
1278            },
1279            Event::ToolCallArgs(e) => self.call_continued(&e.tool_call_id, owned),
1280            Event::ToolCallEnd(e) => {
1281                let keep = self.call_continued(&e.tool_call_id, owned);
1282                self.open_visibility
1283                    .remove(&(Kind::Tool, e.tool_call_id.as_str().to_owned()));
1284                keep
1285            }
1286            // A result goes where its call went, whoever executed it: one for
1287            // a call the consumer never saw is a protocol error, and one for
1288            // a call it did see is owed.
1289            Event::ToolCallResult(e) => {
1290                if let Some(owner) = self.hidden_tool_calls.get(&e.tool_call_id) {
1291                    self.hidden_text.insert(e.message_id.clone(), owner.clone());
1292                } else {
1293                    self.hidden_text.remove(&e.message_id);
1294                }
1295                self.call_visibility
1296                    .get(&e.tool_call_id)
1297                    .copied()
1298                    .unwrap_or_else(|| !self.hidden_tool_calls.contains_key(&e.tool_call_id))
1299            }
1300
1301            // An activity is owned by the snapshot that minted it, and only a
1302            // replacing snapshot re-mints it — the verifiers' rule. A merge
1303            // into a visible activity is kept whoever wrote it, as a result
1304            // for a visible call is: the entity is the consumer's to keep
1305            // whole.
1306            Event::ActivitySnapshot(e) => {
1307                let existing = self.activities.get(&e.message_id).copied();
1308                let hidden = match existing {
1309                    Some(hidden) if !e.replace => hidden,
1310                    _ => owned,
1311                };
1312                self.activities.insert(e.message_id.clone(), hidden);
1313                !hidden
1314            }
1315            Event::ActivityDelta(e) => {
1316                !self.activities.get(&e.message_id).copied().unwrap_or(owned)
1317            }
1318
1319            // An opaque blob for an entity the consumer never saw goes with
1320            // the entity, as `FilterToolCalls` drops one for a dropped call.
1321            Event::ReasoningEncryptedValue(e) => {
1322                !owned
1323                    && match e.subtype {
1324                        crate::ReasoningEncryptedValueSubtype::ToolCall => !self
1325                            .hidden_tool_calls
1326                            .contains_key(&ToolCallId::new(e.entity_id.clone())),
1327                        crate::ReasoningEncryptedValueSubtype::Message => {
1328                            let id = MessageId::new(e.entity_id.clone());
1329                            !self.hidden_text.contains_key(&id)
1330                                && !self.hidden_reasoning.contains_key(&id)
1331                        }
1332                    }
1333            }
1334
1335            // The thread's state, whoever published it.
1336            Event::StateSnapshot(_) | Event::StateDelta(_) => true,
1337
1338            Event::RunFinished(_) | Event::RunError(_) => {
1339                self.open_visibility.clear();
1340                true
1341            }
1342
1343            _ => !owned,
1344        }
1345    }
1346
1347    fn owners_mut(&mut self, kind: Kind) -> &mut HashMap<MessageId, SubagentRunId> {
1348        match kind {
1349            Kind::Text => &mut self.hidden_text,
1350            Kind::Reasoning => &mut self.hidden_reasoning,
1351            Kind::Tool => unreachable!("tool calls have their own map"),
1352        }
1353    }
1354
1355    fn is_hidden(&self, kind: Kind, id: &str) -> bool {
1356        match kind {
1357            Kind::Text => self.hidden_text.contains_key(&MessageId::new(id)),
1358            Kind::Reasoning => self.hidden_reasoning.contains_key(&MessageId::new(id)),
1359            Kind::Tool => self.hidden_tool_calls.contains_key(&ToolCallId::new(id)),
1360        }
1361    }
1362
1363    /// A message opens under `owner` — the first writer keeps it — and the
1364    /// consumer sees it iff the owner is the parent, unless it is already
1365    /// open, in which case it keeps the visibility it was opened with.
1366    fn opened(&mut self, kind: Kind, id: &MessageId, owner: Option<&SubagentRunId>) -> bool {
1367        if let Some(owner) = owner {
1368            self.owners_mut(kind)
1369                .entry(id.clone())
1370                .or_insert_with(|| owner.clone());
1371        }
1372        *self
1373            .open_visibility
1374            .entry((kind, id.as_str().to_owned()))
1375            .or_insert(owner.is_none())
1376    }
1377
1378    fn continued(&self, kind: Kind, id: &MessageId, owned: bool) -> bool {
1379        !owned
1380            && self
1381                .open_visibility
1382                .get(&(kind, id.as_str().to_owned()))
1383                .copied()
1384                .unwrap_or_else(|| !self.is_hidden(kind, id.as_str()))
1385    }
1386
1387    fn closed(&mut self, kind: Kind, id: &MessageId, owned: bool) -> bool {
1388        let keep = self.continued(kind, id, owned);
1389        let key = (kind, id.as_str().to_owned());
1390        if !owned || self.open_visibility.get(&key) != Some(&true) {
1391            self.open_visibility.remove(&key);
1392        }
1393        keep
1394    }
1395
1396    fn call_opened(&mut self, id: &ToolCallId, owner: Option<&SubagentRunId>) -> bool {
1397        if let Some(owner) = owner {
1398            self.hidden_tool_calls
1399                .entry(id.clone())
1400                .or_insert_with(|| owner.clone());
1401        }
1402        let visible = *self
1403            .open_visibility
1404            .entry((Kind::Tool, id.as_str().to_owned()))
1405            .or_insert(owner.is_none());
1406        self.call_visibility.insert(id.clone(), visible);
1407        visible
1408    }
1409
1410    fn call_continued(&self, id: &ToolCallId, owned: bool) -> bool {
1411        !owned
1412            && self
1413                .open_visibility
1414                .get(&(Kind::Tool, id.as_str().to_owned()))
1415                .copied()
1416                .unwrap_or_else(|| !self.hidden_tool_calls.contains_key(id))
1417    }
1418
1419    /// Re-reads what a replay says about ownership. Authoritatively — a
1420    /// `MESSAGES_SNAPSHOT` — an untagged message takes its id back for the
1421    /// parent; as history — the `RUN_STARTED` echo — only the subagents'
1422    /// messages are added. A tool message goes where its call went, so one
1423    /// answering a visible call is not hidden however it is tagged.
1424    fn seed_hidden(&mut self, messages: &[crate::Message], authoritative: bool) {
1425        for message in messages {
1426            let id = message.id().clone();
1427            if let crate::Message::Activity(_) = message {
1428                if authoritative || !self.activities.contains_key(&id) {
1429                    self.activities
1430                        .insert(id, message.subagent_run_id().is_some());
1431                }
1432                continue;
1433            }
1434            if matches!(message, Message::Tool(_)) {
1435                continue; // Its owner follows the call, regardless of history order.
1436            }
1437            let kind = if matches!(message, Message::Reasoning(_)) {
1438                Kind::Reasoning
1439            } else {
1440                Kind::Text
1441            };
1442            let hidden_open =
1443                self.open_visibility.get(&(kind, id.as_str().to_owned())) == Some(&false);
1444            if let Some(owner) = message.subagent_run_id() {
1445                self.owners_mut(kind).insert(id.clone(), owner.clone());
1446            } else if authoritative && !hidden_open {
1447                self.owners_mut(kind).remove(&id);
1448            }
1449            if let Message::Assistant(assistant) = message {
1450                let owner = self.hidden_text.get(&id).cloned();
1451                for call in assistant.tool_calls.iter().flatten() {
1452                    if let Some(owner) = &owner {
1453                        self.hidden_tool_calls
1454                            .insert(call.id.clone(), owner.clone());
1455                        self.call_visibility.insert(call.id.clone(), false);
1456                    } else if authoritative || !self.call_visibility.contains_key(&call.id) {
1457                        self.hidden_tool_calls.remove(&call.id);
1458                        self.call_visibility.insert(call.id.clone(), true);
1459                    }
1460                }
1461            }
1462        }
1463        for message in messages {
1464            if let Message::Tool(tool) = message {
1465                if let Some(owner) = self.hidden_tool_calls.get(&tool.tool_call_id) {
1466                    self.hidden_text.insert(tool.id.clone(), owner.clone());
1467                } else if authoritative {
1468                    self.hidden_text.remove(&tool.id);
1469                }
1470            }
1471        }
1472    }
1473
1474    fn show_message(&self, message: &mut Message) -> bool {
1475        if let Message::Tool(tool) = message {
1476            if self.hidden_tool_calls.contains_key(&tool.tool_call_id) {
1477                return false;
1478            }
1479            tool.subagent_run_id = None;
1480            return true;
1481        }
1482        let kind = if matches!(message, Message::Reasoning(_)) {
1483            Kind::Reasoning
1484        } else {
1485            Kind::Text
1486        };
1487        message.subagent_run_id().is_none()
1488            && self
1489                .open_visibility
1490                .get(&(kind, message.id().as_str().to_owned()))
1491                != Some(&false)
1492    }
1493}
1494
1495/// The chunk stream a chunk belongs to: its kind and the id it names.
1496fn chunk_item(event: &Event) -> Option<(Kind, &str)> {
1497    Some(match event {
1498        Event::TextMessageChunk(e) => (Kind::Text, e.message_id.as_ref()?.as_str()),
1499        Event::ReasoningMessageChunk(e) => (Kind::Reasoning, e.message_id.as_ref()?.as_str()),
1500        Event::ToolCallChunk(e) => (Kind::Tool, e.tool_call_id.as_ref()?.as_str()),
1501        _ => return None,
1502    })
1503}
1504
1505/// The stream a chunk that names `id` continues, as the open-stream model
1506/// places it: the one assembling that id, which for an attributed chunk has
1507/// to be in the lane it is attributed to.
1508fn assembling<'a>(
1509    streams: &'a Streams,
1510    kind: Kind,
1511    id: &str,
1512    tag: &Option<SubagentRunId>,
1513) -> Option<&'a Stream> {
1514    streams
1515        .holder(kind, id)
1516        .filter(|stream| tag.is_none() || &stream.owner == tag)
1517}
1518
1519impl StreamTransformer for SubagentFilter {
1520    /// History, as the `RUN_STARTED` echo would carry it: what a subagent
1521    /// owned in an earlier run stays hidden in this one, echo or not.
1522    fn seed(&mut self, history: &[Message]) {
1523        if self.mode == SubagentVisibility::Hidden {
1524            self.seed_hidden(history, false);
1525        }
1526    }
1527
1528    /// What was sent is what a consumer holds, so the chunk streams it left
1529    /// open are the ones a consumer has open now.
1530    fn replay(&mut self, sent: &[Event]) {
1531        for event in sent {
1532            self.record_output(event);
1533        }
1534    }
1535
1536    fn transform(&mut self, event: Event) -> Vec<Event> {
1537        match self.mode {
1538            SubagentVisibility::Attributed => vec![event],
1539            SubagentVisibility::Inline => self.inline(event),
1540            SubagentVisibility::Hidden => self.hidden(event),
1541        }
1542    }
1543}
1544
1545#[cfg(test)]
1546mod tests {
1547    use super::*;
1548    use crate::{ReasoningEncryptedValueSubtype, TextMessageRole};
1549    use serde_json::json;
1550
1551    #[test]
1552    fn allow_list_drops_everything_unlisted() {
1553        let mut filter = FilterToolCalls::allow(["search"]);
1554        assert_eq!(
1555            filter
1556                .transform(Event::tool_call_start("c1", "search"))
1557                .len(),
1558            1
1559        );
1560        assert!(
1561            filter
1562                .transform(Event::tool_call_start("c2", "delete_everything"))
1563                .is_empty()
1564        );
1565        assert!(
1566            filter
1567                .transform(Event::tool_call_args("c2", "{}"))
1568                .is_empty()
1569        );
1570        assert!(
1571            filter
1572                .transform(Event::tool_call_result("m1", "c2", "gone"))
1573                .is_empty()
1574        );
1575        assert_eq!(filter.transform(Event::tool_call_args("c1", "{}")).len(), 1);
1576    }
1577
1578    #[test]
1579    fn filter_leaves_unrelated_events_alone() {
1580        let mut filter = FilterToolCalls::deny(["nope"]);
1581        let event = Event::text_message_start("m1", TextMessageRole::Assistant);
1582        assert_eq!(filter.transform(event.clone()), vec![event]);
1583    }
1584
1585    #[test]
1586    fn filter_drops_encrypted_reasoning_for_a_dropped_call() {
1587        let mut filter = FilterToolCalls::deny(["nope"]);
1588        filter.transform(Event::tool_call_start("c1", "nope"));
1589        let blob = Event::reasoning_encrypted_value(
1590            ReasoningEncryptedValueSubtype::ToolCall,
1591            "c1",
1592            "opaque",
1593        );
1594        assert!(filter.transform(blob).is_empty());
1595    }
1596
1597    /// Nothing named the call, so the filter cannot tell it from one it
1598    /// removed where it could not see: what belongs to it is dropped.
1599    #[test]
1600    fn an_event_of_a_call_nothing_named_is_dropped() {
1601        let blob = Event::reasoning_encrypted_value(
1602            ReasoningEncryptedValueSubtype::ToolCall,
1603            "c1",
1604            "opaque",
1605        );
1606        let chunk = |id: Option<&str>| {
1607            Event::tool_call_chunk(id.map(ToolCallId::new), None, Some("{}".to_owned()))
1608        };
1609        let unknown = [
1610            Event::tool_call_args("c1", "{}"),
1611            Event::tool_call_end("c1"),
1612            Event::tool_call_result("m1", "c1", "done"),
1613            blob,
1614            chunk(Some("c1")),
1615            chunk(None),
1616        ];
1617        for mut filter in [
1618            FilterToolCalls::deny(["nope"]),
1619            FilterToolCalls::allow(["search"]),
1620        ] {
1621            for event in &unknown {
1622                assert_eq!(filter.transform(event.clone()), [], "{event:?}");
1623            }
1624            // Named, the same call is judged, and what follows goes with it.
1625            let start = Event::tool_call_start("c1", "search");
1626            assert_eq!(filter.transform(start.clone()), [start]);
1627            let args = Event::tool_call_args("c1", "{}");
1628            assert_eq!(filter.transform(args.clone()), [args]);
1629        }
1630    }
1631
1632    /// A dropped event is one its producer takes as sent, since the emit
1633    /// returned `Ok`: one of a call nothing named still ends the chunk
1634    /// stream in its lane.
1635    #[test]
1636    fn an_event_dropped_for_an_unknown_call_ends_the_chunk_stream_in_its_lane() {
1637        let open = || Event::tool_call_chunk(Some("c1".into()), Some("search".into()), None);
1638        let bare = || Event::tool_call_chunk(None, None, Some("{}".into()));
1639
1640        let mut filter = FilterToolCalls::deny(["nope"]);
1641        assert_eq!(filter.transform(open()), [open()]);
1642        assert_eq!(filter.transform(bare()), [bare()]);
1643        assert_eq!(filter.transform(Event::tool_call_args("c9", "{}")), []);
1644        assert_eq!(filter.transform(bare()), []);
1645
1646        // A chunk that names such a call takes up its stream, so the chunks
1647        // with no id after it are its own, and not the call that passes.
1648        let mut filter = FilterToolCalls::deny(["nope"]);
1649        assert_eq!(filter.transform(open()), [open()]);
1650        let unknown = Event::tool_call_chunk(Some("c9".into()), None, Some("{}".into()));
1651        assert_eq!(filter.transform(unknown), []);
1652        assert_eq!(filter.transform(bare()), []);
1653    }
1654
1655    #[test]
1656    fn a_restated_conversation_loses_only_what_the_filter_is_about() {
1657        use crate::{AssistantMessage, ToolCall};
1658
1659        let untouched = [
1660            // Neither content nor calls, and no filtered call was taken out
1661            // of it: it stays as it is.
1662            Message::Assistant(AssistantMessage {
1663                id: "empty".into(),
1664                ..Default::default()
1665            }),
1666            Message::Assistant(AssistantMessage {
1667                id: "no-calls".into(),
1668                tool_calls: Some(Vec::new()),
1669                ..Default::default()
1670            }),
1671            Message::Assistant(AssistantMessage {
1672                id: "public".into(),
1673                tool_calls: Some(vec![ToolCall::new("c-public", "search", "{}")]),
1674                ..Default::default()
1675            }),
1676            Message::tool("answer", "c-public", "1 hit"),
1677        ];
1678        let mut restated = untouched.to_vec();
1679        restated.extend([
1680            // Its content is all that is left of it.
1681            Message::Assistant(AssistantMessage {
1682                id: "says-and-calls".into(),
1683                content: Some("One moment.".into()),
1684                tool_calls: Some(vec![ToolCall::new("c-private", "nope", "{}")]),
1685                ..Default::default()
1686            }),
1687            // Nothing is left of it: an empty content is no content.
1688            Message::Assistant(AssistantMessage {
1689                id: "only-calls".into(),
1690                content: Some(String::new()),
1691                encrypted_value: Some("opaque".into()),
1692                tool_calls: Some(vec![ToolCall::new("c-private-2", "nope", "{}")]),
1693                ..Default::default()
1694            }),
1695            Message::tool("hidden-answer", "c-private", "everything"),
1696            // No call in the conversation, or before it, has this id.
1697            Message::tool("orphan", "c-unheard-of", "whose result is this?"),
1698        ]);
1699
1700        let mut filter = FilterToolCalls::deny(["nope"]);
1701        let out = filter.transform(Event::messages_snapshot(restated));
1702        let [Event::MessagesSnapshot(snapshot)] = out.as_slice() else {
1703            panic!("the snapshot is kept: {out:?}");
1704        };
1705        let mut expected = untouched.to_vec();
1706        expected.push(Message::assistant("says-and-calls", "One moment."));
1707        assert_eq!(snapshot.messages, expected);
1708
1709        // The calls the snapshot carried were judged as it passed.
1710        let answered = Event::tool_call_result("m1", "c-public", "again");
1711        assert_eq!(filter.transform(answered.clone()), [answered]);
1712        let hidden = Event::tool_call_result("m2", "c-private", "again");
1713        assert_eq!(filter.transform(hidden), []);
1714    }
1715
1716    /// What was sent names calls, which the filter learns, and leaves a
1717    /// chunk stream open, which it does not take up: the earlier producer
1718    /// may have had another stream open in that lane, one its filter
1719    /// removed. A chunk that names the call takes it up.
1720    #[test]
1721    fn a_filter_learns_the_calls_that_were_sent_and_not_their_chunk_streams() {
1722        let sent = [
1723            Event::run_started("t", "r"),
1724            Event::tool_call_start("c1", "search"),
1725            Event::tool_call_args("c1", "{"),
1726            Event::tool_call_chunk(Some("c2".into()), Some("lookup".into()), Some("{".into())),
1727        ];
1728        let bare = || Event::tool_call_chunk(None, None, Some("}".into()));
1729        let named = || Event::tool_call_chunk(Some("c2".into()), None, Some("}".into()));
1730        let args = || Event::tool_call_args("c1", "}");
1731
1732        let mut filter = FilterToolCalls::allow(["search", "lookup"]);
1733        filter.replay(&sent);
1734        assert_eq!(filter.transform(bare()), []);
1735        assert_eq!(filter.transform(named()), [named()]);
1736        assert_eq!(filter.transform(bare()), [bare()]);
1737        assert_eq!(filter.transform(args()), [args()]);
1738        // The explicit event ended the chunk stream in its lane: a chunk
1739        // that names no id has nothing left to continue.
1740        assert_eq!(filter.transform(bare()), []);
1741
1742        // Each call is judged by its own name.
1743        let mut filter = FilterToolCalls::deny(["lookup"]);
1744        filter.replay(&sent);
1745        assert_eq!(filter.transform(named()), []);
1746        assert_eq!(filter.transform(bare()), []);
1747        assert_eq!(filter.transform(args()), [args()]);
1748    }
1749
1750    #[test]
1751    fn a_call_the_history_answered_is_not_waiting_for_a_result() {
1752        use crate::{AssistantMessage, ToolCall};
1753
1754        let history = [
1755            Message::Assistant(AssistantMessage {
1756                id: "a0".into(),
1757                tool_calls: Some(vec![
1758                    ToolCall::new("answered", "load", "{}"),
1759                    ToolCall::new("waiting", "load", "{}"),
1760                    ToolCall::new("another-tool", "search", "{}"),
1761                ]),
1762                ..Default::default()
1763            }),
1764            Message::tool("t0", "answered", r#"{"a":0}"#),
1765        ];
1766        let mut promote = ToolResultToState::snapshot("load");
1767        promote.seed(&history);
1768        for (call, promoted) in [
1769            ("answered", false),
1770            ("another-tool", false),
1771            ("waiting", true),
1772        ] {
1773            let result = Event::tool_call_result("m1", call, r#"{"a":1}"#);
1774            let out = promote.transform(result);
1775            assert_eq!(out.len(), if promoted { 2 } else { 1 }, "{call}");
1776        }
1777        // One result answers a call: a second is not promoted again.
1778        let again = Event::tool_call_result("m2", "waiting", r#"{"a":2}"#);
1779        assert_eq!(promote.transform(again).len(), 1);
1780    }
1781
1782    #[test]
1783    fn a_malformed_patch_is_not_promoted() {
1784        let mut promote = ToolResultToState::delta("patch_state");
1785        for (call, content) in [
1786            ("c1", r#"[{"op":"add","path":"oops","value":1}]"#),
1787            ("c2", r#"[{"op":"move","from":"oops","path":"/a"}]"#),
1788            ("c3", r#"[{"op":"add","path":"/a/~2","value":1}]"#),
1789            ("c4", r#"[{"op":"add","path":"/a"}]"#),
1790            ("c5", r#"[{"op":"replace","path":"/a"}]"#),
1791            ("c6", r#"[{"op":"test","path":"/a"}]"#),
1792        ] {
1793            promote.transform(Event::tool_call_start(call, "patch_state"));
1794            let result = Event::tool_call_result("m1", call, content);
1795            assert_eq!(promote.transform(result.clone()), vec![result], "{content}");
1796        }
1797        // The root is a pointer, and so is an escaped segment.
1798        promote.transform(Event::tool_call_start("valid", "patch_state"));
1799        let content = r#"[{"op":"add","path":"/a~1b","value":null,"note":"keep"},{"op":"test","path":"","value":{}}]"#;
1800        let result = Event::tool_call_result("m1", "valid", content);
1801        let delta =
1802            Event::state_delta(serde_json::from_str::<Vec<PatchOperation>>(content).unwrap());
1803        assert_eq!(promote.transform(result.clone()), [result, delta]);
1804    }
1805
1806    #[test]
1807    fn promoting_keeps_the_result_by_default() {
1808        let mut promote = ToolResultToState::snapshot("load");
1809        promote.transform(Event::tool_call_start("c1", "load"));
1810        let result = Event::tool_call_result("m1", "c1", r#"{"a":1}"#);
1811        assert_eq!(
1812            promote.transform(result.clone()),
1813            vec![result, Event::state_snapshot(json!({"a": 1}))]
1814        );
1815    }
1816
1817    #[test]
1818    fn promoting_a_patch_emits_a_delta() {
1819        let mut promote = ToolResultToState::delta("patch_state").replacing();
1820        promote.transform(Event::tool_call_start("c1", "patch_state"));
1821        let content = r#"[{"op":"replace","path":"/step","value":2}]"#;
1822        assert_eq!(
1823            promote.transform(Event::tool_call_result("m1", "c1", content)),
1824            vec![Event::state_delta(vec![PatchOperation::replace(
1825                "/step", 2
1826            )])]
1827        );
1828    }
1829
1830    #[test]
1831    fn unparseable_content_passes_through_untouched() {
1832        let mut promote = ToolResultToState::snapshot("load").replacing();
1833        promote.transform(Event::tool_call_start("c1", "load"));
1834        let result = Event::tool_call_result("m1", "c1", "not json");
1835        assert_eq!(promote.transform(result.clone()), vec![result]);
1836    }
1837
1838    #[test]
1839    fn multimodal_result_is_not_promoted_to_state() {
1840        let mut promote = ToolResultToState::snapshot("load").replacing();
1841        promote.transform(Event::tool_call_start("c1", "load"));
1842        let result =
1843            Event::tool_call_result("m1", "c1", vec![crate::InputContent::text(r#"{"a":1}"#)]);
1844        assert_eq!(promote.transform(result.clone()), vec![result]);
1845    }
1846
1847    #[test]
1848    fn other_tools_are_not_promoted() {
1849        let mut promote = ToolResultToState::snapshot("load");
1850        promote.transform(Event::tool_call_start("c1", "something_else"));
1851        let result = Event::tool_call_result("m1", "c1", r#"{"a":1}"#);
1852        assert_eq!(promote.transform(result.clone()), vec![result]);
1853    }
1854
1855    #[test]
1856    fn chain_runs_transformers_in_order() {
1857        let mut chain = TransformerChain::new()
1858            .with(FilterToolCalls::deny(["load"]))
1859            .with(ToolResultToState::snapshot("load"));
1860        // The filter removes the call first, so the promoter never sees it.
1861        assert!(
1862            chain
1863                .transform(Event::tool_call_start("c1", "load"))
1864                .is_empty()
1865        );
1866        assert!(
1867            chain
1868                .transform(Event::tool_call_result("m1", "c1", r#"{"a":1}"#))
1869                .is_empty()
1870        );
1871    }
1872}