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