Skip to main content

ag_ui/client/
apply.rs

1//! Turning a stream of events into materialised state.
2//!
3//! Consuming AG-UI is not "read a response". The agent sends deltas — a message
4//! opens, text arrives a fragment at a time, tool arguments accumulate as
5//! unparseable JSON fragments, state moves by RFC 6902 patch. [`Applier`] is the
6//! state machine that folds all of that back into something a UI can draw:
7//! a message list, reasoning and activities included, and a JSON state
8//! document.
9//!
10//! It is a plain synchronous struct. No async, no runtime, no I/O — feed it
11//! events from anywhere.
12//!
13//! ```
14//! # #[cfg(feature = "client")]
15//! # fn main() -> Result<(), ag_ui::client::Error> {
16//! use ag_ui::client::apply::Applier;
17//! use ag_ui::{Event, TextMessageRole};
18//!
19//! let mut applier = Applier::new();
20//! for event in [
21//!     Event::run_started("thread-1", "run-1"),
22//!     Event::text_message_start("msg-1", TextMessageRole::Assistant),
23//!     Event::text_message_content("msg-1", "Hello, "),
24//!     Event::text_message_content("msg-1", "world"),
25//!     Event::text_message_end("msg-1"),
26//!     Event::run_finished_success("thread-1", "run-1"),
27//! ] {
28//!     applier.apply(&event)?;
29//! }
30//!
31//! assert_eq!(applier.messages().len(), 1);
32//! assert_eq!(applier.text_of("msg-1"), Some("Hello, world"));
33//! # Ok(())
34//! # }
35//! # #[cfg(not(feature = "client"))]
36//! # fn main() {}
37//! ```
38//!
39//! # What it does not do
40//!
41//! The applier is *tolerant*: an orphan `TEXT_MESSAGE_CONTENT` opens a message
42//! rather than failing, because a half-drawn conversation beats a blank screen.
43//! Catching the producer's mistake is [`crate::client::verify`]'s job, and
44//! [`crate::client::Thread`] runs both. The one thing the applier refuses to do
45//! quietly is corrupt state: a patch that does not apply is an error.
46//!
47//! It applies the explicit form of the protocol only. A `*_CHUNK` event
48//! stands for a start, content and an end that depend on what came before it,
49//! and a retired `THINKING_*` event for a `REASONING_*` one; expanding the
50//! first is [`crate::client::chunks`]'s job and translating the second is the
51//! compatibility boundary's
52//! ([`TransportStream::into_events`](crate::client::transport::TransportStream::into_events),
53//! [`enforce_events`](crate::client::transport::enforce_events)). Both run
54//! before the applier in a [`Thread`](crate::client::Thread). Handed one
55//! directly, [`Applier::apply`] returns [`Error::Unsupported`] and changes
56//! nothing.
57
58// The THINKING_* events are deprecated, and this module has to name them to
59// refuse them. Downstream users still get the warnings.
60#![allow(deprecated)]
61
62use std::collections::HashMap;
63
64use crate::{
65    ActivityDeltaEvent, ActivityMessage, ActivitySnapshotEvent, AssistantMessage, DeveloperMessage,
66    Event, InputContent, Interrupt, JsonObject, Message, MessageId, PatchOperation,
67    ReasoningEncryptedValueEvent, ReasoningEncryptedValueSubtype, ReasoningMessage, RunId,
68    RunOutcome, SubagentErrorEvent, SubagentFinishedEvent, SubagentOutcome, SubagentRunId,
69    SubagentStartedEvent, SystemMessage, TextInputContent, TextMessageRole, ThreadId, ToolCall,
70    ToolCallId, ToolContent, ToolMessage, UserContent, UserMessage,
71};
72use serde::{Deserialize, Serialize};
73use serde_json::Value;
74
75use crate::client::error::{Error, Result};
76use crate::metadata::merge_metadata_into;
77
78/// What one event changed.
79///
80/// Returned by [`Applier::apply`] so a UI can redraw one row instead of the
81/// whole conversation. Every variant that names a message carries its index
82/// into [`Applier::messages`].
83#[derive(Clone, Debug, PartialEq)]
84#[non_exhaustive]
85pub enum Changed {
86    /// Nothing a view would redraw: `STEP_*`, `RAW`, `CUSTOM`, a reasoning
87    /// span (`REASONING_START`, `REASONING_END`), or an event whose target
88    /// does not exist.
89    Nothing,
90    /// One message was created, appended to, or completed.
91    Message(MessageChange),
92    /// `MESSAGES_SNAPSHOT` replaced the whole list. Messages may have been
93    /// removed, so a view must redraw all of it.
94    MessagesReplaced,
95    /// The application state was replaced or patched.
96    State,
97    /// A `REASONING_MESSAGE_*` event created, appended to or completed a
98    /// message, or a reasoning message took an encrypted value. The message
99    /// is in [`Applier::messages`] like any other. The variant is its own so
100    /// that a view can draw reasoning apart from the reply, or leave it out.
101    Reasoning(ReasoningChange),
102    /// A subagent was announced, resumed, finished, suspended or failed. What
103    /// it *produces* arrives as ordinary message and reasoning changes,
104    /// carrying its id; this is the lifecycle. See [`Applier::subagents`].
105    Subagent(SubagentChange),
106    /// `RUN_STARTED`.
107    RunStarted {
108        /// The conversation the run belongs to.
109        thread_id: ThreadId,
110        /// The run that started.
111        run_id: RunId,
112    },
113    /// `RUN_FINISHED`. An absent outcome is reported as
114    /// [`RunOutcome::Success`], which is what the protocol says it means.
115    RunFinished {
116        /// How the run ended.
117        outcome: RunOutcome,
118        /// The agent's return value, if it sent one.
119        result: Option<Value>,
120    },
121    /// `RUN_ERROR`.
122    RunError {
123        /// What went wrong, for a human.
124        message: String,
125        /// The machine-readable code, when the agent sent one.
126        code: Option<String>,
127    },
128}
129
130/// Which message changed, and how.
131///
132/// `#[non_exhaustive]`: read the fields, match with `..`, and build one, to
133/// compare with what [`Applier::apply`] returned, with [`MessageChange::new`].
134///
135/// ```
136/// # #[cfg(feature = "client")]
137/// # fn main() -> Result<(), ag_ui::client::Error> {
138/// use ag_ui::client::apply::{Applier, Changed, MessageChange, MessageChangeKind};
139/// use ag_ui::{Event, TextMessageRole};
140///
141/// let mut applier = Applier::new();
142/// let started = applier.apply(&Event::text_message_start("m-1", TextMessageRole::Assistant))?;
143/// assert_eq!(
144///     started,
145///     Changed::Message(MessageChange::new(0, "m-1", MessageChangeKind::Started))
146/// );
147/// # Ok(())
148/// # }
149/// # #[cfg(not(feature = "client"))]
150/// # fn main() {}
151/// ```
152///
153/// A struct literal does not compile outside this crate:
154///
155/// ```compile_fail,E0639
156/// use ag_ui::client::apply::{MessageChange, MessageChangeKind};
157///
158/// let change = MessageChange { index: 0, id: "m-1".into(), kind: MessageChangeKind::Ended };
159/// ```
160#[derive(Clone, Debug, PartialEq)]
161#[non_exhaustive]
162pub struct MessageChange {
163    /// Index into [`Applier::messages`].
164    pub index: usize,
165    /// The message's id.
166    pub id: MessageId,
167    /// What happened to it.
168    pub kind: MessageChangeKind,
169}
170
171impl MessageChange {
172    /// A change of `kind` to the message `id`, at `index` of
173    /// [`Applier::messages`].
174    pub fn new(index: usize, id: impl Into<MessageId>, kind: MessageChangeKind) -> Self {
175        Self {
176            index,
177            id: id.into(),
178            kind,
179        }
180    }
181}
182
183/// What happened to a message.
184#[derive(Clone, Debug, PartialEq)]
185#[non_exhaustive]
186pub enum MessageChangeKind {
187    /// Local consumption stopped before the producer completed this message.
188    Aborted,
189    /// The message was created and is now open for content.
190    Started,
191    /// Text was appended.
192    Content {
193        /// The text this event appended.
194        delta: String,
195    },
196    /// The message was closed; no more content will arrive for it.
197    Ended,
198    /// A tool call was attached to the message. Several can be open at once —
199    /// a model asking for two things at once opens two.
200    ToolCallStarted {
201        /// The call's id.
202        tool_call_id: ToolCallId,
203        /// The tool being called.
204        name: String,
205    },
206    /// Argument JSON was appended to a tool call.
207    ///
208    /// Parallel calls interleave their events, so consecutive `ToolCallArgs`
209    /// need not belong to the same call: `tool_call_id` is what separates them,
210    /// and arrival order is the only nesting there is — see the [thread module
211    /// docs](crate::client::thread).
212    ToolCallArgs {
213        /// The call being appended to.
214        tool_call_id: ToolCallId,
215        /// The fragment this event appended. Rarely valid JSON on its own.
216        delta: String,
217    },
218    /// A tool call's arguments are complete.
219    ToolCallEnded {
220        /// The call that closed.
221        tool_call_id: ToolCallId,
222    },
223    /// A tool result arrived and was appended as a new message.
224    ToolResult {
225        /// The call this result answers.
226        tool_call_id: ToolCallId,
227    },
228    /// An activity was published or patched.
229    Activity,
230    /// A provider's opaque reasoning blob was attached to the message or to one
231    /// of its tool calls.
232    EncryptedValue,
233}
234
235/// Which reasoning message changed, and how.
236///
237/// `#[non_exhaustive]`: read the fields, match with `..`, and build one, to
238/// compare with what [`Applier::apply`] returned, with
239/// [`ReasoningChange::new`]. A struct literal does not compile outside this
240/// crate:
241///
242/// ```compile_fail,E0639
243/// use ag_ui::client::apply::{ReasoningChange, ReasoningChangeKind};
244///
245/// let change = ReasoningChange { index: 0, id: "r-1".into(), kind: ReasoningChangeKind::Ended };
246/// ```
247#[derive(Clone, Debug, PartialEq)]
248#[non_exhaustive]
249pub struct ReasoningChange {
250    /// Index into [`Applier::messages`].
251    pub index: usize,
252    /// The reasoning message's id.
253    pub id: MessageId,
254    /// What happened to it.
255    pub kind: ReasoningChangeKind,
256}
257
258impl ReasoningChange {
259    /// A change of `kind` to the reasoning message `id`, at `index` of
260    /// [`Applier::messages`].
261    pub fn new(index: usize, id: impl Into<MessageId>, kind: ReasoningChangeKind) -> Self {
262        Self {
263            index,
264            id: id.into(),
265            kind,
266        }
267    }
268}
269
270/// What happened to a reasoning message.
271///
272/// The message is what `REASONING_MESSAGE_START`, `_CONTENT` and `_END`
273/// assemble. The span around it, `REASONING_START` to `REASONING_END`, opens
274/// no message and reports no change, whether or not it carries the message's
275/// id. So [`Started`](Self::Started) and [`Ended`](Self::Ended) arrive once
276/// per message, and a consumer that prints a finished thought prints it once.
277#[derive(Clone, Debug, PartialEq)]
278#[non_exhaustive]
279pub enum ReasoningChangeKind {
280    /// Consumption stopped before this reasoning message completed.
281    Aborted,
282    /// The reasoning message was created.
283    Started,
284    /// Reasoning text was appended.
285    Content {
286        /// The text this event appended.
287        delta: String,
288    },
289    /// The reasoning message was closed; no more content will arrive for it.
290    Ended,
291    /// A provider's opaque reasoning blob was attached.
292    EncryptedValue,
293}
294
295/// One subagent invocation the run has announced, as the applier tracks it.
296///
297/// Keyed by [`run_id`](Self::run_id), which names *this invocation* — running
298/// the same subagent twice yields two entries — while [`name`](Self::name) is
299/// the reusable half, for display. Key transient UI by the id; persist
300/// nothing by it.
301#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
302#[non_exhaustive]
303pub struct Subagent {
304    /// The invocation's id, as every event it produced carries it.
305    pub run_id: SubagentRunId,
306    /// The subagent's declared type or name.
307    pub name: String,
308    /// Human-readable description, when announced.
309    pub description: Option<String>,
310    /// The enclosing subagent, when subagents nest.
311    pub parent_subagent_run_id: Option<SubagentRunId>,
312    /// The tool call that spawned it, for the agents-as-tools pattern.
313    pub parent_tool_call_id: Option<ToolCallId>,
314    /// The message that held that tool call.
315    pub parent_message_id: Option<MessageId>,
316    /// Where the invocation stands.
317    pub status: SubagentStatus,
318}
319
320/// Where a subagent invocation stands.
321#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
322#[non_exhaustive]
323pub enum SubagentStatus {
324    /// The enclosing run stopped without confirming this invocation's outcome.
325    Aborted,
326    /// Announced and not yet closed.
327    Running,
328    /// Closed with a success outcome — or with none, the legacy reading.
329    Finished {
330        /// The completion payload, if it sent one.
331        result: Option<Value>,
332    },
333    /// Closed because the run paused on interrupts the subagent raised. The
334    /// same id may be announced again by the run that resumes it, and that
335    /// arrives as [`SubagentChangeKind::Resumed`] rather than as a second
336    /// subagent.
337    Suspended {
338        /// The completion payload so far, if it sent one.
339        result: Option<Value>,
340        /// The run-level interrupts it directly owns — empty for an ancestor
341        /// suspended because a descendant interrupted. Each such
342        /// [`Interrupt`] carries the id back as `subagent_run_id`.
343        interrupt_ids: Vec<String>,
344    },
345    /// Closed by `SUBAGENT_ERROR`.
346    Failed {
347        /// What went wrong, for a human.
348        message: String,
349        /// The machine-readable code, when the agent sent one.
350        code: Option<String>,
351    },
352}
353
354/// Which subagent changed, and how.
355///
356/// `#[non_exhaustive]`: read the fields, match with `..`, and build one, to
357/// compare with what [`Applier::apply`] returned, with
358/// [`SubagentChange::new`]. A struct literal does not compile outside this
359/// crate:
360///
361/// ```compile_fail,E0639
362/// use ag_ui::client::apply::{SubagentChange, SubagentChangeKind};
363///
364/// let change = SubagentChange { index: 0, run_id: "s-1".into(), kind: SubagentChangeKind::Finished };
365/// ```
366#[derive(Clone, Debug, PartialEq)]
367#[non_exhaustive]
368pub struct SubagentChange {
369    /// Index into [`Applier::subagents`].
370    pub index: usize,
371    /// The invocation's id.
372    pub run_id: SubagentRunId,
373    /// What happened to it.
374    pub kind: SubagentChangeKind,
375}
376
377impl SubagentChange {
378    /// A change of `kind` to the invocation `run_id`, at `index` of
379    /// [`Applier::subagents`].
380    pub fn new(index: usize, run_id: impl Into<SubagentRunId>, kind: SubagentChangeKind) -> Self {
381        Self {
382            index,
383            run_id: run_id.into(),
384            kind,
385        }
386    }
387}
388
389/// What happened to a subagent invocation.
390#[derive(Clone, Debug, PartialEq)]
391#[non_exhaustive]
392pub enum SubagentChangeKind {
393    /// The enclosing run stopped; no business outcome was inferred.
394    Aborted,
395    /// A new invocation was announced.
396    Started,
397    /// A suspended invocation was announced again — a continuation, not a
398    /// second subagent. Move its group from waiting back to running.
399    Resumed,
400    /// The invocation completed.
401    Finished,
402    /// The invocation paused on interrupts; see [`SubagentStatus::Suspended`].
403    Suspended,
404    /// The invocation failed.
405    Failed,
406}
407
408/// The ids one kind of stream has open, in the order they opened.
409///
410/// Kept by id, so that opening and closing one costs the same however many
411/// are open: a producer that opens messages and never closes them does not
412/// make each later event slower. The order is read only when a run stops.
413#[derive(Clone, Debug, Default)]
414struct Open {
415    /// Each open id, with its place in the order of opening.
416    opened: HashMap<MessageId, u64>,
417    /// The place the next one opened takes.
418    next: u64,
419}
420
421impl Open {
422    /// Opens `id`. One that is open already moves behind the others.
423    fn open(&mut self, id: MessageId) {
424        self.opened.insert(id, self.next);
425        self.next += 1;
426    }
427
428    fn close(&mut self, id: &MessageId) {
429        self.opened.remove(id);
430    }
431
432    fn contains(&self, id: &MessageId) -> bool {
433        self.opened.contains_key(id)
434    }
435
436    fn clear(&mut self) {
437        self.opened.clear();
438    }
439
440    /// The open ids, the one opened first first.
441    fn in_order(&self) -> Vec<&MessageId> {
442        let mut ids: Vec<_> = self.opened.iter().collect();
443        ids.sort_unstable_by_key(|(_, place)| **place);
444        ids.into_iter().map(|(id, _)| id).collect()
445    }
446}
447
448/// The materialised view of a run.
449///
450/// See the [module docs](self) for the shape of the problem this solves.
451#[derive(Clone, Debug)]
452pub struct Applier {
453    messages: Vec<Message>,
454    by_id: HashMap<MessageId, usize>,
455    /// Tool call id to the index of the assistant message that owns it.
456    tool_calls: HashMap<ToolCallId, usize>,
457    /// Carriers allocated for parentless calls in this run. A chunk stream
458    /// can reopen after another lane interrupts it and must keep its carrier.
459    synthetic_carriers: HashMap<ToolCallId, MessageId>,
460    /// Text messages open for content, in the order they opened — several at
461    /// once under concurrent subagents. What a run that stops reports as
462    /// aborted. An id stays here when a `MESSAGES_SNAPSHOT` removes its
463    /// message: the stream is still open, and has nowhere to write.
464    open_text: Open,
465    /// The same for reasoning messages: what `REASONING_MESSAGE_START` opened
466    /// and `REASONING_MESSAGE_END` has not closed.
467    open_reasoning: Open,
468    /// The owner the first `TEXT_MESSAGE_START` for an id gave it, where the
469    /// conversation held that id as a reasoning or an activity message, so
470    /// the text went into that message or nowhere. The ordering rules keep
471    /// text apart from reasoning and record that owner for the id as a text
472    /// message's, which is whose a tool call naming the id as its parent is.
473    claimed: HashMap<MessageId, Option<SubagentRunId>>,
474    state: Value,
475    thread_id: Option<ThreadId>,
476    run_id: Option<RunId>,
477    interrupts: Vec<Interrupt>,
478    /// The subagent invocations announced so far, in announcement order.
479    subagents: Vec<Subagent>,
480    subagent_by_id: HashMap<SubagentRunId, usize>,
481}
482
483impl Default for Applier {
484    fn default() -> Self {
485        Self::new()
486    }
487}
488
489impl Applier {
490    /// An empty applier: no messages, and `{}` for state.
491    ///
492    /// The state starts as an empty object rather than `null` so that the first
493    /// `STATE_DELTA` of a run has something to patch.
494    pub fn new() -> Self {
495        Self {
496            messages: Vec::new(),
497            by_id: HashMap::new(),
498            tool_calls: HashMap::new(),
499            synthetic_carriers: HashMap::new(),
500            open_text: Open::default(),
501            open_reasoning: Open::default(),
502            claimed: HashMap::new(),
503            state: Value::Object(JsonObject::new()),
504            thread_id: None,
505            run_id: None,
506            interrupts: Vec::new(),
507            subagents: Vec::new(),
508            subagent_by_id: HashMap::new(),
509        }
510    }
511
512    /// Seeds the applier with an existing conversation.
513    #[must_use]
514    pub fn with_messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
515        self.replace_messages(messages.into());
516        self
517    }
518
519    /// Seeds the applier with an existing state document.
520    #[must_use]
521    pub fn with_state(mut self, state: impl Into<Value>) -> Self {
522        self.state = state.into();
523        self
524    }
525
526    /// The assembled conversation, oldest first: every role, reasoning and
527    /// activity included, each message where it arrived.
528    pub fn messages(&self) -> &[Message] {
529        &self.messages
530    }
531
532    /// Material already delivered for a message that is still streaming.
533    #[cfg(feature = "server")]
534    pub(crate) fn open_messages(&self) -> impl Iterator<Item = &Message> {
535        self.messages.iter().filter(|message| {
536            self.open_text.contains(message.id()) || self.open_reasoning.contains(message.id())
537        })
538    }
539
540    pub(crate) fn tool_call_holder(&self, call: &ToolCallId) -> Option<&MessageId> {
541        self.messages
542            .get(*self.tool_calls.get(call)?)
543            .map(Message::id)
544    }
545
546    /// The message with this id, if the applier has seen one.
547    pub fn message(&self, id: &MessageId) -> Option<&Message> {
548        self.by_id
549            .get(id)
550            .and_then(|index| self.messages.get(*index))
551    }
552
553    /// The text of the message with this id, for the roles that carry plain
554    /// text. Multimodal user messages return only their text parts' first
555    /// fragment; use [`Applier::message`] for the whole payload.
556    pub fn text_of(&self, id: impl Into<MessageId>) -> Option<&str> {
557        match self.message(&id.into())? {
558            Message::Assistant(m) => m.content.as_deref(),
559            Message::System(m) => Some(&m.content),
560            Message::Developer(m) => Some(&m.content),
561            Message::Tool(m) => match &m.content {
562                ToolContent::Text(text) => Some(text),
563                ToolContent::Parts(parts) => parts.iter().find_map(|part| match part {
564                    InputContent::Text(text) => Some(text.text.as_str()),
565                    _ => None,
566                }),
567            },
568            Message::Reasoning(m) => Some(&m.content),
569            Message::User(m) => match &m.content {
570                UserContent::Text(text) => Some(text),
571                UserContent::Parts(parts) => parts.iter().find_map(|part| match part {
572                    InputContent::Text(text) => Some(text.text.as_str()),
573                    _ => None,
574                }),
575            },
576            Message::Activity(_) => None,
577        }
578    }
579
580    /// The application state, as the JSON document the protocol carries.
581    ///
582    /// This is the authority: snapshots replace it and deltas patch it. A typed
583    /// view is a projection of this — see [`Applier::state_as`].
584    pub fn state(&self) -> &Value {
585        &self.state
586    }
587
588    /// Deserializes the application state into a caller-defined type.
589    ///
590    /// ```
591    /// # #[cfg(feature = "client")]
592    /// # fn main() -> Result<(), ag_ui::client::Error> {
593    /// # use ag_ui::client::apply::Applier;
594    /// # use ag_ui::Event;
595    /// # use serde::{Deserialize, Serialize};
596    /// #[derive(Deserialize)]
597    /// struct Ui {
598    ///     step: u32,
599    /// }
600    ///
601    /// let mut applier = Applier::new();
602    /// applier.apply(&Event::state_snapshot(serde_json::json!({ "step": 2 })))?;
603    /// assert_eq!(applier.state_as::<Ui>()?.step, 2);
604    /// # Ok(())
605    /// # }
606    /// # #[cfg(not(feature = "client"))]
607    /// # fn main() {}
608    /// ```
609    pub fn state_as<T: for<'de> Deserialize<'de>>(&self) -> Result<T> {
610        T::deserialize(&self.state).map_err(Error::State)
611    }
612
613    /// Replaces the application state without going through an event.
614    pub fn set_state(&mut self, state: impl Into<Value>) {
615        self.state = state.into();
616    }
617
618    /// The reasoning messages of the conversation, oldest first.
619    ///
620    /// A view over [`Applier::messages`], not a second list: a reasoning
621    /// message is held there, where it arrived, and is sent back to the agent
622    /// with the rest. This is for a UI that shows reasoning in a pane of its
623    /// own.
624    pub fn reasoning(&self) -> impl Iterator<Item = &ReasoningMessage> {
625        self.messages.iter().filter_map(|message| match message {
626            Message::Reasoning(reasoning) => Some(reasoning),
627            _ => None,
628        })
629    }
630
631    /// The accumulated text of one reasoning message. `None` for an id that
632    /// names no message, or a message of another role.
633    pub fn reasoning_text(&self, id: &MessageId) -> Option<&str> {
634        match self.message(id)? {
635            Message::Reasoning(message) => Some(&message.content),
636            _ => None,
637        }
638    }
639
640    /// The thread of the run last seen on `RUN_STARTED`.
641    pub fn thread_id(&self) -> Option<&ThreadId> {
642        self.thread_id.as_ref()
643    }
644
645    /// The run id last seen on `RUN_STARTED`.
646    pub fn run_id(&self) -> Option<&RunId> {
647        self.run_id.as_ref()
648    }
649
650    /// The interrupts the last `RUN_FINISHED` paused on. Empty unless the run
651    /// is waiting for human input; cleared when the next run starts, and by
652    /// `RUN_ERROR` — a failed run waits for nothing.
653    pub fn interrupts(&self) -> &[Interrupt] {
654        &self.interrupts
655    }
656
657    /// The subagent invocations the run has announced, in announcement order.
658    ///
659    /// Kept across runs on purpose: a subagent suspended in one run is
660    /// announced again by the run that resumes it, and the entry it left is
661    /// what makes that read as a continuation rather than a duplicate.
662    pub fn subagents(&self) -> &[Subagent] {
663        &self.subagents
664    }
665
666    /// One subagent invocation, by id.
667    pub fn subagent(&self, run_id: &SubagentRunId) -> Option<&Subagent> {
668        self.subagent_by_id
669            .get(run_id)
670            .and_then(|index| self.subagents.get(*index))
671    }
672
673    /// Appends a message the client itself produced — typically the user's
674    /// turn, before starting a run.
675    ///
676    /// Returns its index in [`Applier::messages`].
677    pub fn push_message(&mut self, message: Message) -> usize {
678        let index = self.messages.len();
679        self.by_id.insert(message.id().clone(), index);
680        if let Message::Assistant(assistant) = &message {
681            for call in assistant.tool_calls.iter().flatten() {
682                self.tool_calls.insert(call.id.clone(), index);
683            }
684        }
685        self.messages.push(message);
686        index
687    }
688
689    /// Applies one event and reports what it changed.
690    ///
691    /// An event the conversation has no place for changes nothing and is not
692    /// an error: [`Changed::Nothing`] is returned for text, reasoning or
693    /// tool-call arguments whose message or call the conversation does not
694    /// hold, or holds as an activity message, which takes no text. That is
695    /// what follows a `MESSAGES_SNAPSHOT` that removed a message or a call
696    /// the run still had open: the snapshot is the new baseline, and nothing
697    /// is made again from the rest of the item. A
698    /// [`Thread`](crate::client::Thread) reports each such item once per run,
699    /// as a warning.
700    ///
701    /// # Errors
702    ///
703    /// [`Error::Patch`] or [`Error::InvalidPatchDocument`] for a state or
704    /// activity patch that does not apply, [`Error::Protocol`] for a
705    /// `RUN_FINISHED` whose interrupt outcome carries no interrupt, and
706    /// [`Error::Unsupported`] for a
707    /// `*_CHUNK` or a retired `THINKING_*` event, which this applies only in
708    /// their explicit form. Run a raw stream through a
709    /// [`ChunkNormalizer`](crate::client::ChunkNormalizer) first, and read
710    /// one that may carry `THINKING_*` through the compatibility boundary;
711    /// see the [module docs](self).
712    pub fn apply(&mut self, event: &Event) -> Result<Changed> {
713        let changed = self.apply_inner(event)?;
714        // Metadata folds into whatever the event built, once the event has
715        // built it — see `crate::metadata` for which events build anything.
716        if let Some(metadata) = event.metadata() {
717            self.merge_event_metadata(event, &changed, metadata);
718        }
719        Ok(changed)
720    }
721
722    fn apply_inner(&mut self, event: &Event) -> Result<Changed> {
723        match event {
724            Event::TextMessageStart(e) => Ok(self.text_start(
725                e.message_id.clone(),
726                e.role,
727                e.name.clone(),
728                e.subagent_run_id.clone(),
729            )),
730            Event::TextMessageContent(e) => {
731                self.text_content(&e.message_id, &e.delta, &e.subagent_run_id)
732            }
733            Event::TextMessageEnd(e) => Ok(self.text_end(&e.message_id)),
734
735            Event::ToolCallStart(e) => Ok(self.tool_call_start(
736                e.tool_call_id.clone(),
737                e.tool_call_name.clone(),
738                e.parent_message_id.clone(),
739                e.subagent_run_id.clone(),
740            )),
741            Event::ToolCallArgs(e) => self.tool_call_args(&e.tool_call_id, &e.delta),
742            Event::ToolCallEnd(e) => Ok(self.tool_call_end(&e.tool_call_id)),
743            Event::ToolCallResult(e) => Ok(self.tool_call_result(
744                e.message_id.clone(),
745                e.tool_call_id.clone(),
746                e.content.clone(),
747                e.subagent_run_id.clone(),
748            )),
749
750            Event::StateSnapshot(e) => {
751                self.state = e.snapshot.clone();
752                Ok(Changed::State)
753            }
754            Event::StateDelta(e) => {
755                self.state = patched(self.state.clone(), &e.delta, "state")?;
756                Ok(Changed::State)
757            }
758            Event::MessagesSnapshot(e) => {
759                self.merge_snapshot(e.messages.clone());
760                Ok(Changed::MessagesReplaced)
761            }
762
763            Event::ActivitySnapshot(e) => Ok(self.activity_snapshot(e)),
764            Event::ActivityDelta(e) => self.activity_delta(e),
765
766            // A span opens no message, so it leaves nothing to draw: a
767            // reasoning message is in the conversation from its own start to
768            // its own end. A caller that wants the span reads these two
769            // events where it reads the stream.
770            Event::ReasoningStart(_) | Event::ReasoningEnd(_) => Ok(Changed::Nothing),
771            Event::ReasoningMessageStart(e) => {
772                Ok(self.reasoning_start(e.message_id.clone(), e.subagent_run_id.clone()))
773            }
774            Event::ReasoningMessageContent(e) => {
775                self.reasoning_content(&e.message_id, &e.delta, &e.subagent_run_id)
776            }
777            Event::ReasoningMessageEnd(e) => Ok(self.reasoning_end(&e.message_id)),
778            Event::ReasoningEncryptedValue(e) => Ok(self.encrypted_value(e)),
779
780            // The two families that stand for other events. What a chunk
781            // continues, and which reasoning message a THINKING_* event
782            // belongs to, is decided before the applier, in one place each.
783            Event::TextMessageChunk(_)
784            | Event::ToolCallChunk(_)
785            | Event::ReasoningMessageChunk(_) => Err(Error::Unsupported(format!(
786                "{} is applied in its expanded form: run the stream through a \
787                 ChunkNormalizer first",
788                event.event_type()
789            ))),
790            Event::ThinkingStart(_)
791            | Event::ThinkingEnd(_)
792            | Event::ThinkingTextMessageStart(_)
793            | Event::ThinkingTextMessageContent(_)
794            | Event::ThinkingTextMessageEnd(_) => Err(Error::Unsupported(format!(
795                "{} is retired in AG-UI 1.0 and is applied as the REASONING_* event the \
796                 compatibility boundary translates it to",
797                event.event_type()
798            ))),
799
800            Event::RunStarted(e) => {
801                if self.run_id.as_ref() != Some(&e.run_id)
802                    || self.thread_id.as_ref() != Some(&e.thread_id)
803                {
804                    self.synthetic_carriers.clear();
805                }
806                self.thread_id = Some(e.thread_id.clone());
807                self.run_id = Some(e.run_id.clone());
808                self.interrupts.clear();
809                Ok(Changed::RunStarted {
810                    thread_id: e.thread_id.clone(),
811                    run_id: e.run_id.clone(),
812                })
813            }
814            Event::RunFinished(e) => {
815                let outcome = e.outcome.clone().unwrap_or(RunOutcome::Success);
816                outcome.validate()?;
817                self.interrupts = outcome.interrupts().to_vec();
818                Ok(Changed::RunFinished {
819                    outcome,
820                    result: e.result.clone(),
821                })
822            }
823            // Even after RUN_FINISHED: a late failure fails the run that
824            // paused, so what it paused on is no longer asked.
825            Event::RunError(e) => {
826                self.interrupts.clear();
827                Ok(Changed::RunError {
828                    message: e.message.clone(),
829                    code: e.code.clone(),
830                })
831            }
832
833            Event::StepStarted(_) | Event::StepFinished(_) | Event::Raw(_) | Event::Custom(_) => {
834                Ok(Changed::Nothing)
835            }
836
837            Event::SubagentStarted(e) => Ok(self.subagent_started(e)),
838            Event::SubagentFinished(e) => Ok(self.subagent_finished(e)),
839            Event::SubagentError(e) => Ok(self.subagent_error(e)),
840        }
841    }
842
843    /// Restore materialized auxiliary state without reopening streaming parsers.
844    pub(crate) fn restore_auxiliary(
845        &mut self,
846        subagents: Vec<Subagent>,
847        interrupts: Vec<Interrupt>,
848    ) {
849        self.subagent_by_id = subagents
850            .iter()
851            .enumerate()
852            .map(|(i, subagent)| (subagent.run_id.clone(), i))
853            .collect();
854        self.subagents = subagents;
855        self.interrupts = interrupts;
856    }
857
858    pub(crate) fn reset_streams(&mut self) {
859        self.open_text.clear();
860        self.open_reasoning.clear();
861    }
862
863    pub(crate) fn abort_messages(&mut self) -> (Vec<MessageChange>, Vec<ReasoningChange>) {
864        // One a snapshot removed while it was open has no message to report.
865        let messages = self
866            .open_text
867            .in_order()
868            .into_iter()
869            .filter_map(|id| {
870                self.streamable(id).map(|index| MessageChange {
871                    index,
872                    id: id.clone(),
873                    kind: MessageChangeKind::Aborted,
874                })
875            })
876            .collect();
877        let reasoning = self
878            .open_reasoning
879            .in_order()
880            .into_iter()
881            .filter_map(|id| {
882                self.streamable(id).map(|index| ReasoningChange {
883                    index,
884                    id: id.clone(),
885                    kind: ReasoningChangeKind::Aborted,
886                })
887            })
888            .collect();
889        self.reset_streams();
890        (messages, reasoning)
891    }
892
893    pub(crate) fn abort_subagents(&mut self) -> Vec<SubagentChange> {
894        self.reset_streams();
895        self.subagents
896            .iter_mut()
897            .enumerate()
898            .filter_map(|(index, subagent)| {
899                if subagent.status != SubagentStatus::Running {
900                    return None;
901                }
902                subagent.status = SubagentStatus::Aborted;
903                Some(SubagentChange {
904                    index,
905                    run_id: subagent.run_id.clone(),
906                    kind: SubagentChangeKind::Aborted,
907                })
908            })
909            .collect()
910    }
911
912    // ---- messages -------------------------------------------------------
913
914    fn replace_messages(&mut self, messages: Vec<Message>) {
915        self.by_id.clear();
916        self.tool_calls.clear();
917        self.synthetic_carriers.clear();
918        for (index, message) in messages.iter().enumerate() {
919            self.by_id.insert(message.id().clone(), index);
920            if let Message::Assistant(assistant) = message {
921                for call in assistant.tool_calls.iter().flatten() {
922                    self.tool_calls.insert(call.id.clone(), index);
923                    // A join prelude can send a partial carrier as a snapshot
924                    // before reopening its call. The call itself must be on
925                    // that carrier: its message ID alone proves nothing.
926                    let base = format!("{}-message", call.id);
927                    let id = assistant.id.as_str();
928                    let synthetic = id == base
929                        || id
930                            .strip_prefix(&base)
931                            .and_then(|tail| tail.strip_prefix('-'))
932                            .is_some_and(|suffix| {
933                                !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit())
934                            });
935                    if synthetic {
936                        self.synthetic_carriers
937                            .insert(call.id.clone(), assistant.id.clone());
938                    }
939                }
940            } else if let Message::Tool(result) = message {
941                self.synthetic_carriers.remove(&result.tool_call_id);
942            }
943        }
944        self.messages = messages;
945        // What is open stays open. AG-UI 1.0 (`basic/patterns/streaming`):
946        // the standalone events, `MESSAGES_SNAPSHOT` among them, "open and
947        // close no items of their own, and MAY appear anywhere within an
948        // open run". The events that follow for an open item apply to what
949        // the conversation now holds under its id, and to nothing when the
950        // snapshot removed it.
951    }
952
953    /// The index of the message with this id, when it can take streamed
954    /// text: any message but an activity, whose content is an object.
955    fn streamable(&self, id: &MessageId) -> Option<usize> {
956        let index = *self.by_id.get(id)?;
957        (!matches!(self.messages.get(index)?, Message::Activity(_))).then_some(index)
958    }
959
960    /// Folds a `MESSAGES_SNAPSHOT` into the conversation.
961    ///
962    /// A snapshot is an *edit*, not a replacement — upstream
963    /// (`client/src/apply/default.ts`, `case EventType.MESSAGES_SNAPSHOT`)
964    /// rebuilds the list by filtering the local one and appending whatever the
965    /// snapshot adds. Three consequences, all of them load-bearing:
966    ///
967    /// - a message the snapshot carries replaces the local one with the same
968    ///   id, in the place the local one had, so a backend that reorders its
969    ///   own history does not reshuffle the transcript under the user. One
970    ///   the client has not seen is appended, in snapshot order;
971    /// - messages the snapshot leaves out are dropped — that is how a
972    ///   summarizing backend deletes turns;
973    /// - except `activity` and `reasoning`, each of which survives a snapshot
974    ///   that carries none of its role. Activity never travels back to the
975    ///   backend and most backends do not track reasoning, so a backend that
976    ///   does not track a role *cannot* list it. Dropping the local copies
977    ///   would clear a pane of the UI on every snapshot, and take the
978    ///   reasoning out of the next request. A snapshot that does carry a role
979    ///   is declaring the whole set of it, so a message of that role missing
980    ///   from it has been deleted. Without that half a client-side activity
981    ///   would be undeletable, and a backend that restates reasoning under
982    ///   ids of its own would leave every thought in the list twice.
983    ///
984    /// A snapshot is the new baseline for what a run has open, too. It
985    /// closes nothing, and it is not merged with what was there: a message
986    /// being streamed into is replaced by the snapshot's copy or removed,
987    /// and a tool call the snapshot's copy of its message does not list is
988    /// gone. AG-UI 1.0 (`basic/patterns/snapshots`): "A consumer MUST
989    /// replace its copy with the snapshot's content — a snapshot is not a
990    /// merge"; and of what a snapshot leaves out (`events/reasoning`): "The
991    /// consumer's duty is to return what it holds once all events have
992    /// applied, not to resurrect what a snapshot removed."
993    ///
994    /// An id names one message (1.0, `basic`: "it MUST be unique within its
995    /// thread"), so of a snapshot that carries an id more than once the last
996    /// copy is kept, where the first stood.
997    fn merge_snapshot(&mut self, snapshot: Vec<Message>) {
998        let owns_activity = snapshot.iter().any(|m| matches!(m, Message::Activity(_)));
999        let owns_reasoning = snapshot.iter().any(|m| matches!(m, Message::Reasoning(_)));
1000
1001        // `Option` slots so a message can be moved out when it is placed, and
1002        // whatever is left over is exactly what the snapshot added.
1003        let mut incoming: Vec<Option<Message>> = Vec::with_capacity(snapshot.len());
1004        let mut position: HashMap<MessageId, usize> = HashMap::with_capacity(snapshot.len());
1005        for message in snapshot {
1006            match position.get(message.id()) {
1007                Some(first) => incoming[*first] = Some(message),
1008                None => {
1009                    position.insert(message.id().clone(), incoming.len());
1010                    incoming.push(Some(message));
1011                }
1012            }
1013        }
1014
1015        let previous = std::mem::take(&mut self.messages);
1016        let mut merged = Vec::with_capacity(previous.len().max(incoming.len()));
1017        for message in previous {
1018            let restated = position
1019                .get(message.id())
1020                .and_then(|index| incoming[*index].take());
1021            if let Some(replacement) = restated {
1022                // By id alone: the snapshot's copy takes the place, whatever
1023                // role either copy has.
1024                merged.push(replacement);
1025                continue;
1026            }
1027            let survives = match message {
1028                Message::Activity(_) => !owns_activity,
1029                Message::Reasoning(_) => !owns_reasoning,
1030                _ => false,
1031            };
1032            if survives {
1033                merged.push(message);
1034            }
1035        }
1036        merged.extend(incoming.into_iter().flatten());
1037
1038        self.replace_messages(merged);
1039    }
1040
1041    fn text_start(
1042        &mut self,
1043        id: MessageId,
1044        role: TextMessageRole,
1045        name: Option<String>,
1046        owner: Option<SubagentRunId>,
1047    ) -> Changed {
1048        if let Some(held) = self.message(&id) {
1049            if matches!(held, Message::Reasoning(_) | Message::Activity(_)) {
1050                self.claimed.entry(id.clone()).or_insert(owner);
1051            }
1052            // An activity message has no text to append to, so the id opens
1053            // nothing: its content is left as it is, as in the reference
1054            // client.
1055            let Some(index) = self.streamable(&id) else {
1056                return Changed::Nothing;
1057            };
1058            self.open_text.open(id.clone());
1059            // Re-opening a known id keeps the message and appends to it, which
1060            // is what a producer that restarts a stream means — and keeps its
1061            // attribution, which the opener transferred once.
1062            return Changed::Message(MessageChange {
1063                index,
1064                id,
1065                kind: MessageChangeKind::Started,
1066            });
1067        }
1068        self.open_text.open(id.clone());
1069        // Attribution transfers to the message the event creates, so a
1070        // renderer can group a conversation by subagent without replaying
1071        // the stream.
1072        let mut message = empty_message(id.clone(), role, name);
1073        message.set_subagent_run_id(owner);
1074        let index = self.push_message(message);
1075        Changed::Message(MessageChange {
1076            index,
1077            id,
1078            kind: MessageChangeKind::Started,
1079        })
1080    }
1081
1082    fn text_content(
1083        &mut self,
1084        id: &MessageId,
1085        delta: &str,
1086        owner: &Option<SubagentRunId>,
1087    ) -> Result<Changed> {
1088        if !self.by_id.contains_key(id) {
1089            // The message was open and a `MESSAGES_SNAPSHOT` removed it.
1090            // Nothing is made again from the rest of it: the snapshot said
1091            // the conversation does not hold it.
1092            if self.open_text.contains(id) {
1093                return Ok(Changed::Nothing);
1094            }
1095            // Tolerant: an orphan content event opens the message it names.
1096            self.text_start(id.clone(), TextMessageRole::Assistant, None, owner.clone());
1097        }
1098        // An activity message under this id takes no text.
1099        let Some(index) = self.streamable(id) else {
1100            return Ok(Changed::Nothing);
1101        };
1102        append_text(&mut self.messages[index], delta);
1103        Ok(Changed::Message(MessageChange {
1104            index,
1105            id: id.clone(),
1106            kind: MessageChangeKind::Content {
1107                delta: delta.to_owned(),
1108            },
1109        }))
1110    }
1111
1112    fn text_end(&mut self, id: &MessageId) -> Changed {
1113        self.open_text.close(id);
1114        match self.streamable(id) {
1115            Some(index) => Changed::Message(MessageChange {
1116                index,
1117                id: id.clone(),
1118                kind: MessageChangeKind::Ended,
1119            }),
1120            None => Changed::Nothing,
1121        }
1122    }
1123
1124    // ---- tool calls -----------------------------------------------------
1125
1126    fn tool_call_start(
1127        &mut self,
1128        tool_call_id: ToolCallId,
1129        name: String,
1130        parent_message_id: Option<MessageId>,
1131        owner: Option<SubagentRunId>,
1132    ) -> Changed {
1133        // The message the call names carries it, when that is an assistant
1134        // message, or none yet, which the call then opens. A message created
1135        // here takes the call's attribution; one that already exists keeps
1136        // its own.
1137        let named = parent_message_id
1138            .as_ref()
1139            .and_then(|parent| self.by_id.get(parent).copied());
1140        let carries =
1141            |index: usize| matches!(self.messages.get(index), Some(Message::Assistant(_)));
1142        let (carrier, owner) = match (parent_message_id, named) {
1143            (Some(parent), Some(index)) if carries(index) => (parent, owner),
1144            (Some(parent), None) => (parent, owner),
1145            // A call with no parent belongs to a message of its own; the call
1146            // id is the only id available to name it. So does one whose
1147            // parent is not an assistant message and cannot carry a call: a
1148            // reasoning message a reply shares its id with, say. The
1149            // reference client does the same.
1150            //
1151            // Unattributed, such a call is whoever's the ordering rules make
1152            // it: the owner they record for the parent as a text message.
1153            // That is the named message's own, or, for an id the
1154            // conversation holds as reasoning or activity, the owner the
1155            // text start that shared it claimed. None claimed it: the parent
1156            // agent's.
1157            (parent, named) => {
1158                let inherited = || {
1159                    let held = self.messages.get(named?)?;
1160                    match held {
1161                        Message::Reasoning(_) | Message::Activity(_) => {
1162                            self.claimed.get(parent.as_ref()?).cloned().flatten()
1163                        }
1164                        _ => held.subagent_run_id().cloned(),
1165                    }
1166                };
1167                let owner = owner.or_else(inherited);
1168                let resumed = self.synthetic_carriers.get(&tool_call_id).filter(|id| {
1169                    self.tool_call_holder(&tool_call_id) == Some(*id)
1170                        && matches!(self.message(id), Some(Message::Assistant(assistant))
1171                            if (owner.is_none() || owner == assistant.subagent_run_id)
1172                            && assistant.tool_calls.iter().flatten().any(|call| call.id == tool_call_id && call.function.name == name))
1173                });
1174                let id = match resumed {
1175                    Some(id) => id.clone(),
1176                    _ => {
1177                        let base = format!("{tool_call_id}-message");
1178                        let mut id = MessageId::new(&base);
1179                        let mut suffix = 1usize;
1180                        while self.by_id.contains_key(&id) {
1181                            id = MessageId::new(format!("{base}-{suffix}"));
1182                            suffix += 1;
1183                        }
1184                        self.synthetic_carriers
1185                            .insert(tool_call_id.clone(), id.clone());
1186                        id
1187                    }
1188                };
1189                (id, owner)
1190            }
1191        };
1192        let index = match self.by_id.get(&carrier) {
1193            Some(index) => *index,
1194            None => self.push_message(Message::Assistant(AssistantMessage {
1195                id: carrier.clone(),
1196                subagent_run_id: owner,
1197                ..Default::default()
1198            })),
1199        };
1200        let Some(Message::Assistant(assistant)) = self.messages.get_mut(index) else {
1201            return Changed::Nothing;
1202        };
1203        let calls = assistant.tool_calls.get_or_insert_with(Vec::new);
1204        if !calls.iter().any(|call| call.id == tool_call_id) {
1205            calls.push(ToolCall::new(tool_call_id.clone(), name.clone(), ""));
1206        }
1207        self.tool_calls.insert(tool_call_id.clone(), index);
1208        Changed::Message(MessageChange {
1209            index,
1210            id: carrier,
1211            kind: MessageChangeKind::ToolCallStarted { tool_call_id, name },
1212        })
1213    }
1214
1215    fn tool_call_args(&mut self, tool_call_id: &ToolCallId, delta: &str) -> Result<Changed> {
1216        // No message holds the call: it was never started, its start had
1217        // nowhere to put it, or a `MESSAGES_SNAPSHOT` since restated its
1218        // message without it. The fragment is dropped, as in the reference
1219        // client, and a `Thread` says so.
1220        let Some(index) = self.tool_calls.get(tool_call_id).copied() else {
1221            return Ok(Changed::Nothing);
1222        };
1223        let Some(Message::Assistant(assistant)) = self.messages.get_mut(index) else {
1224            return Ok(Changed::Nothing);
1225        };
1226        let Some(call) = assistant
1227            .tool_calls
1228            .as_mut()
1229            .and_then(|calls| calls.iter_mut().find(|call| &call.id == tool_call_id))
1230        else {
1231            return Ok(Changed::Nothing);
1232        };
1233        call.function.arguments.push_str(delta);
1234        Ok(Changed::Message(MessageChange {
1235            index,
1236            id: assistant.id.clone(),
1237            kind: MessageChangeKind::ToolCallArgs {
1238                tool_call_id: tool_call_id.clone(),
1239                delta: delta.to_owned(),
1240            },
1241        }))
1242    }
1243
1244    fn tool_call_end(&mut self, tool_call_id: &ToolCallId) -> Changed {
1245        match self.tool_calls.get(tool_call_id).copied() {
1246            Some(index) => match self.messages.get(index) {
1247                Some(message) => Changed::Message(MessageChange {
1248                    index,
1249                    id: message.id().clone(),
1250                    kind: MessageChangeKind::ToolCallEnded {
1251                        tool_call_id: tool_call_id.clone(),
1252                    },
1253                }),
1254                None => Changed::Nothing,
1255            },
1256            None => Changed::Nothing,
1257        }
1258    }
1259
1260    fn tool_call_result(
1261        &mut self,
1262        message_id: MessageId,
1263        tool_call_id: ToolCallId,
1264        content: ToolContent,
1265        owner: Option<SubagentRunId>,
1266    ) -> Changed {
1267        self.synthetic_carriers.remove(&tool_call_id);
1268        let index = match self.by_id.get(&message_id).copied() {
1269            Some(index) => {
1270                if let Some(Message::Tool(tool)) = self.messages.get_mut(index) {
1271                    tool.content = content;
1272                    // The newest mint wins, as both verifiers record it.
1273                    tool.subagent_run_id = owner;
1274                }
1275                index
1276            }
1277            // The result's own attribution, not the call's: whoever executed
1278            // the tool owns the message that reports it.
1279            None => self.push_message(Message::Tool(ToolMessage {
1280                id: message_id.clone(),
1281                content,
1282                tool_call_id: tool_call_id.clone(),
1283                subagent_run_id: owner,
1284                ..Default::default()
1285            })),
1286        };
1287        Changed::Message(MessageChange {
1288            index,
1289            id: message_id,
1290            kind: MessageChangeKind::ToolResult { tool_call_id },
1291        })
1292    }
1293
1294    // ---- activities -----------------------------------------------------
1295
1296    fn activity_snapshot(&mut self, event: &ActivitySnapshotEvent) -> Changed {
1297        let index = match self.by_id.get(&event.message_id).copied() {
1298            Some(index) => index,
1299            // A snapshot for an id not seen yet creates the activity, in
1300            // sequence position, whatever `replace` says.
1301            None => {
1302                let index = self.push_message(Message::Activity(ActivityMessage {
1303                    id: event.message_id.clone(),
1304                    activity_type: event.activity_type.clone(),
1305                    content: event.content.clone(),
1306                    subagent_run_id: event.subagent_run_id.clone(),
1307                    ..Default::default()
1308                }));
1309                return Changed::Message(MessageChange {
1310                    index,
1311                    id: event.message_id.clone(),
1312                    kind: MessageChangeKind::Activity,
1313                });
1314            }
1315        };
1316        // `replace: false` leaves an existing activity as it stands: content,
1317        // `activityType` and owner. It is not a merge.
1318        if !event.replace {
1319            return Changed::Nothing;
1320        }
1321        // A replacing snapshot re-mints the activity, attribution included:
1322        // one that carries none takes the activity back for the parent.
1323        // Metadata is not content, and keeps merging.
1324        if let Some(Message::Activity(activity)) = self.messages.get_mut(index) {
1325            activity.activity_type = event.activity_type.clone();
1326            activity.subagent_run_id = event.subagent_run_id.clone();
1327            activity.content = event.content.clone();
1328        }
1329        Changed::Message(MessageChange {
1330            index,
1331            id: event.message_id.clone(),
1332            kind: MessageChangeKind::Activity,
1333        })
1334    }
1335
1336    /// Patches an activity's content and gives it the delta's `activityType`.
1337    /// A delta whose target does not exist, or is not an activity, is
1338    /// skipped: the error says so, nothing is created, and a `Thread` reports
1339    /// it without failing the run. A patch that does not apply changes nothing.
1340    fn activity_delta(&mut self, event: &ActivityDeltaEvent) -> Result<Changed> {
1341        let what = format!("activity {}", event.message_id);
1342        let index = self.by_id.get(&event.message_id).copied();
1343        let Some((index, Message::Activity(activity))) =
1344            index.and_then(|index| Some((index, self.messages.get_mut(index)?)))
1345        else {
1346            return Err(Error::Patch {
1347                target: what,
1348                message: "no activity message has this id, so the delta was skipped; an \
1349                          ACTIVITY_SNAPSHOT has to create it first"
1350                    .to_owned(),
1351            });
1352        };
1353        // Patched on a copy, and committed only once the result is still an
1354        // object. An activity's content is an object by definition, so a
1355        // whole-document operation — `{"op":"replace","path":"","value":7}`
1356        // — has nowhere to land; taking the content out first would leave
1357        // the activity holding nothing at all.
1358        let content = patched(Value::Object(activity.content.clone()), &event.patch, &what)?;
1359        let Value::Object(object) = content else {
1360            return Err(Error::Patch {
1361                target: what,
1362                message: format!(
1363                    "patch replaced the whole activity with {}, which is not an object",
1364                    kind_of(&content)
1365                ),
1366            });
1367        };
1368        activity.content = object;
1369        // The delta's type replaces the message's: a delta may retype the
1370        // activity it amends.
1371        activity.activity_type = event.activity_type.clone();
1372        Ok(Changed::Message(MessageChange {
1373            index,
1374            id: event.message_id.clone(),
1375            kind: MessageChangeKind::Activity,
1376        }))
1377    }
1378
1379    // ---- reasoning ------------------------------------------------------
1380
1381    /// Opens the reasoning message a `REASONING_MESSAGE_START` names: a
1382    /// message of the conversation, appended where it arrives.
1383    ///
1384    /// A message id is unique within its thread. So an id the conversation
1385    /// already holds continues that message, whatever its role, as a
1386    /// `TEXT_MESSAGE_START` for a known id does and as the reference client
1387    /// does. Nothing is created beside it.
1388    fn reasoning_start(&mut self, id: MessageId, owner: Option<SubagentRunId>) -> Changed {
1389        let index = if self.by_id.contains_key(&id) {
1390            // An activity message has no text, so the id opens nothing.
1391            let Some(index) = self.streamable(&id) else {
1392                return Changed::Nothing;
1393            };
1394            index
1395        } else {
1396            // Attribution transfers to the message the event creates, as it
1397            // does for text.
1398            self.push_message(Message::Reasoning(ReasoningMessage {
1399                id: id.clone(),
1400                subagent_run_id: owner,
1401                ..Default::default()
1402            }))
1403        };
1404        self.open_reasoning.open(id.clone());
1405        Changed::Reasoning(ReasoningChange {
1406            index,
1407            id,
1408            kind: ReasoningChangeKind::Started,
1409        })
1410    }
1411
1412    fn reasoning_content(
1413        &mut self,
1414        id: &MessageId,
1415        delta: &str,
1416        owner: &Option<SubagentRunId>,
1417    ) -> Result<Changed> {
1418        if !self.by_id.contains_key(id) {
1419            // Open, and removed by a `MESSAGES_SNAPSHOT`: as for text,
1420            // nothing is made again from the rest of it.
1421            if self.open_reasoning.contains(id) {
1422                return Ok(Changed::Nothing);
1423            }
1424            // Tolerant: an orphan content event opens the message it names.
1425            self.reasoning_start(id.clone(), owner.clone());
1426        }
1427        // An activity message under this id takes no text.
1428        let Some(index) = self.streamable(id) else {
1429            return Ok(Changed::Nothing);
1430        };
1431        append_text(&mut self.messages[index], delta);
1432        Ok(Changed::Reasoning(ReasoningChange {
1433            index,
1434            id: id.clone(),
1435            kind: ReasoningChangeKind::Content {
1436                delta: delta.to_owned(),
1437            },
1438        }))
1439    }
1440
1441    fn reasoning_end(&mut self, id: &MessageId) -> Changed {
1442        self.open_reasoning.close(id);
1443        match self.streamable(id) {
1444            Some(index) => Changed::Reasoning(ReasoningChange {
1445                index,
1446                id: id.clone(),
1447                kind: ReasoningChangeKind::Ended,
1448            }),
1449            None => Changed::Nothing,
1450        }
1451    }
1452
1453    fn encrypted_value(&mut self, event: &ReasoningEncryptedValueEvent) -> Changed {
1454        let blob = event.encrypted_value.clone();
1455        match event.subtype {
1456            ReasoningEncryptedValueSubtype::ToolCall => {
1457                let tool_call_id = ToolCallId::new(event.entity_id.clone());
1458                let Some(index) = self.tool_calls.get(&tool_call_id).copied() else {
1459                    return Changed::Nothing;
1460                };
1461                let Some(Message::Assistant(assistant)) = self.messages.get_mut(index) else {
1462                    return Changed::Nothing;
1463                };
1464                if let Some(call) = assistant
1465                    .tool_calls
1466                    .as_mut()
1467                    .and_then(|calls| calls.iter_mut().find(|call| call.id == tool_call_id))
1468                {
1469                    call.encrypted_value = Some(blob);
1470                }
1471                Changed::Message(MessageChange {
1472                    index,
1473                    id: assistant.id.clone(),
1474                    kind: MessageChangeKind::EncryptedValue,
1475                })
1476            }
1477            // Stored with the message it names, which is what carries it
1478            // back: the next request sends that message as it stands.
1479            ReasoningEncryptedValueSubtype::Message => {
1480                let id = MessageId::new(event.entity_id.clone());
1481                let Some(index) = self.by_id.get(&id).copied() else {
1482                    return Changed::Nothing;
1483                };
1484                let Some(message) = self.messages.get_mut(index) else {
1485                    return Changed::Nothing;
1486                };
1487                // An activity has no field for the value, so the event names
1488                // nothing that can hold it.
1489                if !set_encrypted_value(message, blob) {
1490                    return Changed::Nothing;
1491                }
1492                if matches!(message, Message::Reasoning(_)) {
1493                    Changed::Reasoning(ReasoningChange {
1494                        index,
1495                        id,
1496                        kind: ReasoningChangeKind::EncryptedValue,
1497                    })
1498                } else {
1499                    Changed::Message(MessageChange {
1500                        index,
1501                        id,
1502                        kind: MessageChangeKind::EncryptedValue,
1503                    })
1504                }
1505            }
1506        }
1507    }
1508
1509    // ---- subagents ------------------------------------------------------
1510
1511    fn subagent_started(&mut self, event: &SubagentStartedEvent) -> Changed {
1512        let run_id = event.subagent_run_id.clone();
1513        if let Some(index) = self.subagent_by_id.get(&run_id).copied() {
1514            // The one legal re-announcement: a suspended invocation continuing
1515            // on the resuming run. Anything else is a producer bug the
1516            // verifier already reported, and the entry is reset rather than
1517            // duplicated so a view keeps one row per id.
1518            let subagent = &mut self.subagents[index];
1519            let kind = if matches!(subagent.status, SubagentStatus::Suspended { .. }) {
1520                SubagentChangeKind::Resumed
1521            } else {
1522                SubagentChangeKind::Started
1523            };
1524            subagent.name.clone_from(&event.name);
1525            if event.description.is_some() {
1526                subagent.description.clone_from(&event.description);
1527            }
1528            if let Some(parent) = &event.parent_subagent_run_id {
1529                self.adopt(index, parent);
1530            }
1531            let subagent = &mut self.subagents[index];
1532            if event.parent_tool_call_id.is_some() {
1533                subagent
1534                    .parent_tool_call_id
1535                    .clone_from(&event.parent_tool_call_id);
1536                subagent
1537                    .parent_message_id
1538                    .clone_from(&event.parent_message_id);
1539            }
1540            subagent.status = SubagentStatus::Running;
1541            return Changed::Subagent(SubagentChange {
1542                index,
1543                run_id,
1544                kind,
1545            });
1546        }
1547        let index = self.push_subagent(Subagent {
1548            run_id: run_id.clone(),
1549            name: event.name.clone(),
1550            description: event.description.clone(),
1551            // No invocation spawned itself.
1552            parent_subagent_run_id: event
1553                .parent_subagent_run_id
1554                .clone()
1555                .filter(|parent| parent != &run_id),
1556            parent_tool_call_id: event.parent_tool_call_id.clone(),
1557            parent_message_id: event.parent_message_id.clone(),
1558            status: SubagentStatus::Running,
1559        });
1560        Changed::Subagent(SubagentChange {
1561            index,
1562            run_id,
1563            kind: SubagentChangeKind::Started,
1564        })
1565    }
1566
1567    /// Gives the subagent at `index`, which is announced again, the parent
1568    /// its new announcement names.
1569    ///
1570    /// The newest announcement stands. What the table holds may say the
1571    /// opposite: a run that announces two invocations the other way round
1572    /// than the run before it finds the named parent recorded *under* this
1573    /// subagent, and keeping both links would make each the other's
1574    /// ancestor, which no tree has and no snapshot restores. So the older
1575    /// link, the one on the way up from the parent that ends at this
1576    /// subagent, is dropped, and its holder stands directly under the
1577    /// parent agent, where an announcement that names no parent puts it.
1578    ///
1579    /// Only an announcement that changes the parent of a known invocation
1580    /// walks the ancestors, so a first announcement costs the same at any
1581    /// depth.
1582    fn adopt(&mut self, index: usize, parent: &SubagentRunId) {
1583        let id = self.subagents[index].run_id.clone();
1584        let unchanged = self.subagents[index].parent_subagent_run_id.as_ref() == Some(parent);
1585        // No invocation spawned itself.
1586        if unchanged || *parent == id {
1587            return;
1588        }
1589        let mut at = self.subagent_by_id.get(parent).copied();
1590        // A walk longer than the table has met a cycle that was there
1591        // already, which only a stream nothing verified leaves.
1592        for _ in 0..self.subagents.len() {
1593            let Some(ancestor) = at else { break };
1594            let above = self.subagents[ancestor].parent_subagent_run_id.clone();
1595            match above {
1596                Some(above) if above == id => {
1597                    self.subagents[ancestor].parent_subagent_run_id = None;
1598                    break;
1599                }
1600                Some(above) => at = self.subagent_by_id.get(&above).copied(),
1601                None => break,
1602            }
1603        }
1604        self.subagents[index].parent_subagent_run_id = Some(parent.clone());
1605    }
1606
1607    fn subagent_finished(&mut self, event: &SubagentFinishedEvent) -> Changed {
1608        let run_id = event.subagent_run_id.clone();
1609        let index = self.subagent_index(&run_id);
1610        let (status, kind) = match &event.outcome {
1611            Some(SubagentOutcome::Suspended { interrupt_ids }) => (
1612                SubagentStatus::Suspended {
1613                    result: event.result.clone(),
1614                    interrupt_ids: interrupt_ids.clone().unwrap_or_default(),
1615                },
1616                SubagentChangeKind::Suspended,
1617            ),
1618            // Absent means success: the legacy reading.
1619            Some(SubagentOutcome::Success) | None => (
1620                SubagentStatus::Finished {
1621                    result: event.result.clone(),
1622                },
1623                SubagentChangeKind::Finished,
1624            ),
1625        };
1626        self.subagents[index].status = status;
1627        Changed::Subagent(SubagentChange {
1628            index,
1629            run_id,
1630            kind,
1631        })
1632    }
1633
1634    fn subagent_error(&mut self, event: &SubagentErrorEvent) -> Changed {
1635        let run_id = event.subagent_run_id.clone();
1636        let index = self.subagent_index(&run_id);
1637        self.subagents[index].status = SubagentStatus::Failed {
1638            message: event.message.clone(),
1639            code: event.code.clone(),
1640        };
1641        Changed::Subagent(SubagentChange {
1642            index,
1643            run_id,
1644            kind: SubagentChangeKind::Failed,
1645        })
1646    }
1647
1648    /// The index of the subagent with this id, creating a bare entry when a
1649    /// producer closed one it never announced. Tolerant, like the rest of the
1650    /// applier: the verifier is where that is a complaint, and a view still
1651    /// wants a row to hang the outcome on.
1652    fn subagent_index(&mut self, run_id: &SubagentRunId) -> usize {
1653        match self.subagent_by_id.get(run_id).copied() {
1654            Some(index) => index,
1655            None => self.push_subagent(Subagent {
1656                run_id: run_id.clone(),
1657                name: run_id.to_string(),
1658                description: None,
1659                parent_subagent_run_id: None,
1660                parent_tool_call_id: None,
1661                parent_message_id: None,
1662                status: SubagentStatus::Running,
1663            }),
1664        }
1665    }
1666
1667    fn push_subagent(&mut self, subagent: Subagent) -> usize {
1668        let index = self.subagents.len();
1669        self.subagent_by_id.insert(subagent.run_id.clone(), index);
1670        self.subagents.push(subagent);
1671        index
1672    }
1673
1674    // ---- metadata -------------------------------------------------------
1675
1676    /// Folds an event's metadata into what the event built: the message for
1677    /// the text, result and activity families, the tool call for `TOOL_CALL_*`,
1678    /// the reasoning message for `REASONING_MESSAGE_*`. Everything else keeps
1679    /// its metadata to itself — see [`crate::metadata`].
1680    fn merge_event_metadata(&mut self, event: &Event, changed: &Changed, metadata: &JsonObject) {
1681        match event {
1682            Event::TextMessageStart(_)
1683            | Event::TextMessageContent(_)
1684            | Event::TextMessageEnd(_)
1685            | Event::ToolCallResult(_)
1686            | Event::ActivitySnapshot(_)
1687            | Event::ActivityDelta(_) => {
1688                let Changed::Message(change) = changed else {
1689                    return;
1690                };
1691                if let Some(message) = self.messages.get_mut(change.index) {
1692                    merge_metadata_into(message.metadata_mut(), Some(metadata));
1693                }
1694            }
1695            Event::ToolCallStart(_) | Event::ToolCallArgs(_) | Event::ToolCallEnd(_) => {
1696                let Changed::Message(change) = changed else {
1697                    return;
1698                };
1699                let tool_call_id = match &change.kind {
1700                    MessageChangeKind::ToolCallStarted { tool_call_id, .. }
1701                    | MessageChangeKind::ToolCallArgs { tool_call_id, .. }
1702                    | MessageChangeKind::ToolCallEnded { tool_call_id } => tool_call_id.clone(),
1703                    _ => return,
1704                };
1705                let Some(Message::Assistant(assistant)) = self.messages.get_mut(change.index)
1706                else {
1707                    return;
1708                };
1709                if let Some(call) = assistant
1710                    .tool_calls
1711                    .as_mut()
1712                    .and_then(|calls| calls.iter_mut().find(|call| call.id == tool_call_id))
1713                {
1714                    merge_metadata_into(&mut call.metadata, Some(metadata));
1715                }
1716            }
1717            Event::ReasoningMessageStart(_)
1718            | Event::ReasoningMessageContent(_)
1719            | Event::ReasoningMessageEnd(_) => {
1720                let Changed::Reasoning(change) = changed else {
1721                    return;
1722                };
1723                if let Some(message) = self.messages.get_mut(change.index) {
1724                    merge_metadata_into(message.metadata_mut(), Some(metadata));
1725                }
1726            }
1727            _ => {}
1728        }
1729    }
1730}
1731
1732/// Applies a patch to an owned copy. A failed move may already have removed
1733/// its source; the caller only receives a document after every operation succeeds.
1734fn patched(mut candidate: Value, operations: &[PatchOperation], what: &str) -> Result<Value> {
1735    // The protocol's operation type and the patch engine's are both the RFC
1736    // wire format, so JSON is the conversion. Deserializing is also where a
1737    // malformed JSON Pointer is caught, before anything is mutated.
1738    let document = serde_json::to_value(operations)?;
1739    let patch: json_patch::Patch =
1740        serde_json::from_value(document).map_err(|error| Error::InvalidPatchDocument {
1741            target: what.to_owned(),
1742            message: error.to_string(),
1743        })?;
1744    json_patch::patch_unsafe(&mut candidate, &patch).map_err(|error| Error::Patch {
1745        target: what.to_owned(),
1746        message: error.to_string(),
1747    })?;
1748    Ok(candidate)
1749}
1750
1751/// Names a JSON value's type, for an error message.
1752fn kind_of(value: &Value) -> &'static str {
1753    match value {
1754        Value::Null => "null",
1755        Value::Bool(_) => "a boolean",
1756        Value::Number(_) => "a number",
1757        Value::String(_) => "a string",
1758        Value::Array(_) => "an array",
1759        Value::Object(_) => "an object",
1760    }
1761}
1762
1763/// Builds the empty message a `TEXT_MESSAGE_START` opens.
1764fn empty_message(id: MessageId, role: TextMessageRole, name: Option<String>) -> Message {
1765    match role {
1766        TextMessageRole::Assistant => Message::Assistant(AssistantMessage {
1767            id,
1768            content: Some(String::new()),
1769            name,
1770            ..Default::default()
1771        }),
1772        TextMessageRole::User => Message::User(UserMessage {
1773            id,
1774            content: UserContent::Text(String::new()),
1775            name,
1776            ..Default::default()
1777        }),
1778        TextMessageRole::System => Message::System(SystemMessage {
1779            id,
1780            content: String::new(),
1781            name,
1782            ..Default::default()
1783        }),
1784        TextMessageRole::Developer => Message::Developer(DeveloperMessage {
1785            id,
1786            content: String::new(),
1787            name,
1788            ..Default::default()
1789        }),
1790    }
1791}
1792
1793/// Appends streamed text to whichever field of the message carries it. An
1794/// activity message has none, and is not handed here.
1795fn append_text(message: &mut Message, delta: &str) {
1796    match message {
1797        Message::Assistant(m) => m.content.get_or_insert_with(String::new).push_str(delta),
1798        Message::System(m) => m.content.push_str(delta),
1799        Message::Developer(m) => m.content.push_str(delta),
1800        Message::Reasoning(m) => m.content.push_str(delta),
1801        Message::Tool(m) => match &mut m.content {
1802            ToolContent::Text(text) => text.push_str(delta),
1803            ToolContent::Parts(parts) => match parts.last_mut() {
1804                Some(InputContent::Text(text)) => text.text.push_str(delta),
1805                _ => parts.push(InputContent::text(delta)),
1806            },
1807        },
1808        Message::User(m) => match &mut m.content {
1809            UserContent::Text(text) => text.push_str(delta),
1810            UserContent::Parts(parts) => match parts.last_mut() {
1811                Some(InputContent::Text(text)) => text.text.push_str(delta),
1812                _ => parts.push(InputContent::Text(TextInputContent {
1813                    text: delta.to_owned(),
1814                    ..Default::default()
1815                })),
1816            },
1817        },
1818        Message::Activity(_) => {}
1819    }
1820}
1821
1822/// Attaches a provider's opaque reasoning blob to a message, and says whether
1823/// the message could take it.
1824fn set_encrypted_value(message: &mut Message, blob: String) -> bool {
1825    let slot = match message {
1826        Message::Assistant(m) => &mut m.encrypted_value,
1827        Message::System(m) => &mut m.encrypted_value,
1828        Message::Developer(m) => &mut m.encrypted_value,
1829        Message::User(m) => &mut m.encrypted_value,
1830        Message::Tool(m) => &mut m.encrypted_value,
1831        Message::Reasoning(m) => &mut m.encrypted_value,
1832        // An activity has no field for it.
1833        Message::Activity(_) => return false,
1834    };
1835    *slot = Some(blob);
1836    true
1837}