Skip to main content

ag_ui/client/thread/
run.rs

1//! One request of a conversation: the stream that answers it, the runs that
2//! stream carries, and what it yields.
3
4use std::collections::{HashMap, HashSet, VecDeque};
5use std::pin::Pin;
6use std::sync::{
7    Arc,
8    atomic::{AtomicBool, Ordering},
9};
10use std::task::{Context as TaskContext, Poll};
11
12use crate::client::{
13    apply::{
14        Changed, MessageChangeKind, ReasoningChange, ReasoningChangeKind, Subagent,
15        SubagentChangeKind,
16    },
17    chunks::ChunkNormalizer,
18    enforce::{Checked, CheckedStream, REMEMBERED},
19    error::{Error, Result},
20    transport::Transport,
21    verify::{Verifier, nested_run_started},
22};
23use crate::protocol::excerpt;
24use crate::{
25    Event, Interrupt, Message, MessageId, ReasoningEncryptedValueEvent,
26    ReasoningEncryptedValueSubtype, ResumeEntry, RunAgentInput, RunId, RunOutcome, SubagentRunId,
27    ToolCallId,
28};
29use futures_core::Stream;
30use futures_util::{StreamExt, task::AtomicWaker};
31use serde::{Deserialize, Serialize, de::DeserializeOwned};
32use serde_json::Value;
33
34use super::pending::{ResumeSubmission, SubmissionStatus, unread_expiries, validate_responses};
35use super::{StateViewError, Thread};
36
37/// Something a view should react to.
38///
39/// One [`Update`] is one redraw. `S` is the caller's state type; it is
40/// [`serde_json::Value`] unless a [`Thread`] is asked for something better.
41#[derive(Debug)]
42#[non_exhaustive]
43pub enum Update<S = Value> {
44    /// A message was created, appended to, or completed.
45    Message(MessageUpdate),
46    /// `MESSAGES_SNAPSHOT` replaced the conversation. Messages may have
47    /// disappeared, so redraw all of it.
48    Messages(Vec<Message>),
49    /// The application state changed, and here it is in the caller's type.
50    ///
51    /// Carries no association with whatever was open when it arrived — a tool
52    /// call, a message — because the wire carries none either. Where it lands
53    /// in the stream is the only nesting there is; see the [module
54    /// docs](super).
55    State(S),
56    /// A reasoning message was created, appended to, or completed. It is in
57    /// [`Thread::messages`] like any other message, and is announced here and
58    /// not as an [`Update::Message`], so a view can draw reasoning apart
59    /// from the reply, or leave it out.
60    ///
61    /// The span around reasoning messages, `REASONING_START` to
62    /// `REASONING_END`, opens no message and yields no update. An application
63    /// that needs to know one is open reads those two events in
64    /// [`Thread::on_event`].
65    Reasoning(ReasoningUpdate),
66    /// A subagent was announced, resumed, finished, suspended or failed.
67    ///
68    /// The lifecycle only: what a subagent *says* arrives as ordinary
69    /// [`Update::Message`]s and [`Update::Reasoning`]s whose messages carry
70    /// its `subagent_run_id`, so a view groups by that and uses this for the
71    /// group's header and status. See [`Thread::subagents`].
72    Subagent(SubagentUpdate),
73    /// The run paused and needs a human. Answer it with
74    /// [`Thread::resume`] — one update per pending interrupt.
75    ///
76    /// Only for interrupts that became pending on the thread: those of the
77    /// requested run, or of a run after it, which replace the requested
78    /// run's. A replayed run's are history, and are in its [`RunSummary`]
79    /// only. [`Thread::interrupts`] holds what is pending once the stream
80    /// has ended.
81    Interrupt(Interrupt),
82    /// Something went wrong: a malformed stream, a patch that would not apply,
83    /// a transport failure, a `RUN_ERROR`.
84    ///
85    /// Not necessarily fatal — a run survives a patch it could not apply, and
86    /// a stream goes on after a `RUN_ERROR`, which fails one run and may be
87    /// followed by the next. When it ends the stream, the matching
88    /// [`Update::Done`] follows.
89    Error(Error),
90    /// Not an error: the stream was accepted, with a correction or an omission
91    /// the application may want to log. An unrecognised field, enum member or
92    /// event was dropped, a retired `THINKING_*` event was translated, a
93    /// deprecated `null` was read as omitted, or the producer declared a newer
94    /// protocol version. The run is unaffected. So is it in two more cases: a
95    /// run after the requested one finished, and the pending interrupts were
96    /// not replaced because a resume submission is still unconfirmed; or a
97    /// `REASONING_ENCRYPTED_VALUE` was dropped because the thread holds no
98    /// message or tool call by its `entityId` that can store it.
99    ///
100    /// Each text is delivered once per run and repeats at most 64 characters
101    /// of input, with control characters escaped. [`RunReport::diagnostics`]
102    /// keeps it with kind `warning`.
103    Warning(String),
104    /// One run on the stream ended, and how.
105    ///
106    /// A stream carries the run the request asked for, and AG-UI 1.0 lets
107    /// runs the producer replays precede it. Each run gets one of these, the
108    /// only run of a stream included, once nothing can change how it ended:
109    /// at its `RUN_ERROR`, or for a run that reported `RUN_FINISHED` at
110    /// whatever follows it — the next `RUN_STARTED`, a late `RUN_ERROR`, the
111    /// end of the stream. A `RUN_ERROR` that opens the stream is reported at
112    /// whatever follows it as well, because that decides whether it was the
113    /// requested run; its [`Update::Error`] comes when it arrives.
114    /// [`Update::Done`] follows the last one.
115    RunEnded(RunSummary),
116    /// The stream ended, and how the request went: the [`RunEnd`] of the
117    /// requested run — of the last run on the stream, should the producer
118    /// have gone on after it — or how reading stopped before any such run
119    /// ended. Always the last update, on every path out: the agent
120    /// finishing, the agent failing, and the transport dying mid-sentence.
121    ///
122    /// It arrives when the stream ends, not at a terminal event: another run
123    /// may follow `RUN_FINISHED` or `RUN_ERROR`.
124    Done(RunEnd),
125}
126
127/// A message that changed, and the message as it now stands.
128#[derive(Clone, Debug, PartialEq)]
129#[non_exhaustive]
130pub struct MessageUpdate {
131    /// Index into [`Thread::messages`].
132    pub index: usize,
133    /// The message's id.
134    pub id: MessageId,
135    /// What this event did to it — the text delta, the tool call, the close.
136    pub change: MessageChangeKind,
137    /// The whole message, assembled so far.
138    pub message: Message,
139}
140
141/// Reasoning that changed, and the reasoning as it now stands.
142#[derive(Clone, Debug, PartialEq)]
143#[non_exhaustive]
144pub struct ReasoningUpdate {
145    /// Index into [`Thread::messages`], where the reasoning message is.
146    pub index: usize,
147    /// The reasoning message's id.
148    pub id: MessageId,
149    /// What this event did to it.
150    pub change: ReasoningChangeKind,
151    /// The accumulated reasoning text.
152    pub text: String,
153}
154
155/// A subagent that changed, and the subagent as it now stands.
156#[derive(Clone, Debug, PartialEq)]
157#[non_exhaustive]
158pub struct SubagentUpdate {
159    /// Index into [`Thread::subagents`].
160    pub index: usize,
161    /// The invocation's id — what the messages it produced carry.
162    pub run_id: crate::SubagentRunId,
163    /// What this event did to it.
164    pub change: SubagentChangeKind,
165    /// The whole entry, status included.
166    pub subagent: Subagent,
167}
168
169/// How the remote run ended, or how local consumption stopped.
170#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
171pub enum RunEnd {
172    /// The server confirmed successful completion. Local diagnostics remain separate.
173    Success {
174        /// Optional server result.
175        result: Option<Value>,
176    },
177    /// The server completed, with frontend tool calls awaiting answers.
178    SuccessWithPendingToolCalls {
179        /// Optional server result.
180        result: Option<Value>,
181        /// Calls to answer in the next request, in call order.
182        pending_tool_call_ids: Vec<ToolCallId>,
183    },
184    /// The server paused for input.
185    Interrupted {
186        /// Current pending questions.
187        interrupts: Vec<Interrupt>,
188    },
189    /// The server or transport failed, or its terminal event was invalid.
190    Failed {
191        /// Human-readable cause.
192        message: String,
193        /// Optional server error code.
194        code: Option<String>,
195    },
196    /// The server confirmed that it stopped the run before completion.
197    Cancelled,
198    /// Local consumption stopped. This does not confirm cancellation on the server.
199    Aborted,
200}
201
202/// One run a stream carried, and how it ended.
203///
204/// The runs of a stream fall in three places. Those before the requested run
205/// are *replayed*: history the producer restates. They are read into the
206/// conversation and reported here, and change nothing the thread owes. The
207/// *requested* run answers the request: it alone confirms a resume
208/// submission. A run *after* it is one AG-UI 1.0 does not provide for — the
209/// requested run is the last of its exchange — but a producer that keeps the
210/// stream open sends one, and the agent then stands where that run left it.
211/// So what the thread owes next, its pending interrupts and the tool calls a
212/// success outcome names, is what the last run from the requested one on
213/// reported.
214#[derive(Clone, Debug, PartialEq)]
215#[non_exhaustive]
216pub struct RunSummary {
217    /// The id its `RUN_STARTED` carried. `None` for a failure that opened
218    /// the stream: a `RUN_ERROR` with no run before it.
219    pub run_id: Option<RunId>,
220    /// How it ended, or how reading it stopped.
221    pub end: RunEnd,
222    /// Whether this is the run the request asked for: the one whose
223    /// `RUN_STARTED` carried the request's run id, or a failure that opened
224    /// the stream and that no run followed, which is that run failing before
225    /// it began. At most one run of a stream is the requested one: a failure
226    /// that opened the stream and that a run followed is history, like a
227    /// replayed run.
228    pub requested: bool,
229}
230
231/// One retained diagnostic, independent of the terminal outcome.
232#[derive(Clone, Debug, PartialEq, Eq)]
233#[non_exhaustive]
234pub struct RunDiagnostic {
235    /// A stable broad category: `warning` for an [`Update::Warning`], and for
236    /// an [`Update::Error`] one of these, by the [`Error`] it carries.
237    ///
238    /// | Kind | The error |
239    /// | --- | --- |
240    /// | `state` | [`Error::State`]: the state does not fit the caller's type |
241    /// | `protocol` | [`Error::Protocol`], [`Error::InvalidPatchDocument`]: the stream broke a rule |
242    /// | `patch` | [`Error::Patch`]: a patch did not apply, and the run went on |
243    /// | `decode` | [`Error::Json`], [`Error::Decode`]: a frame or its payload could not be read |
244    /// | `run` | [`Error::Run`]: the agent reported `RUN_ERROR` |
245    /// | `unsupported` | [`Error::Unsupported`] |
246    /// | `transport` | any other error: the connection, the HTTP response |
247    pub kind: &'static str,
248    /// Human-readable cause.
249    pub message: String,
250}
251
252/// Results from the whole stream, including updates consumed before `collect_report`.
253#[derive(Clone, Debug, PartialEq)]
254#[non_exhaustive]
255pub struct RunReport {
256    /// How the request went: what [`Update::Done`] carried.
257    pub end: RunEnd,
258    /// Every run the stream carried, in order. One entry for a stream that
259    /// carried the requested run alone; none when reading stopped before any
260    /// run began.
261    pub runs: Vec<RunSummary>,
262    /// Messages whose IDs were absent when this request was prepared,
263    /// reasoning messages among them, whichever run on the stream produced
264    /// them.
265    pub new_messages: Vec<Message>,
266    /// Retained diagnostics, in observation order.
267    pub diagnostics: Vec<RunDiagnostic>,
268    /// Diagnostics beyond the configured retention limit.
269    pub diagnostics_omitted: usize,
270}
271
272impl<T, S> Thread<T, S> {
273    /// A snapshot may remove or replace a tool result or the assistant that
274    /// held a decided call. Keep local provenance only for what survives it.
275    fn apply_event(&mut self, event: &Event) -> Result<Changed> {
276        let Event::MessagesSnapshot(snapshot) = event else {
277            return self.applier.apply(event);
278        };
279        let echoed: HashMap<_, _> = snapshot
280            .messages
281            .iter()
282            .filter(|message| self.abandoned.contains(message.id()))
283            .map(|message| (message.id(), message))
284            .collect();
285        self.abandoned.retain(|id| {
286            self.applier
287                .message(id)
288                .is_some_and(|old| echoed.get(id) == Some(&old))
289        });
290        let before: HashMap<_, _> = self
291            .decided_interrupt_tool_call_ids
292            .iter()
293            .filter_map(|call| {
294                self.applier
295                    .tool_call_holder(call)
296                    .map(|holder| (call.clone(), holder.clone()))
297            })
298            .collect();
299        let changed = self.applier.apply(event)?;
300        self.decided_interrupt_tool_call_ids.retain(|call| {
301            self.applier
302                .tool_call_holder(call)
303                .is_some_and(|holder| before.get(call) == Some(holder))
304        });
305        Ok(changed)
306    }
307}
308
309impl<T: Transport, S> Thread<T, S> {
310    pub(super) fn start(
311        &mut self,
312        message: Option<Message>,
313        resume: Option<Vec<ResumeEntry>>,
314    ) -> Result<RunStream<'_, T, S>> {
315        let run_id = match &self.next_run_id {
316            Some(id) => id.clone(),
317            None => RunId::new(self.fresh_id(true)?),
318        };
319        let initial_ids = self
320            .messages()
321            .iter()
322            .map(|message| message.id().clone())
323            .collect();
324        // Activity messages describe local renderer state. Like the reference
325        // client, retain them in the thread but omit them from agent requests.
326        // Nothing else is left out: a reasoning message goes back as it
327        // stands, which is what returns its `encryptedValue` to the agent.
328        let messages = self
329            .messages()
330            .iter()
331            .chain(message.iter())
332            .filter(|message| !matches!(message, Message::Activity(_)))
333            .cloned()
334            .collect();
335        let input = RunAgentInput {
336            thread_id: self.thread_id.clone(),
337            run_id,
338            protocol_version: self.protocol_version.clone(),
339            parent_run_id: None,
340            state: self.raw_state().clone(),
341            messages,
342            tools: self.tools.clone(),
343            context: self.context.clone(),
344            forwarded_props: self.forwarded_props.clone(),
345            resume,
346        };
347        let verifier = self.verify.then(Verifier::new);
348        let request_run_id = input.run_id.clone();
349        Ok(RunStream {
350            request_run_id,
351            thread: self,
352            prepared: Some((input, message)),
353            validated: false,
354            events: None,
355            normalizer: ChunkNormalizer::new(),
356            verifier,
357            expanded: Vec::new(),
358            ready: VecDeque::new(),
359            done: false,
360            dispatched: false,
361            abort: AbortHandle::default(),
362            end: None,
363            run: None,
364            runs: Vec::new(),
365            opened: false,
366            leading: None,
367            live: false,
368            outcome: None,
369            diagnostics: Vec::new(),
370            diagnostics_omitted: 0,
371            initial_ids,
372            shared_ids: HashSet::new(),
373        })
374    }
375}
376
377/// Where a run stands relative to the one the request asked for.
378#[derive(Clone, Copy, Debug, PartialEq, Eq)]
379enum Place {
380    /// Before it: history the producer restates.
381    Replayed,
382    /// The one asked for.
383    Requested,
384    /// After it.
385    Later,
386}
387
388/// The run being read: from its `RUN_STARTED` until its end is settled.
389struct OpenRun {
390    run_id: RunId,
391    place: Place,
392    /// What `RUN_FINISHED` reported, held until the stream says what follows
393    /// it: a `RUN_ERROR` may still fail the run.
394    finished: Option<(RunOutcome, Option<Value>)>,
395    /// The tool calls this run started.
396    started_tool_calls: HashSet<ToolCallId>,
397    /// What this run has warned about once and does not repeat: an encrypted
398    /// value it dropped, a message or tool call it had nowhere to keep. Up
399    /// to [`REMEMBERED`] keys.
400    said: HashSet<String>,
401}
402
403/// "a" or "an", for the role that follows it in a warning.
404fn article(role: &str) -> &'static str {
405    if role.starts_with(['a', 'e', 'i', 'o', 'u']) {
406        "an"
407    } else {
408        "a"
409    }
410}
411
412/// What a warning calls an owner.
413fn whose(owner: &Option<SubagentRunId>) -> String {
414    match owner {
415        None => "the parent agent".to_owned(),
416        Some(id) => format!("subagent \"{}\"", excerpt(id.as_str(), false)),
417    }
418}
419
420#[derive(Default)]
421struct AbortState {
422    aborted: AtomicBool,
423    waker: AtomicWaker,
424}
425/// Cloneable cancellation for one local request. Wakes a pending poll and drops its
426/// connection/response stream. It does not confirm remote cancellation.
427#[derive(Clone, Default)]
428pub struct AbortHandle {
429    state: Arc<AbortState>,
430}
431impl std::fmt::Debug for AbortHandle {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.debug_struct("AbortHandle")
434            .field("aborted", &self.is_aborted())
435            .finish()
436    }
437}
438impl AbortHandle {
439    /// Request local cancellation and wake its consumer.
440    pub fn abort(&self) {
441        self.state.aborted.store(true, Ordering::Release);
442        self.state.waker.wake();
443    }
444    /// Whether cancellation was requested.
445    pub fn is_aborted(&self) -> bool {
446        self.state.aborted.load(Ordering::Acquire)
447    }
448}
449
450/// A lazily dispatched request, read to the end of the stream that answers
451/// it. It borrows the thread until dropped. Every consumed stream yields one
452/// [`Update::RunEnded`] per run it carried and then one [`Update::Done`];
453/// dropping an unpolled one leaves the thread unchanged.
454pub struct RunStream<'a, T, S = Value> {
455    thread: &'a mut Thread<T, S>,
456    prepared: Option<(RunAgentInput, Option<Message>)>,
457    /// Local validation can yield warnings before a transport is even called.
458    validated: bool,
459    events: Option<CheckedStream>,
460    normalizer: ChunkNormalizer,
461    verifier: Option<Verifier>,
462    expanded: Vec<Event>,
463    ready: VecDeque<Update<S>>,
464    done: bool,
465    dispatched: bool,
466    abort: AbortHandle,
467    end: Option<RunEnd>,
468    /// The run being read.
469    run: Option<OpenRun>,
470    /// Every run whose end is settled, in stream order.
471    runs: Vec<RunSummary>,
472    /// Whether a `RUN_STARTED` has arrived.
473    opened: bool,
474    /// A `RUN_ERROR` that opened the stream, held until the stream says what
475    /// follows it: with nothing after it, it is the requested run failing
476    /// before it began; with a run after it, it is history.
477    leading: Option<RunEnd>,
478    /// Whether the requested run has started. A run from then on is live:
479    /// its end says where the conversation stands.
480    live: bool,
481    /// How the last live run ended.
482    outcome: Option<RunEnd>,
483    diagnostics: Vec<RunDiagnostic>,
484    diagnostics_omitted: usize,
485    initial_ids: HashSet<MessageId>,
486    request_run_id: RunId,
487    /// The ids a start of one kind, text or reasoning, has found held by a
488    /// message of the other kind on this stream, up to [`REMEMBERED`].
489    shared_ids: HashSet<MessageId>,
490}
491impl<T, S> std::fmt::Debug for RunStream<'_, T, S> {
492    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493        f.debug_struct("RunStream")
494            .field("pending", &self.ready.len())
495            .field("dispatched", &self.dispatched)
496            .field("done", &self.done)
497            .finish_non_exhaustive()
498    }
499}
500impl<T, S> RunStream<'_, T, S> {
501    /// Read-only materialized conversation while the run is borrowed.
502    pub fn thread(&self) -> &Thread<T, S> {
503        self.thread
504    }
505    /// A handle that cancels this request only.
506    pub fn abort_handle(&self) -> AbortHandle {
507        self.abort.clone()
508    }
509    /// Interrupt consumption locally.
510    pub fn abort(&self) {
511        self.abort.abort();
512    }
513    fn diagnostic(&mut self, error: Error) {
514        if self.diagnostics.len() < self.thread.diagnostic_limit {
515            let kind = match &error {
516                Error::State(_) => "state",
517                Error::Protocol(_) | Error::InvalidPatchDocument { .. } => "protocol",
518                Error::Unsupported(_) => "unsupported",
519                Error::Patch { .. } => "patch",
520                Error::Run { .. } => "run",
521                Error::Json(_) | Error::Decode(_) => "decode",
522                _ => "transport",
523            };
524            self.diagnostics.push(RunDiagnostic {
525                kind,
526                message: error.to_string(),
527            });
528        } else {
529            self.diagnostics_omitted += 1;
530        }
531        self.ready.push_back(Update::Error(error));
532    }
533    /// Kept like a diagnostic, within the same limit, but delivered as a
534    /// warning: the run is unaffected.
535    fn warning(&mut self, warning: String) {
536        if self.diagnostics.len() < self.thread.diagnostic_limit {
537            self.diagnostics.push(RunDiagnostic {
538                kind: "warning",
539                message: warning.clone(),
540            });
541        } else {
542            self.diagnostics_omitted += 1;
543        }
544        self.ready.push_back(Update::Warning(warning));
545    }
546    /// Ends the stream. The end of the last live run is how the request
547    /// went; `stopped` is how reading stopped, for a stream on which no live
548    /// run ended.
549    fn terminate(&mut self, stopped: RunEnd) {
550        if self.done {
551            return;
552        }
553        debug_assert!(self.run.is_none(), "the run being read is settled first");
554        // Nothing followed a failure that opened the stream.
555        self.settle_leading(Place::Requested);
556        self.done = true;
557        self.events = None;
558        self.prepared = None;
559        self.run = None;
560        self.thread.applier.reset_streams();
561        // The requested run settles a resume submission one way or the
562        // other. On a stream without it, nothing did.
563        if self.dispatched && self.outcome.is_none() {
564            self.thread.unconfirm();
565        }
566        let end = self.outcome.take().unwrap_or(stopped);
567        if self.dispatched {
568            self.thread.last_run_end = Some(end.clone());
569            self.thread.active_run_id = None;
570        }
571        self.end = Some(end.clone());
572        self.ready.push_back(Update::Done(end));
573    }
574    /// Queues the update for a change to a reasoning message, with the text
575    /// the message now holds.
576    fn reasoning_changed(&mut self, change: ReasoningChange) {
577        let text = self
578            .thread
579            .applier
580            .text_of(change.id.clone())
581            .unwrap_or_default()
582            .to_owned();
583        self.ready.push_back(Update::Reasoning(ReasoningUpdate {
584            index: change.index,
585            id: change.id,
586            change: change.kind,
587            text,
588        }));
589    }
590    /// Reports what a run that stopped short left open as aborted: its
591    /// messages, its reasoning, its running subagents.
592    fn stop_subagents(&mut self) {
593        let (messages, reasoning) = self.thread.applier.abort_messages();
594        for change in messages {
595            if let Some(message) = self.thread.applier.messages().get(change.index) {
596                self.ready.push_back(Update::Message(MessageUpdate {
597                    index: change.index,
598                    id: change.id,
599                    change: change.kind,
600                    message: message.clone(),
601                }));
602            }
603        }
604        for change in reasoning {
605            self.reasoning_changed(change);
606        }
607        for change in self.thread.applier.abort_subagents() {
608            let subagent = self.thread.applier.subagents()[change.index].clone();
609            self.ready.push_back(Update::Subagent(SubagentUpdate {
610                index: change.index,
611                run_id: change.run_id,
612                change: change.kind,
613                subagent,
614            }));
615        }
616    }
617    /// Stops reading because of `error`. The run being read fails with it,
618    /// and so does the request, unless a live run already said how it went.
619    fn fail(&mut self, error: Error) {
620        let end = RunEnd::Failed {
621            message: error.to_string(),
622            code: None,
623        };
624        self.diagnostic(error);
625        if !self.settle_stopped(end.clone()) {
626            self.stop_subagents();
627        }
628        self.terminate(end);
629    }
630    /// Stops reading at the application's request: an abort, or a drop.
631    fn stop(&mut self) {
632        // A run that reported how it ended keeps that ending.
633        if !self.settle_reported() && !self.settle_stopped(RunEnd::Aborted) && self.dispatched {
634            self.stop_subagents();
635        }
636        self.terminate(RunEnd::Aborted);
637    }
638    /// The stream ended.
639    fn end_of_input(&mut self) {
640        // A failure that opened the stream, and nothing after it.
641        self.settle_leading(Place::Requested);
642        // A run that reported how it ended is over. One still active was cut
643        // short, and so was a stream no run arrived on.
644        if !self.settle_reported() && (self.run.is_some() || self.runs.is_empty()) {
645            let error = self
646                .verifier
647                .as_ref()
648                .and_then(|verifier| verifier.finish().err())
649                .unwrap_or_else(|| {
650                    Error::protocol("the stream ended before RUN_FINISHED or RUN_ERROR")
651                });
652            return self.fail(error);
653        }
654        match self.outcome.clone() {
655            Some(end) => self.terminate(end),
656            // Every run on the stream was a replayed one.
657            None => self.fail(Error::protocol(format!(
658                "the stream ended without the requested run: no RUN_STARTED carried run ID {:?}",
659                self.request_run_id.as_str()
660            ))),
661        }
662    }
663    /// Whether the run being read reported `RUN_FINISHED`, and waits for the
664    /// stream to say what follows.
665    fn reported(&self) -> bool {
666        self.run.as_ref().is_some_and(|run| run.finished.is_some())
667    }
668    /// Ends the run being read as its `RUN_FINISHED` reported, if one
669    /// arrived and nothing has ended the run since.
670    fn settle_reported(&mut self) -> bool {
671        if !self.reported() {
672            return false;
673        }
674        let run = self.run.take().expect("a run is being read");
675        let (outcome, result) = run.finished.expect("the run reported RUN_FINISHED");
676        let end = match outcome {
677            RunOutcome::Success => RunEnd::Success { result },
678            RunOutcome::SuccessWithPendingToolCalls {
679                pending_tool_call_ids,
680            } => RunEnd::SuccessWithPendingToolCalls {
681                result,
682                pending_tool_call_ids,
683            },
684            RunOutcome::Interrupt { interrupts } => RunEnd::Interrupted { interrupts },
685            RunOutcome::Cancelled => RunEnd::Cancelled,
686        };
687        self.settle(Some(run.run_id), run.place, &run.started_tool_calls, end);
688        true
689    }
690    /// Places a failure that opened the stream, if one is held: as the
691    /// requested run when nothing followed it, and as history when a run
692    /// did. AG-UI 1.0, `events/lifecycle`: "`RUN_ERROR` is admitted first
693    /// because a run can fail before it begins". One run answers a request,
694    /// so a stream that goes on to a run did not carry the requested one
695    /// before it.
696    fn settle_leading(&mut self, place: Place) {
697        if let Some(end) = self.leading.take() {
698            self.live |= place == Place::Requested;
699            self.settle(None, place, &HashSet::new(), end);
700        }
701    }
702    /// Ends the run being read, if there is one, short of an ending of its
703    /// own: reading stopped, or the stream was rejected. A `RUN_FINISHED` it
704    /// had reported is withdrawn.
705    fn settle_stopped(&mut self, end: RunEnd) -> bool {
706        let Some(run) = self.run.take() else {
707            return false;
708        };
709        self.settle(Some(run.run_id), run.place, &run.started_tool_calls, end);
710        true
711    }
712    /// Records how one run ended, and applies what that means for the thread.
713    fn settle(
714        &mut self,
715        run_id: Option<RunId>,
716        place: Place,
717        started_tool_calls: &HashSet<ToolCallId>,
718        end: RunEnd,
719    ) {
720        let confirms = matches!(
721            end,
722            RunEnd::Success { .. }
723                | RunEnd::SuccessWithPendingToolCalls { .. }
724                | RunEnd::Interrupted { .. }
725        );
726        // Only the requested run answers the request, so only it settles a
727        // resume submission.
728        if place == Place::Requested {
729            if confirms {
730                self.thread
731                    .confirm_interrupt_tool_decisions(started_tool_calls);
732                self.thread.submission = None;
733            } else if end == RunEnd::Cancelled {
734                // AG-UI 1.0, `events/lifecycle`, "Cancelled runs": "A
735                // cancelled run waits for nothing. Its outcome carries no
736                // interrupts, and the next run on the thread is an ordinary
737                // new run, not a resume." The run took the answers and
738                // reported how it ended, so nothing is left to reconcile. It
739                // did not complete, so a tool call an answer approved is not
740                // recorded as decided: without a result it is still owed.
741                self.thread.submission = None;
742            } else {
743                self.thread.unconfirm();
744            }
745        }
746        if confirms {
747            // RUN_FINISHED found everything closed, unless nothing checked.
748            self.thread.applier.reset_streams();
749        } else {
750            self.stop_subagents();
751        }
752        if place != Place::Replayed {
753            self.replace_pending(run_id.as_ref(), place, &end);
754            self.outcome = Some(end.clone());
755        }
756        let summary = RunSummary {
757            run_id,
758            end,
759            requested: place == Place::Requested,
760        };
761        self.runs.push(summary.clone());
762        self.ready.push_back(Update::RunEnded(summary));
763    }
764    /// What a live run's end leaves pending on the thread: an interrupt
765    /// outcome sets the pending interrupts, a success or cancelled one
766    /// clears them, and a run that failed or was cut short leaves them.
767    ///
768    /// Not while a resume submission is held. Its entries answer exactly the
769    /// pending interrupts, and it stays until the application reconciles it,
770    /// so they stay with it.
771    fn replace_pending(&mut self, run_id: Option<&RunId>, place: Place, end: &RunEnd) {
772        let (pending, outcome): (&[Interrupt], _) = match end {
773            RunEnd::Interrupted { interrupts } => (interrupts, "interrupt"),
774            RunEnd::Success { .. } | RunEnd::SuccessWithPendingToolCalls { .. } => (&[], "success"),
775            RunEnd::Cancelled => (&[], "cancelled"),
776            RunEnd::Failed { .. } | RunEnd::Aborted => return,
777        };
778        if self.thread.submission.is_none() {
779            self.thread.interrupts = pending.to_vec();
780            for interrupt in pending {
781                self.ready.push_back(Update::Interrupt(interrupt.clone()));
782            }
783        } else if place == Place::Later && self.thread.interrupts != pending {
784            // That the requested run left the submission unconfirmed is its
785            // own ending. This run came after it, and would have moved the
786            // thread on.
787            let run = run_id.map_or_else(String::new, |id| {
788                format!(" \"{}\"", crate::protocol::excerpt(id.as_str(), false))
789            });
790            self.warning(format!(
791                "run{run} finished with outcome `{outcome}` while a resume submission is \
792                 unconfirmed: the pending interrupts stay the ones that submission answers \
793                 until the application reconciles it"
794            ));
795        }
796    }
797}
798impl<T, S> Drop for RunStream<'_, T, S> {
799    fn drop(&mut self) {
800        if self.dispatched && !self.done {
801            self.stop();
802        }
803    }
804}
805
806impl<T: Transport, S: DeserializeOwned + Clone + Unpin> RunStream<'_, T, S> {
807    /// Consume the remainder and return the outcome, the runs and the
808    /// diagnostics of the whole stream.
809    pub async fn collect_report(mut self) -> RunReport {
810        while self.next().await.is_some() {}
811        RunReport {
812            end: self
813                .end
814                .clone()
815                .expect("a consumed stream has a terminal outcome"),
816            runs: std::mem::take(&mut self.runs),
817            new_messages: self
818                .thread
819                .messages()
820                .iter()
821                .filter(|message| !self.initial_ids.contains(message.id()))
822                .cloned()
823                .collect(),
824            diagnostics: std::mem::take(&mut self.diagnostics),
825            diagnostics_omitted: self.diagnostics_omitted,
826        }
827    }
828}
829
830impl<T, S: DeserializeOwned + Clone> RunStream<'_, T, S> {
831    fn ingest(&mut self, event: Event) {
832        if let Some(observer) = &mut self.thread.observer {
833            observer(&event);
834        }
835        if matches!(event, Event::RunError(_)) {
836            // A failed run ends what it had open along with it. Nothing is
837            // closed on its behalf, and nothing of it is left for the next
838            // run to close.
839            self.normalizer.abandon();
840            self.handle(event);
841            return;
842        }
843        let mut expanded = std::mem::take(&mut self.expanded);
844        expanded.clear();
845        let result = self.normalizer.normalize(event, &mut expanded);
846        for event in expanded.drain(..) {
847            if !self.done {
848                self.handle(event);
849            }
850        }
851        self.expanded = expanded;
852        if let Err(error) = result {
853            self.fail(error);
854        }
855    }
856    fn handle(&mut self, event: Event) {
857        // Pair each run's boundary events with each other and with the
858        // request, even when optional ordering verification is disabled. Run
859        // errors carry no IDs.
860        let mut opening = None;
861        match &event {
862            Event::RunStarted(started) => {
863                match self.run.as_ref().filter(|run| run.finished.is_none()) {
864                    // Inside a run that has not ended it is a nested run
865                    // whatever ids it carries, and the verifier says so.
866                    // Without one, the same run announced again is let
867                    // through, as it always was.
868                    Some(active) => {
869                        let again = started.thread_id == self.thread.thread_id
870                            && started.run_id == active.run_id;
871                        if self.verifier.is_none() && !again {
872                            self.fail(nested_run_started());
873                            return;
874                        }
875                    }
876                    None => {
877                        // The run before it, if it reported how it ended, is
878                        // over: nothing can fail it now.
879                        self.settle_reported();
880                        if started.thread_id != self.thread.thread_id {
881                            self.fail(Error::protocol(
882                                "RUN_STARTED does not match the requested thread ID",
883                            ));
884                            return;
885                        }
886                        if self.live && started.run_id == self.request_run_id {
887                            self.fail(Error::protocol(
888                                "the requested run ID was started a second time",
889                            ));
890                            return;
891                        }
892                        opening = Some(started.run_id.clone());
893                    }
894                }
895            }
896            Event::RunFinished(finished) => {
897                let closes = finished.thread_id == self.thread.thread_id
898                    && self
899                        .run
900                        .as_ref()
901                        .is_some_and(|run| run.run_id == finished.run_id);
902                if !closes {
903                    self.fail(Error::protocol("RUN_FINISHED does not match RUN_STARTED"));
904                    return;
905                }
906                if self.verifier.is_none() {
907                    if let Some(error) = finished
908                        .outcome
909                        .as_ref()
910                        .and_then(RunOutcome::interrupt_error)
911                    {
912                        self.fail(Error::protocol(error));
913                        return;
914                    }
915                }
916            }
917            _ => {}
918        }
919        if let Some(verifier) = &mut self.verifier {
920            if let Err(error) = verifier.verify(&event) {
921                self.fail(error);
922                return;
923            }
924        }
925        if let Some(run_id) = opening {
926            self.open(run_id);
927        }
928        let same_replayed_call = match &event {
929            Event::ToolCallStart(started)
930                if self
931                    .run
932                    .as_ref()
933                    .is_some_and(|r| r.place == Place::Replayed) =>
934            {
935                started.parent_message_id.as_ref().is_some_and(|holder| {
936                    self.thread.applier.tool_call_holder(&started.tool_call_id) == Some(holder)
937                })
938            }
939            _ => false,
940        };
941        match self.thread.apply_event(&event) {
942            Ok(changed) => {
943                self.remark(&event, &changed);
944                if let Event::ToolCallStart(started) = &event {
945                    if !same_replayed_call {
946                        self.thread
947                            .decided_interrupt_tool_call_ids
948                            .remove(&started.tool_call_id);
949                    }
950                    if let Some(run) = &mut self.run {
951                        run.started_tool_calls.insert(started.tool_call_id.clone());
952                    }
953                }
954                if let Event::ToolCallResult(result) = &event {
955                    // A result that arrives under the id of a stand-in for
956                    // one replaces it, and is a result.
957                    self.thread.abandoned.remove(&result.message_id);
958                }
959                self.emit(changed);
960            }
961            Err(error @ Error::Patch { .. }) => self.diagnostic(error),
962            Err(error) => self.fail(error),
963        }
964    }
965    /// Begins reading the run a `RUN_STARTED` opened.
966    ///
967    /// The run that echoes the request's id is the requested one. One before
968    /// it is replayed, one after it is not, and neither is held to the
969    /// request's id: AG-UI 1.0, `basic/run-input`, "the requested run echoes
970    /// this input's `runId`; a replayed run carries its own".
971    fn open(&mut self, run_id: RunId) {
972        let place = if run_id == self.request_run_id {
973            Place::Requested
974        } else if self.live {
975            Place::Later
976        } else {
977            Place::Replayed
978        };
979        // A failure that opened the stream was not the requested run: a run
980        // follows it.
981        self.settle_leading(Place::Replayed);
982        self.opened = true;
983        self.live |= place == Place::Requested;
984        // A new run starts with nothing open.
985        self.thread.applier.reset_streams();
986        self.run = Some(OpenRun {
987            run_id,
988            place,
989            finished: None,
990            started_tool_calls: HashSet::new(),
991            said: HashSet::new(),
992        });
993    }
994    /// Warns that an encrypted value was dropped, once per text per run:
995    /// AG-UI 1.0 (`events/reasoning`, "Error Handling") says a consumer
996    /// SHOULD warn about one whose entity it does not hold, and MAY drop it.
997    /// The applier stores it nowhere when no message or tool call it holds
998    /// can take it, an activity message included.
999    fn dropped(&mut self, event: &ReasoningEncryptedValueEvent) {
1000        let noun = match event.subtype {
1001            ReasoningEncryptedValueSubtype::Message => "message",
1002            ReasoningEncryptedValueSubtype::ToolCall => "tool call",
1003        };
1004        let warning = format!(
1005            "REASONING_ENCRYPTED_VALUE for {noun} \"{}\" was dropped: the thread holds no \
1006             {noun} with that id that can store it",
1007            excerpt(&event.entity_id, false)
1008        );
1009        if self.first(warning.clone()) {
1010            self.warning(warning);
1011        }
1012    }
1013    /// Whether `key` has not come up before in the run being read, so that
1014    /// what it stands for is said once per run. Up to [`REMEMBERED`] keys are
1015    /// kept; past that, and outside a run, everything is said.
1016    fn first(&mut self, key: String) -> bool {
1017        let Some(run) = &mut self.run else {
1018            return true;
1019        };
1020        if run.said.contains(&key) {
1021            return false;
1022        }
1023        if run.said.len() < REMEMBERED {
1024            run.said.insert(key);
1025        }
1026        true
1027    }
1028    /// Warns about what an event the applier took could not do, or did
1029    /// somewhere other than where it said. None of it fails the run: the
1030    /// verifier accepted the stream, and a consumer that cannot keep
1031    /// something says so and carries on, as the reference client does.
1032    fn remark(&mut self, event: &Event, changed: &Changed) {
1033        match (event, changed) {
1034            (Event::ReasoningEncryptedValue(value), Changed::Nothing) => self.dropped(value),
1035            (Event::MessagesSnapshot(snapshot), _) => self.repeated(&snapshot.messages),
1036            (Event::ToolCallStart(start), Changed::Message(change)) => {
1037                let named = start.parent_message_id.as_ref();
1038                if let Some(parent) = named.filter(|parent| **parent != change.id) {
1039                    self.carried_apart(&start.tool_call_id, parent, &change.id);
1040                }
1041            }
1042            (Event::TextMessageStart(start), Changed::Message(change)) => {
1043                self.shared(event, &start.subagent_run_id, change.index, "text");
1044            }
1045            (Event::ReasoningMessageStart(start), Changed::Reasoning(change)) => {
1046                self.shared(event, &start.subagent_run_id, change.index, "reasoning");
1047            }
1048            (_, Changed::Nothing) => self.unplaced(event),
1049            _ => {}
1050        }
1051    }
1052    /// Warns that an event of a message or a tool call was dropped because
1053    /// the thread has nowhere to keep it, once per item per run.
1054    ///
1055    /// This is what follows a `MESSAGES_SNAPSHOT` that removed a message, or
1056    /// restated one without a call, while the run still had it open. AG-UI
1057    /// 1.0 (`basic/patterns/snapshots`): "A consumer MUST replace its copy
1058    /// with the snapshot's content — a snapshot is not a merge". The
1059    /// snapshot closes nothing, so the events that follow are in order, and
1060    /// they have nothing to continue. The same goes for text streamed into
1061    /// an id an activity message holds.
1062    fn unplaced(&mut self, event: &Event) {
1063        let held = |id: &MessageId| match self.thread.applier.message(id) {
1064            Some(Message::Activity(_)) => {
1065                "the thread holds an activity message with that id, which takes no text"
1066            }
1067            _ => "the thread holds no message with that id",
1068        };
1069        let (noun, id, why) = match event {
1070            Event::TextMessageStart(e) => ("message", e.message_id.as_str(), held(&e.message_id)),
1071            Event::TextMessageContent(e) => ("message", e.message_id.as_str(), held(&e.message_id)),
1072            Event::TextMessageEnd(e) => ("message", e.message_id.as_str(), held(&e.message_id)),
1073            Event::ReasoningMessageStart(e) => (
1074                "reasoning message",
1075                e.message_id.as_str(),
1076                held(&e.message_id),
1077            ),
1078            Event::ReasoningMessageContent(e) => (
1079                "reasoning message",
1080                e.message_id.as_str(),
1081                held(&e.message_id),
1082            ),
1083            Event::ReasoningMessageEnd(e) => (
1084                "reasoning message",
1085                e.message_id.as_str(),
1086                held(&e.message_id),
1087            ),
1088            Event::ToolCallStart(e) => (
1089                "tool call",
1090                e.tool_call_id.as_str(),
1091                "the thread holds no message that can carry it",
1092            ),
1093            Event::ToolCallArgs(e) => (
1094                "tool call",
1095                e.tool_call_id.as_str(),
1096                "no message the thread holds has that call",
1097            ),
1098            Event::ToolCallEnd(e) => (
1099                "tool call",
1100                e.tool_call_id.as_str(),
1101                "no message the thread holds has that call",
1102            ),
1103            _ => return,
1104        };
1105        let warning = format!(
1106            "{} for {noun} \"{}\" was dropped: {why}",
1107            event.event_type(),
1108            excerpt(id, false)
1109        );
1110        if self.first(format!("unplaced {noun} {id}")) {
1111            self.warning(warning);
1112        }
1113    }
1114    /// Warns that a tool call is on a message of its own because the parent
1115    /// it named is not an assistant message, once per call per run.
1116    fn carried_apart(&mut self, call: &ToolCallId, parent: &MessageId, carrier: &MessageId) {
1117        let Some(named) = self.thread.applier.message(parent) else {
1118            return;
1119        };
1120        let role = named.role().as_str();
1121        let warning = format!(
1122            "TOOL_CALL_START for tool call \"{}\" names parent message \"{}\", which is {} \
1123             {role} message and carries no tool calls: the call is on message \"{}\"",
1124            excerpt(call.as_str(), false),
1125            excerpt(parent.as_str(), false),
1126            article(role),
1127            excerpt(carrier.as_str(), false)
1128        );
1129        if self.first(format!("carried apart {call}")) {
1130            self.warning(warning);
1131        }
1132    }
1133    /// Warns that a text message and a reasoning message of different owners
1134    /// share an id, when a start of one kind lands on a message the other
1135    /// kind made: an id names one message, so what the start opens goes into
1136    /// the other owner's message. Checked at the first such start of an id
1137    /// on the stream, which is the one whose attribution opens the item; a
1138    /// later one continues it.
1139    ///
1140    /// The ordering rules keep the two kinds apart, as the reference
1141    /// verifier does, and accept the stream. This says what the conversation
1142    /// made of it.
1143    fn shared(&mut self, event: &Event, from: &Option<SubagentRunId>, index: usize, what: &str) {
1144        let Some(message) = self.thread.applier.messages().get(index) else {
1145            return;
1146        };
1147        let reasoning = matches!(message, Message::Reasoning(_));
1148        if reasoning == (what == "reasoning") {
1149            return;
1150        }
1151        if self.shared_ids.len() >= REMEMBERED || !self.shared_ids.insert(message.id().clone()) {
1152            return;
1153        }
1154        let owner = message.subagent_run_id().cloned();
1155        if *from == owner {
1156            return;
1157        }
1158        let role = message.role().as_str();
1159        let warning = format!(
1160            "{} for message \"{}\" is from {}, and the thread holds {} {role} message with \
1161             that id from {}: the id is shared across owners, and the {what} goes into that \
1162             message",
1163            event.event_type(),
1164            excerpt(message.id().as_str(), false),
1165            whose(from),
1166            article(role),
1167            whose(&owner)
1168        );
1169        self.warning(warning);
1170    }
1171    /// Warns that a `MESSAGES_SNAPSHOT` carried a message id more than once,
1172    /// once per id per run. AG-UI 1.0, `basic`: a `messageId` "MUST be
1173    /// unique within its thread". The applier kept the last copy.
1174    fn repeated(&mut self, messages: &[Message]) {
1175        let mut seen = HashSet::with_capacity(messages.len());
1176        let mut told = HashSet::new();
1177        for id in messages.iter().map(Message::id) {
1178            if seen.insert(id) || !told.insert(id) {
1179                continue;
1180            }
1181            let warning = format!(
1182                "MESSAGES_SNAPSHOT carries message id \"{}\" more than once: the last copy is \
1183                 kept, where the first stood. A message id is unique within its thread",
1184                excerpt(id.as_str(), false)
1185            );
1186            if self.first(warning.clone()) {
1187                self.warning(warning);
1188            }
1189        }
1190    }
1191    fn emit(&mut self, changed: Changed) {
1192        match changed {
1193            Changed::Nothing | Changed::RunStarted { .. } => {}
1194            Changed::Message(change) => {
1195                if let Some(message) = self.thread.applier.messages().get(change.index) {
1196                    self.ready.push_back(Update::Message(MessageUpdate {
1197                        index: change.index,
1198                        id: change.id,
1199                        change: change.kind,
1200                        message: message.clone(),
1201                    }));
1202                }
1203            }
1204            Changed::MessagesReplaced => self
1205                .ready
1206                .push_back(Update::Messages(self.thread.messages().to_vec())),
1207            Changed::State => match self.thread.applier.state_as::<S>() {
1208                Ok(state) => {
1209                    self.thread.state = Ok(state.clone());
1210                    self.ready.push_back(Update::State(state));
1211                }
1212                Err(error) => {
1213                    self.thread.state = Err(StateViewError {
1214                        message: match &error {
1215                            Error::State(error) => error.to_string(),
1216                            _ => error.to_string(),
1217                        },
1218                    });
1219                    self.diagnostic(error);
1220                }
1221            },
1222            Changed::Reasoning(change) => self.reasoning_changed(change),
1223            Changed::Subagent(change) => {
1224                if let Some(subagent) = self.thread.applier.subagents().get(change.index) {
1225                    self.ready.push_back(Update::Subagent(SubagentUpdate {
1226                        index: change.index,
1227                        run_id: change.run_id,
1228                        change: change.kind,
1229                        subagent: subagent.clone(),
1230                    }));
1231                }
1232            }
1233            // The run is closed, but a RUN_ERROR may still follow and fail
1234            // it, so the outcome takes effect when the stream says what
1235            // comes next.
1236            Changed::RunFinished { outcome, result } => {
1237                if let Some(run) = &mut self.run {
1238                    run.finished = Some((outcome, result));
1239                }
1240            }
1241            // The run is over, and the stream is not: the next run may
1242            // follow.
1243            Changed::RunError { message, code } => {
1244                self.diagnostic(Error::Run {
1245                    message: message.clone(),
1246                    code: code.clone(),
1247                });
1248                let end = RunEnd::Failed { message, code };
1249                if !self.settle_stopped(end.clone()) {
1250                    // No run to fail.
1251                    match (self.opened, self.live) {
1252                        // Before any RUN_STARTED. Whether it is the requested
1253                        // run failing before it began shows in what follows,
1254                        // so it is held until then. A second one, which only
1255                        // a stream nothing verifies carries, makes the first
1256                        // history.
1257                        (false, _) => {
1258                            self.settle_leading(Place::Replayed);
1259                            self.leading = Some(end);
1260                        }
1261                        (true, true) => self.settle(None, Place::Later, &HashSet::new(), end),
1262                        (true, false) => {
1263                            self.settle(None, Place::Replayed, &HashSet::new(), end);
1264                        }
1265                    }
1266                }
1267            }
1268        }
1269    }
1270}
1271
1272impl<T: Transport, S: DeserializeOwned + Clone + Unpin> Stream for RunStream<'_, T, S> {
1273    type Item = Update<S>;
1274    fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
1275        let this = self.get_mut();
1276        this.abort.state.waker.register(cx.waker());
1277        loop {
1278            // A terminal already applied wins over a later abort.
1279            if !this.done && this.abort.is_aborted() {
1280                this.stop();
1281            }
1282            if let Some(update) = this.ready.pop_front() {
1283                return Poll::Ready(Some(update));
1284            }
1285            if this.done {
1286                return Poll::Ready(None);
1287            }
1288            if let Some((input, message)) = this.prepared.take() {
1289                // Expiry may have passed while the prepared stream sat unpolled.
1290                if let Some(entries) = &input.resume {
1291                    if let Err(error) = validate_responses(&this.thread.interrupts, entries, true) {
1292                        this.fail(error);
1293                        continue;
1294                    }
1295                }
1296                let input = if this.validated {
1297                    input
1298                } else {
1299                    let mut warnings = input.resume.as_ref().map_or_else(Vec::new, |entries| {
1300                        unread_expiries(&this.thread.interrupts, entries)
1301                    });
1302                    let normalized = crate::client::agent::outgoing(input, &mut warnings);
1303                    for warning in warnings {
1304                        this.warning(warning);
1305                    }
1306                    let input = match normalized {
1307                        Ok(input) => input,
1308                        Err(error) => {
1309                            this.fail(error);
1310                            continue;
1311                        }
1312                    };
1313                    if !this.ready.is_empty() {
1314                        // No request has left the thread. Dropping the stream
1315                        // while reading these warnings leaves a resume retryable.
1316                        this.validated = true;
1317                        this.prepared = Some((input, message));
1318                        continue;
1319                    }
1320                    input
1321                };
1322                this.dispatched = true;
1323                this.thread.applier.reset_streams();
1324                this.thread.run_ids.insert(input.run_id.clone());
1325                this.thread.active_run_id = Some(input.run_id.clone());
1326                this.thread.next_run_id = None;
1327                if let Some(message) = message {
1328                    this.thread.append_local_message(message);
1329                }
1330                if let Some(entries) = &input.resume {
1331                    this.thread.submission = Some(ResumeSubmission {
1332                        run_id: input.run_id.clone(),
1333                        entries: entries.clone(),
1334                        status: SubmissionStatus::InFlight,
1335                    });
1336                }
1337                this.events = Some(this.thread.agent.run_checked(input));
1338            }
1339            match this
1340                .events
1341                .as_mut()
1342                .expect("dispatched run has a stream")
1343                .as_mut()
1344                .poll_next(cx)
1345            {
1346                Poll::Pending => return Poll::Pending,
1347                Poll::Ready(Some(Ok(Checked::Event(event)))) => this.ingest(event),
1348                Poll::Ready(Some(Ok(Checked::Warning(warning)))) => this.warning(warning),
1349                // After RUN_FINISHED a broken connection truncates nothing:
1350                // the run already ended, so the break is only reported. It
1351                // still fails a request whose own run was yet to come.
1352                Poll::Ready(Some(Err(error @ Error::Transport(_)))) if this.reported() => {
1353                    let stopped = RunEnd::Failed {
1354                        message: error.to_string(),
1355                        code: None,
1356                    };
1357                    this.diagnostic(error);
1358                    this.settle_reported();
1359                    this.terminate(stopped);
1360                }
1361                Poll::Ready(Some(Err(error))) => this.fail(error),
1362                Poll::Ready(None) => this.end_of_input(),
1363            }
1364        }
1365    }
1366}