Skip to main content

ag_ui/client/
thread.rs

1//! A local conversation: independent history, state and human input over a shared transport.
2//!
3//! [`Thread`] owns its transport handle; dropping the agent that created it is safe.
4//! It does not automatically fetch server history or synchronize other local copies.
5//! Each run borrows the thread until dropped. Requests are dispatched on first poll.
6
7use std::collections::{HashSet, VecDeque};
8use std::pin::Pin;
9use std::sync::{
10    Arc,
11    atomic::{AtomicBool, Ordering},
12};
13use std::task::{Context as TaskContext, Poll};
14
15use crate::client::{
16    agent::RemoteAgent,
17    apply::{
18        Applier, Changed, MessageChangeKind, ReasoningChangeKind, Subagent, SubagentChangeKind,
19    },
20    chunks::ChunkNormalizer,
21    error::{Error, Result},
22    interrupts::InterruptExt,
23    transport::{EventStream, Transport},
24    verify::Verifier,
25};
26use crate::{
27    Context, Event, Interrupt, Message, MessageId, ReasoningMessage, ResumeEntry, RunAgentInput,
28    RunId, RunOutcome, ThreadId, Tool,
29};
30use futures_core::Stream;
31use futures_util::{StreamExt, task::AtomicWaker};
32use serde::{Deserialize, Serialize, de::DeserializeOwned};
33use serde_json::Value;
34
35#[cfg(not(target_family = "wasm"))]
36type Observer = Box<dyn FnMut(&Event) + Send>;
37#[cfg(target_family = "wasm")]
38type Observer = Box<dyn FnMut(&Event)>;
39#[cfg(not(target_family = "wasm"))]
40type IdGenerator = Box<dyn FnMut() -> Result<String> + Send>;
41#[cfg(target_family = "wasm")]
42type IdGenerator = Box<dyn FnMut() -> Result<String>>;
43
44/// Something a view should react to.
45///
46/// One [`Update`] is one redraw. `S` is the caller's state type; it is
47/// [`serde_json::Value`] unless a [`Thread`] is asked for something better.
48#[derive(Debug)]
49#[non_exhaustive]
50pub enum Update<S = Value> {
51    /// A message was created, appended to, or completed.
52    Message(MessageUpdate),
53    /// `MESSAGES_SNAPSHOT` replaced the conversation. Messages may have
54    /// disappeared, so redraw all of it.
55    Messages(Vec<Message>),
56    /// The application state changed, and here it is in the caller's type.
57    ///
58    /// Carries no association with whatever was open when it arrived — a tool
59    /// call, a message — because the wire carries none either. Where it lands
60    /// in the stream is the only nesting there is; see the [module
61    /// docs](self).
62    State(S),
63    /// Reasoning text arrived. Kept separate from the reply.
64    Reasoning(ReasoningUpdate),
65    /// A subagent was announced, resumed, finished, suspended or failed.
66    ///
67    /// The lifecycle only: what a subagent *says* arrives as ordinary
68    /// [`Update::Message`]s and [`Update::Reasoning`]s whose messages carry
69    /// its `subagent_run_id`, so a view groups by that and uses this for the
70    /// group's header and status. See [`Thread::subagents`].
71    Subagent(SubagentUpdate),
72    /// The run paused and needs a human. Answer it with
73    /// [`Thread::resume`] — one update per pending interrupt.
74    Interrupt(Interrupt),
75    /// Something went wrong: a malformed stream, a patch that would not apply,
76    /// a transport failure, a `RUN_ERROR`.
77    ///
78    /// Not necessarily fatal — a run survives a patch it could not apply. When
79    /// it is fatal, the matching [`Update::Done`] follows.
80    Error(Error),
81    /// The run ended, and how. Always the last update of a run, on every path
82    /// out: the agent finishing, the agent failing, and the transport dying
83    /// mid-sentence.
84    Done(RunEnd),
85}
86
87/// A message that changed, and the message as it now stands.
88#[derive(Clone, Debug, PartialEq)]
89pub struct MessageUpdate {
90    /// Index into [`Thread::messages`].
91    pub index: usize,
92    /// The message's id.
93    pub id: MessageId,
94    /// What this event did to it — the text delta, the tool call, the close.
95    pub change: MessageChangeKind,
96    /// The whole message, assembled so far.
97    pub message: Message,
98}
99
100/// Reasoning that changed, and the reasoning as it now stands.
101#[derive(Clone, Debug, PartialEq)]
102pub struct ReasoningUpdate {
103    /// The reasoning message's id.
104    pub id: MessageId,
105    /// What this event did to it.
106    pub change: ReasoningChangeKind,
107    /// The accumulated reasoning text.
108    pub text: String,
109}
110
111/// A subagent that changed, and the subagent as it now stands.
112#[derive(Clone, Debug, PartialEq)]
113pub struct SubagentUpdate {
114    /// Index into [`Thread::subagents`].
115    pub index: usize,
116    /// The invocation's id — what the messages it produced carry.
117    pub run_id: crate::SubagentRunId,
118    /// What this event did to it.
119    pub change: SubagentChangeKind,
120    /// The whole entry, status included.
121    pub subagent: Subagent,
122}
123
124/// How the remote run ended, or how local consumption stopped.
125#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
126pub enum RunEnd {
127    /// The server confirmed successful completion. Local diagnostics remain separate.
128    Success {
129        /// Optional server result.
130        result: Option<Value>,
131    },
132    /// The server paused for input.
133    Interrupted {
134        /// Current pending questions.
135        interrupts: Vec<Interrupt>,
136    },
137    /// The server or transport failed, or its terminal event was invalid.
138    Failed {
139        /// Human-readable cause.
140        message: String,
141        /// Optional server error code.
142        code: Option<String>,
143    },
144    /// Local consumption stopped. This does not confirm cancellation on the server.
145    Aborted,
146}
147
148/// A typed view of current raw state could not be constructed.
149#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
150#[error("state does not match the expected type: {message}")]
151pub struct StateViewError {
152    /// The deserializer's explanation.
153    pub message: String,
154}
155
156/// One retained diagnostic, independent of the terminal outcome.
157#[derive(Clone, Debug, PartialEq, Eq)]
158pub struct RunDiagnostic {
159    /// A stable broad category (`state`, `protocol`, `patch`, `transport`, or `run`).
160    pub kind: &'static str,
161    /// Human-readable cause.
162    pub message: String,
163}
164
165/// Results from the whole run, including updates consumed before `collect_report`.
166#[derive(Clone, Debug, PartialEq)]
167pub struct RunReport {
168    /// The observed terminal outcome.
169    pub end: RunEnd,
170    /// Messages whose IDs were absent when this run was prepared.
171    pub new_messages: Vec<Message>,
172    /// Retained diagnostics, in observation order.
173    pub diagnostics: Vec<RunDiagnostic>,
174    /// Diagnostics beyond the configured retention limit.
175    pub diagnostics_omitted: usize,
176}
177
178/// Local observation of an interrupt response submission.
179#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
180pub struct ResumeSubmission {
181    /// The request that carried these responses.
182    pub run_id: RunId,
183    /// Exact answers, retained for reconciliation by the application.
184    pub entries: Vec<ResumeEntry>,
185    /// Whether a valid terminal response has confirmed the request.
186    pub status: SubmissionStatus,
187}
188
189/// A submission is never retried automatically.
190#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
191pub enum SubmissionStatus {
192    /// Dispatched and still being observed. Restoring this becomes `Unconfirmed`.
193    InFlight,
194    /// Consumption stopped without a validated success or interrupt terminal.
195    Unconfirmed,
196}
197
198/// A versioned local snapshot. It contains conversation data, never a transport,
199/// observer or running future. Validate it through `restore` before using it.
200#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
201pub struct ThreadSnapshot {
202    /// Snapshot format version (currently 1).
203    pub version: u32,
204    /// The remote conversation identifier.
205    pub thread_id: ThreadId,
206    /// Materialized conversation.
207    pub messages: Vec<Message>,
208    /// Current raw shared state.
209    pub state: Value,
210    /// Materialized reasoning, separate from the conversation.
211    pub reasoning: Vec<ReasoningMessage>,
212    /// Announced subagent lifecycle state.
213    pub subagents: Vec<Subagent>,
214    /// Questions which have not been confirmed as answered.
215    pub interrupts: Vec<Interrupt>,
216    /// A submitted decision whose acceptance has not been confirmed.
217    pub submission: Option<ResumeSubmission>,
218    /// Previously dispatched local run IDs, used to prevent reuse.
219    pub run_ids: Vec<RunId>,
220    /// The last locally observed termination, if any.
221    pub last_run_end: Option<RunEnd>,
222    /// A dispatched local run which had not ended when this snapshot was taken.
223    pub active_run_id: Option<RunId>,
224}
225
226/// One local conversation with an agent. `T` only supplies communication.
227/// `S` is the current state view, defaulting to JSON.
228pub struct Thread<T, S = Value> {
229    agent: RemoteAgent<Arc<T>>,
230    thread_id: ThreadId,
231    applier: Applier,
232    state: core::result::Result<S, StateViewError>,
233    tools: Vec<Tool>,
234    context: Vec<Context>,
235    forwarded_props: Value,
236    verify: bool,
237    interrupts: Vec<Interrupt>,
238    submission: Option<ResumeSubmission>,
239    run_ids: HashSet<RunId>,
240    next_run_id: Option<RunId>,
241    last_run_end: Option<RunEnd>,
242    active_run_id: Option<RunId>,
243    observer: Option<Observer>,
244    id_generator: IdGenerator,
245    diagnostic_limit: usize,
246}
247
248impl<T, S: std::fmt::Debug> std::fmt::Debug for Thread<T, S> {
249    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        f.debug_struct("Thread")
251            .field("thread_id", &self.thread_id)
252            .field("state", &self.state)
253            .field("messages", &self.messages())
254            .field("interrupts", &self.interrupts)
255            .finish_non_exhaustive()
256    }
257}
258
259impl<T: Transport> Thread<T> {
260    /// Creates an empty JSON conversation. No request is sent.
261    pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self {
262        Self::from_shared(Arc::new(transport), thread_id)
263    }
264
265    pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
266        ThreadBuilder::from_shared(transport, thread_id)
267            .build()
268            .expect("an empty JSON object always deserializes to Value")
269    }
270}
271
272impl<T, S> Thread<T, S> {
273    /// Configures a conversation and validates its initial typed state at `build`.
274    pub fn builder(transport: T, thread_id: impl Into<ThreadId>) -> ThreadBuilder<T, S>
275    where
276        T: Transport,
277    {
278        ThreadBuilder::new(transport, thread_id)
279    }
280    /// The remote conversation identifier.
281    pub fn thread_id(&self) -> &ThreadId {
282        &self.thread_id
283    }
284    /// The current assembled conversation.
285    pub fn messages(&self) -> &[Message] {
286        self.applier.messages()
287    }
288    /// The current typed view. A remote type mismatch invalidates the old view.
289    pub fn state(&self) -> core::result::Result<&S, StateViewError> {
290        self.state.as_ref().map_err(Clone::clone)
291    }
292    /// The latest raw state, even when it does not fit `S`.
293    pub fn raw_state(&self) -> &Value {
294        self.applier.state()
295    }
296    /// Materialized reasoning, separate from the conversation.
297    pub fn reasoning(&self) -> &[ReasoningMessage] {
298        self.applier.reasoning()
299    }
300    /// Pending human input. Dispatching a response does not remove it.
301    pub fn interrupts(&self) -> &[Interrupt] {
302        &self.interrupts
303    }
304    /// Unconfirmed or currently in-flight response submission.
305    pub fn submission(&self) -> Option<&ResumeSubmission> {
306        self.submission.as_ref()
307    }
308    /// Announced subagents across runs.
309    pub fn subagents(&self) -> &[Subagent] {
310        self.applier.subagents()
311    }
312    /// Find a subagent by invocation ID.
313    pub fn subagent(&self, id: &crate::SubagentRunId) -> Option<&Subagent> {
314        self.applier.subagent(id)
315    }
316    /// The current materialized protocol data.
317    pub fn applier(&self) -> &Applier {
318        &self.applier
319    }
320    /// The low-level agent using the same owned transport handle.
321    pub fn agent(&self) -> &RemoteAgent<Arc<T>> {
322        &self.agent
323    }
324    /// The last observed termination. Dropping a dispatched run records `Aborted`.
325    pub fn last_run_end(&self) -> Option<&RunEnd> {
326        self.last_run_end.as_ref()
327    }
328    /// Append a client-owned message, rejecting an ID already in the transcript.
329    pub fn push_message(&mut self, message: Message) -> Result<()> {
330        if self.applier.message(message.id()).is_some() {
331            return Err(Error::Request(format!(
332                "duplicate message ID {}",
333                message.id()
334            )));
335        }
336        self.applier.push_message(message);
337        Ok(())
338    }
339    /// Tools offered on subsequent runs. AG-UI does not discover tools.
340    pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>) {
341        self.tools = tools.into();
342    }
343    /// Context sent on subsequent runs.
344    pub fn set_context(&mut self, context: impl Into<Vec<Context>>) {
345        self.context = context.into();
346    }
347    /// Passthrough request properties supplied by the application.
348    pub fn set_forwarded_props(&mut self, props: impl Into<Value>) {
349        self.forwarded_props = props.into();
350    }
351    /// Configure protocol ordering verification. Identity and resume safety checks stay enabled.
352    pub fn set_verify(&mut self, verify: bool) {
353        self.verify = verify;
354    }
355    /// Retained diagnostics per run. Excess errors are still yielded as updates.
356    pub fn set_diagnostic_limit(&mut self, limit: usize) {
357        self.diagnostic_limit = limit;
358    }
359    /// Reserve an explicit run ID. Reuse is rejected during request preflight.
360    pub fn set_next_run_id(&mut self, id: impl Into<RunId>) {
361        self.next_run_id = Some(id.into());
362    }
363    /// Remove the event observer.
364    pub fn clear_event_observer(&mut self) {
365        self.observer = None;
366    }
367
368    /// Replace the synchronous read-only observer. Called once per decoded event,
369    /// before normalization and validation. Queue slow work in the application.
370    #[cfg(not(target_family = "wasm"))]
371    pub fn on_event(&mut self, observer: impl FnMut(&Event) + Send + 'static) {
372        self.observer = Some(Box::new(observer));
373    }
374    /// Replace the local read-only observer on wasm.
375    #[cfg(target_family = "wasm")]
376    pub fn on_event(&mut self, observer: impl FnMut(&Event) + 'static) {
377        self.observer = Some(Box::new(observer));
378    }
379
380    /// Save local conversation data. Transport settings and callbacks are excluded.
381    pub fn snapshot(&self) -> ThreadSnapshot {
382        let mut run_ids: Vec<_> = self.run_ids.iter().cloned().collect();
383        run_ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
384        ThreadSnapshot {
385            version: 1,
386            thread_id: self.thread_id.clone(),
387            messages: self.messages().to_vec(),
388            state: self.raw_state().clone(),
389            reasoning: self.reasoning().to_vec(),
390            subagents: self.subagents().to_vec(),
391            interrupts: self.interrupts.clone(),
392            submission: self.submission.clone(),
393            run_ids,
394            last_run_end: self.last_run_end.clone(),
395            active_run_id: self.active_run_id.clone(),
396        }
397    }
398
399    fn unconfirm(&mut self) {
400        if let Some(submission) = &mut self.submission {
401            submission.status = SubmissionStatus::Unconfirmed;
402        }
403    }
404}
405
406impl<T, S: DeserializeOwned> Thread<T, S> {
407    /// Validates local JSON before atomically replacing both raw and typed state.
408    pub fn set_state(&mut self, state: impl Into<Value>) -> Result<()> {
409        let state = state.into();
410        let typed = S::deserialize(&state).map_err(Error::State)?;
411        self.applier.set_state(state);
412        self.state = Ok(typed);
413        Ok(())
414    }
415
416    /// Restore local state using a new transport. No server query is performed.
417    pub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>
418    where
419        T: Transport,
420    {
421        Self::restore_shared(Arc::new(transport), snapshot)
422    }
423
424    pub(crate) fn restore_shared(transport: Arc<T>, mut snapshot: ThreadSnapshot) -> Result<Self> {
425        validate_snapshot(&snapshot)?;
426        if snapshot.active_run_id.take().is_some() {
427            snapshot.last_run_end = Some(RunEnd::Aborted);
428        }
429        let typed = S::deserialize(&snapshot.state).map_err(Error::State)?;
430        if let Some(submission) = &mut snapshot.submission {
431            submission.status = SubmissionStatus::Unconfirmed;
432        }
433        for subagent in &mut snapshot.subagents {
434            if subagent.status == crate::client::SubagentStatus::Running {
435                subagent.status = crate::client::SubagentStatus::Aborted;
436            }
437        }
438        let mut applier = Applier::new()
439            .with_messages(snapshot.messages)
440            .with_state(snapshot.state);
441        applier.restore_auxiliary(
442            snapshot.reasoning,
443            snapshot.subagents,
444            snapshot.interrupts.clone(),
445        );
446        Ok(Self {
447            agent: RemoteAgent::new(transport),
448            thread_id: snapshot.thread_id,
449            applier,
450            state: Ok(typed),
451            tools: Vec::new(),
452            context: Vec::new(),
453            forwarded_props: Value::Null,
454            verify: true,
455            interrupts: snapshot.interrupts,
456            submission: snapshot.submission,
457            run_ids: snapshot.run_ids.into_iter().collect(),
458            next_run_id: None,
459            last_run_end: snapshot.last_run_end,
460            active_run_id: None,
461            observer: None,
462            id_generator: Box::new(random_id),
463            diagnostic_limit: 100,
464        })
465    }
466}
467
468impl<T: Transport, S> Thread<T, S> {
469    /// Prepare a user turn. Pending decisions and ambiguous submissions are checked
470    /// before changing history. Dispatch and history insertion occur on first poll.
471    pub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>> {
472        self.preflight(None)?;
473        let id = self.fresh_id(false)?;
474        self.start(Some(Message::user(id, text.into())), None)
475    }
476    /// Prepare a message of any role, rejecting existing IDs.
477    pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>> {
478        self.preflight(None)?;
479        if self.applier.message(message.id()).is_some() {
480            return Err(Error::Request(format!(
481                "duplicate message ID {}",
482                message.id()
483            )));
484        }
485        self.start(Some(message), None)
486    }
487    /// Prepare a run with the existing conversation and no new message.
488    pub fn run(&mut self) -> Result<RunStream<'_, T, S>> {
489        self.preflight(None)?;
490        self.start(None, None)
491    }
492    /// Answer the single outstanding interrupt. All pending IDs must be answered.
493    pub fn resume(
494        &mut self,
495        interrupt: &Interrupt,
496        payload: impl Into<Value>,
497    ) -> Result<RunStream<'_, T, S>> {
498        self.resume_many([interrupt.resolve(payload)])
499    }
500    /// Decline the single outstanding interrupt. This is not execution cancellation.
501    pub fn decline(&mut self, interrupt: &Interrupt) -> Result<RunStream<'_, T, S>> {
502        self.resume_many([interrupt.cancel()])
503    }
504    /// Answer every pending question exactly once. Expiry is checked against the
505    /// stored interrupt. Response schemas are retained for the application/server
506    /// to validate; this transport-neutral API does not execute arbitrary schemas.
507    pub fn resume_many(
508        &mut self,
509        entries: impl IntoIterator<Item = ResumeEntry>,
510    ) -> Result<RunStream<'_, T, S>> {
511        let entries: Vec<_> = entries.into_iter().collect();
512        self.preflight(Some(&entries))?;
513        self.start(None, Some(entries))
514    }
515    fn preflight(&self, resume: Option<&[ResumeEntry]>) -> Result<()> {
516        if self.thread_id.as_str().is_empty() {
517            return Err(Error::Request("thread ID must not be empty".into()));
518        }
519        if self.submission.is_some() {
520            return Err(Error::Request("an unconfirmed submission requires reconciliation with server state before another run".into()));
521        }
522        if let Some(id) = &self.next_run_id {
523            if id.as_str().is_empty() || self.run_ids.contains(id) {
524                return Err(Error::Request(format!(
525                    "run ID {id} is empty or already used"
526                )));
527            }
528        }
529        match resume {
530            None if !self.interrupts.is_empty() => Err(Error::Request(
531                "pending interrupts must be answered with resume_many".into(),
532            )),
533            Some(entries) => validate_responses(&self.interrupts, entries, true),
534            None => Ok(()),
535        }
536    }
537    fn fresh_id(&mut self, run: bool) -> Result<String> {
538        for _ in 0..64 {
539            let id = (self.id_generator)()?;
540            let exists = if run {
541                self.run_ids.contains(&RunId::new(&id))
542            } else {
543                self.applier.message(&MessageId::new(&id)).is_some()
544            };
545            if !id.is_empty() && !exists {
546                return Ok(id);
547            }
548        }
549        Err(Error::Request(
550            "ID generator repeatedly returned empty or existing IDs".into(),
551        ))
552    }
553    fn start(
554        &mut self,
555        message: Option<Message>,
556        resume: Option<Vec<ResumeEntry>>,
557    ) -> Result<RunStream<'_, T, S>> {
558        let run_id = match &self.next_run_id {
559            Some(id) => id.clone(),
560            None => RunId::new(self.fresh_id(true)?),
561        };
562        let initial_ids = self
563            .messages()
564            .iter()
565            .map(|message| message.id().clone())
566            .collect();
567        // Activity messages describe local renderer state. Like the reference
568        // client, retain them in the thread but omit them from agent requests.
569        let messages = self
570            .messages()
571            .iter()
572            .chain(message.iter())
573            .filter(|message| !matches!(message, Message::Activity(_)))
574            .cloned()
575            .collect();
576        let input = RunAgentInput {
577            thread_id: self.thread_id.clone(),
578            run_id,
579            parent_run_id: None,
580            state: self.raw_state().clone(),
581            messages,
582            tools: self.tools.clone(),
583            context: self.context.clone(),
584            forwarded_props: self.forwarded_props.clone(),
585            resume,
586        };
587        let verifier = self.verify.then(Verifier::new);
588        let request_run_id = input.run_id.clone();
589        Ok(RunStream {
590            request_run_id,
591            thread: self,
592            prepared: Some((input, message)),
593            events: None,
594            normalizer: ChunkNormalizer::new(),
595            verifier,
596            expanded: Vec::new(),
597            ready: VecDeque::new(),
598            done: false,
599            dispatched: false,
600            abort: AbortHandle::default(),
601            end: None,
602            diagnostics: Vec::new(),
603            diagnostics_omitted: 0,
604            initial_ids,
605            response_ids: None,
606        })
607    }
608}
609
610/// Configures a thread. `build` checks history IDs and typed initial state.
611pub struct ThreadBuilder<T, S = Value> {
612    transport: Arc<T>,
613    thread_id: ThreadId,
614    messages: Vec<Message>,
615    state: Value,
616    tools: Vec<Tool>,
617    context: Vec<Context>,
618    forwarded_props: Value,
619    verify: bool,
620    diagnostic_limit: usize,
621    id_generator: IdGenerator,
622    marker: std::marker::PhantomData<fn() -> S>,
623}
624impl<T, S> std::fmt::Debug for ThreadBuilder<T, S> {
625    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
626        f.debug_struct("ThreadBuilder")
627            .field("thread_id", &self.thread_id)
628            .finish_non_exhaustive()
629    }
630}
631impl<T, S> ThreadBuilder<T, S> {
632    /// Configure a thread using any transport.
633    pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self
634    where
635        T: Transport,
636    {
637        Self::from_shared(Arc::new(transport), thread_id)
638    }
639    pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
640        Self {
641            transport,
642            thread_id: thread_id.into(),
643            messages: Vec::new(),
644            state: serde_json::json!({}),
645            tools: Vec::new(),
646            context: Vec::new(),
647            forwarded_props: Value::Null,
648            verify: true,
649            diagnostic_limit: 100,
650            id_generator: Box::new(random_id),
651            marker: std::marker::PhantomData,
652        }
653    }
654    /// Existing conversation, checked for duplicate IDs at build time.
655    #[must_use]
656    pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
657        self.messages = messages.into();
658        self
659    }
660    /// Initial JSON, deserialized to `S` at build time.
661    #[must_use]
662    pub fn state(mut self, state: impl Into<Value>) -> Self {
663        self.state = state.into();
664        self
665    }
666    /// Tools offered on each run.
667    #[must_use]
668    pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
669        self.tools = tools.into();
670        self
671    }
672    /// Ambient context supplied on each run.
673    #[must_use]
674    pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
675        self.context = context.into();
676        self
677    }
678    /// Application-specific request properties.
679    #[must_use]
680    pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
681        self.forwarded_props = props.into();
682        self
683    }
684    /// Toggle optional protocol ordering verification.
685    #[must_use]
686    pub fn verify(mut self, verify: bool) -> Self {
687        self.verify = verify;
688        self
689    }
690    /// Maximum diagnostics retained in each report (default 100).
691    #[must_use]
692    pub fn diagnostic_limit(mut self, limit: usize) -> Self {
693        self.diagnostic_limit = limit;
694        self
695    }
696    /// Inject deterministic IDs for tests. Empty or duplicate IDs are retried up to 64 times.
697    #[cfg(not(target_family = "wasm"))]
698    #[must_use]
699    pub fn id_generator(mut self, mut generator: impl FnMut() -> String + Send + 'static) -> Self {
700        self.id_generator = Box::new(move || Ok(generator()));
701        self
702    }
703    /// Inject a local deterministic ID generator on wasm.
704    #[cfg(target_family = "wasm")]
705    #[must_use]
706    pub fn id_generator(mut self, mut generator: impl FnMut() -> String + 'static) -> Self {
707        self.id_generator = Box::new(move || Ok(generator()));
708        self
709    }
710    /// Validate state and history, then construct the conversation.
711    pub fn build(self) -> Result<Thread<T, S>>
712    where
713        S: DeserializeOwned,
714    {
715        unique(
716            self.messages.iter().map(|message| message.id().as_str()),
717            "message",
718        )?;
719        let state = S::deserialize(&self.state).map_err(Error::State)?;
720        Ok(Thread {
721            agent: RemoteAgent::new(self.transport),
722            thread_id: self.thread_id,
723            applier: Applier::new()
724                .with_messages(self.messages)
725                .with_state(self.state),
726            state: Ok(state),
727            tools: self.tools,
728            context: self.context,
729            forwarded_props: self.forwarded_props,
730            verify: self.verify,
731            interrupts: Vec::new(),
732            submission: None,
733            run_ids: HashSet::new(),
734            next_run_id: None,
735            last_run_end: None,
736            active_run_id: None,
737            observer: None,
738            id_generator: self.id_generator,
739            diagnostic_limit: self.diagnostic_limit,
740        })
741    }
742}
743
744#[derive(Default)]
745struct AbortState {
746    aborted: AtomicBool,
747    waker: AtomicWaker,
748}
749/// Cloneable cancellation for one local run. Wakes a pending poll and drops its
750/// connection/response stream. It does not confirm remote cancellation.
751#[derive(Clone, Default)]
752pub struct AbortHandle {
753    state: Arc<AbortState>,
754}
755impl std::fmt::Debug for AbortHandle {
756    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
757        f.debug_struct("AbortHandle")
758            .field("aborted", &self.is_aborted())
759            .finish()
760    }
761}
762impl AbortHandle {
763    /// Request local cancellation and wake its consumer.
764    pub fn abort(&self) {
765        self.state.aborted.store(true, Ordering::Release);
766        self.state.waker.wake();
767    }
768    /// Whether cancellation was requested.
769    pub fn is_aborted(&self) -> bool {
770        self.state.aborted.load(Ordering::Acquire)
771    }
772}
773
774/// A lazily dispatched run. It borrows the thread until dropped. Every consumed
775/// run yields one `Done`; dropping an unpolled run leaves the thread unchanged.
776pub struct RunStream<'a, T, S = Value> {
777    thread: &'a mut Thread<T, S>,
778    prepared: Option<(RunAgentInput, Option<Message>)>,
779    events: Option<EventStream>,
780    normalizer: ChunkNormalizer,
781    verifier: Option<Verifier>,
782    expanded: Vec<Event>,
783    ready: VecDeque<Update<S>>,
784    done: bool,
785    dispatched: bool,
786    abort: AbortHandle,
787    end: Option<RunEnd>,
788    diagnostics: Vec<RunDiagnostic>,
789    diagnostics_omitted: usize,
790    initial_ids: HashSet<MessageId>,
791    response_ids: Option<(ThreadId, RunId)>,
792    request_run_id: RunId,
793}
794impl<T, S> std::fmt::Debug for RunStream<'_, T, S> {
795    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
796        f.debug_struct("RunStream")
797            .field("pending", &self.ready.len())
798            .field("dispatched", &self.dispatched)
799            .field("done", &self.done)
800            .finish_non_exhaustive()
801    }
802}
803impl<T, S> RunStream<'_, T, S> {
804    /// Read-only materialized conversation while the run is borrowed.
805    pub fn thread(&self) -> &Thread<T, S> {
806        self.thread
807    }
808    /// A handle that cancels this run only.
809    pub fn abort_handle(&self) -> AbortHandle {
810        self.abort.clone()
811    }
812    /// Interrupt consumption locally.
813    pub fn abort(&self) {
814        self.abort.abort();
815    }
816    fn diagnostic(&mut self, error: Error) {
817        if self.diagnostics.len() < self.thread.diagnostic_limit {
818            let kind = match &error {
819                Error::State(_) => "state",
820                Error::Protocol(_) => "protocol",
821                Error::Patch { .. } => "patch",
822                Error::Run { .. } => "run",
823                Error::Json(_) | Error::Decode(_) => "decode",
824                _ => "transport",
825            };
826            self.diagnostics.push(RunDiagnostic {
827                kind,
828                message: error.to_string(),
829            });
830        } else {
831            self.diagnostics_omitted += 1;
832        }
833        self.ready.push_back(Update::Error(error));
834    }
835    fn terminate(&mut self, end: RunEnd) {
836        if self.done {
837            return;
838        }
839        self.done = true;
840        self.events = None;
841        self.prepared = None;
842        self.thread.applier.reset_streams();
843        if self.dispatched {
844            self.thread.last_run_end = Some(end.clone());
845            self.thread.active_run_id = None;
846        }
847        self.end = Some(end.clone());
848        self.ready.push_back(Update::Done(end));
849    }
850    fn stop_subagents(&mut self) {
851        let (messages, reasoning) = self.thread.applier.abort_messages();
852        for change in messages {
853            if let Some(message) = self.thread.applier.messages().get(change.index) {
854                self.ready.push_back(Update::Message(MessageUpdate {
855                    index: change.index,
856                    id: change.id,
857                    change: change.kind,
858                    message: message.clone(),
859                }));
860            }
861        }
862        for change in reasoning {
863            let text = self
864                .thread
865                .applier
866                .reasoning_text(&change.id)
867                .unwrap_or_default()
868                .to_owned();
869            self.ready.push_back(Update::Reasoning(ReasoningUpdate {
870                id: change.id,
871                change: change.kind,
872                text,
873            }));
874        }
875        for change in self.thread.applier.abort_subagents() {
876            let subagent = self.thread.applier.subagents()[change.index].clone();
877            self.ready.push_back(Update::Subagent(SubagentUpdate {
878                index: change.index,
879                run_id: change.run_id,
880                change: change.kind,
881                subagent,
882            }));
883        }
884    }
885    fn fail(&mut self, error: Error) {
886        let message = error.to_string();
887        self.diagnostic(error);
888        self.thread.unconfirm();
889        self.stop_subagents();
890        self.terminate(RunEnd::Failed {
891            message,
892            code: None,
893        });
894    }
895}
896impl<T, S> Drop for RunStream<'_, T, S> {
897    fn drop(&mut self) {
898        if self.dispatched && !self.done {
899            self.thread.unconfirm();
900            self.thread.applier.abort_subagents();
901            self.thread.last_run_end = Some(RunEnd::Aborted);
902            self.thread.active_run_id = None;
903        }
904    }
905}
906
907impl<T: Transport, S: DeserializeOwned + Clone + Unpin> RunStream<'_, T, S> {
908    /// Consume the remainder and return the entire run's outcome and diagnostics.
909    pub async fn collect_report(mut self) -> RunReport {
910        while self.next().await.is_some() {}
911        RunReport {
912            end: self
913                .end
914                .clone()
915                .expect("a consumed stream has a terminal outcome"),
916            new_messages: self
917                .thread
918                .messages()
919                .iter()
920                .filter(|message| !self.initial_ids.contains(message.id()))
921                .cloned()
922                .collect(),
923            diagnostics: std::mem::take(&mut self.diagnostics),
924            diagnostics_omitted: self.diagnostics_omitted,
925        }
926    }
927}
928
929impl<T, S: DeserializeOwned + Clone> RunStream<'_, T, S> {
930    fn ingest(&mut self, event: Event) {
931        if let Some(observer) = &mut self.thread.observer {
932            observer(&event);
933        }
934        if matches!(event, Event::RunError(_)) {
935            self.handle(event);
936            return;
937        }
938        let mut expanded = std::mem::take(&mut self.expanded);
939        expanded.clear();
940        let result = self.normalizer.normalize(event, &mut expanded);
941        for event in expanded.drain(..) {
942            if !self.done {
943                self.handle(event);
944            }
945        }
946        self.expanded = expanded;
947        if let Err(error) = result {
948            self.diagnostic(error);
949        }
950    }
951    fn handle(&mut self, event: Event) {
952        // Pair the terminal with the stream's announced run even when optional
953        // ordering verification is disabled. Run errors carry no IDs.
954        match &event {
955            Event::RunStarted(started) => {
956                if started.thread_id != self.thread.thread_id
957                    || started.run_id != self.request_run_id
958                {
959                    self.fail(Error::protocol(
960                        "RUN_STARTED does not match the requested thread and run IDs",
961                    ));
962                    return;
963                }
964                self.response_ids = Some((started.thread_id.clone(), started.run_id.clone()));
965            }
966            Event::RunFinished(finished) => {
967                if self.response_ids.as_ref()
968                    != Some(&(finished.thread_id.clone(), finished.run_id.clone()))
969                {
970                    self.fail(Error::protocol("RUN_FINISHED does not match RUN_STARTED"));
971                    return;
972                }
973                if let Some(RunOutcome::Interrupt { interrupts }) = &finished.outcome {
974                    if let Err(error) =
975                        unique(interrupts.iter().map(|i| i.id.as_str()), "interrupt")
976                    {
977                        self.fail(Error::protocol(error.to_string()));
978                        return;
979                    }
980                }
981            }
982            _ => {}
983        }
984        if let Some(verifier) = &mut self.verifier {
985            if let Err(error) = verifier.verify(&event) {
986                if matches!(event, Event::RunFinished(_) | Event::RunError(_)) {
987                    self.fail(error);
988                } else {
989                    self.diagnostic(error);
990                }
991                return;
992            }
993        }
994        match self.thread.applier.apply(&event) {
995            Ok(changed) => self.emit(changed),
996            Err(error) if matches!(event, Event::RunFinished(_) | Event::RunError(_)) => {
997                self.fail(error)
998            }
999            Err(error) => self.diagnostic(error),
1000        }
1001    }
1002    fn emit(&mut self, changed: Changed) {
1003        match changed {
1004            Changed::Nothing | Changed::RunStarted { .. } => {}
1005            Changed::Message(change) => {
1006                if let Some(message) = self.thread.applier.messages().get(change.index) {
1007                    self.ready.push_back(Update::Message(MessageUpdate {
1008                        index: change.index,
1009                        id: change.id,
1010                        change: change.kind,
1011                        message: message.clone(),
1012                    }));
1013                }
1014            }
1015            Changed::MessagesReplaced => self
1016                .ready
1017                .push_back(Update::Messages(self.thread.messages().to_vec())),
1018            Changed::State => match self.thread.applier.state_as::<S>() {
1019                Ok(state) => {
1020                    self.thread.state = Ok(state.clone());
1021                    self.ready.push_back(Update::State(state));
1022                }
1023                Err(error) => {
1024                    self.thread.state = Err(StateViewError {
1025                        message: match &error {
1026                            Error::State(error) => error.to_string(),
1027                            _ => error.to_string(),
1028                        },
1029                    });
1030                    self.diagnostic(error);
1031                }
1032            },
1033            Changed::Reasoning(change) => {
1034                let text = self
1035                    .thread
1036                    .applier
1037                    .reasoning_text(&change.id)
1038                    .unwrap_or_default()
1039                    .to_owned();
1040                self.ready.push_back(Update::Reasoning(ReasoningUpdate {
1041                    id: change.id,
1042                    change: change.kind,
1043                    text,
1044                }));
1045            }
1046            Changed::Subagent(change) => {
1047                if let Some(subagent) = self.thread.applier.subagents().get(change.index) {
1048                    self.ready.push_back(Update::Subagent(SubagentUpdate {
1049                        index: change.index,
1050                        run_id: change.run_id,
1051                        change: change.kind,
1052                        subagent: subagent.clone(),
1053                    }));
1054                }
1055            }
1056            Changed::RunFinished { outcome, result } => {
1057                self.thread.submission = None;
1058                match outcome {
1059                    RunOutcome::Success => {
1060                        self.thread.interrupts.clear();
1061                        self.terminate(RunEnd::Success { result });
1062                    }
1063                    RunOutcome::Interrupt { interrupts } => {
1064                        self.thread.interrupts.clone_from(&interrupts);
1065                        for interrupt in &interrupts {
1066                            self.ready.push_back(Update::Interrupt(interrupt.clone()));
1067                        }
1068                        self.terminate(RunEnd::Interrupted { interrupts });
1069                    }
1070                }
1071            }
1072            Changed::RunError { message, code } => {
1073                self.diagnostic(Error::Run {
1074                    message: message.clone(),
1075                    code: code.clone(),
1076                });
1077                self.thread.unconfirm();
1078                self.stop_subagents();
1079                self.terminate(RunEnd::Failed { message, code });
1080            }
1081        }
1082    }
1083}
1084
1085impl<T: Transport, S: DeserializeOwned + Clone + Unpin> Stream for RunStream<'_, T, S> {
1086    type Item = Update<S>;
1087    fn poll_next(self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> {
1088        let this = self.get_mut();
1089        this.abort.state.waker.register(cx.waker());
1090        loop {
1091            // A terminal already applied wins over a later abort.
1092            if !this.done && this.abort.is_aborted() {
1093                if this.dispatched {
1094                    this.thread.unconfirm();
1095                    this.stop_subagents();
1096                }
1097                this.terminate(RunEnd::Aborted);
1098            }
1099            if let Some(update) = this.ready.pop_front() {
1100                return Poll::Ready(Some(update));
1101            }
1102            if this.done {
1103                return Poll::Ready(None);
1104            }
1105            if let Some((input, message)) = this.prepared.take() {
1106                // Expiry may have passed while the prepared stream sat unpolled.
1107                if let Some(entries) = &input.resume {
1108                    if let Err(error) = validate_responses(&this.thread.interrupts, entries, true) {
1109                        this.fail(error);
1110                        continue;
1111                    }
1112                }
1113                this.dispatched = true;
1114                this.thread.applier.reset_streams();
1115                this.thread.run_ids.insert(input.run_id.clone());
1116                this.thread.active_run_id = Some(input.run_id.clone());
1117                this.thread.next_run_id = None;
1118                if let Some(message) = message {
1119                    this.thread.applier.push_message(message);
1120                }
1121                if let Some(entries) = &input.resume {
1122                    this.thread.submission = Some(ResumeSubmission {
1123                        run_id: input.run_id.clone(),
1124                        entries: entries.clone(),
1125                        status: SubmissionStatus::InFlight,
1126                    });
1127                }
1128                this.events = Some(this.thread.agent.run_events(input));
1129            }
1130            match this
1131                .events
1132                .as_mut()
1133                .expect("dispatched run has a stream")
1134                .as_mut()
1135                .poll_next(cx)
1136            {
1137                Poll::Pending => return Poll::Pending,
1138                Poll::Ready(Some(Ok(event))) => this.ingest(event),
1139                Poll::Ready(Some(Err(error))) => this.fail(error),
1140                Poll::Ready(None) => {
1141                    let error = this
1142                        .verifier
1143                        .as_ref()
1144                        .and_then(|verifier| verifier.finish().err())
1145                        .unwrap_or_else(|| {
1146                            Error::protocol("the stream ended before RUN_FINISHED or RUN_ERROR")
1147                        });
1148                    this.fail(error);
1149                }
1150            }
1151        }
1152    }
1153}
1154
1155fn random_id() -> Result<String> {
1156    let mut bytes = [0u8; 16];
1157    getrandom::getrandom(&mut bytes)
1158        .map_err(|error| Error::Config(format!("could not obtain ID entropy: {error}")))?;
1159    use std::fmt::Write;
1160    let mut id = String::with_capacity(32);
1161    for byte in bytes {
1162        write!(id, "{byte:02x}").expect("writing to String cannot fail");
1163    }
1164    Ok(id)
1165}
1166
1167fn unique<'a>(ids: impl IntoIterator<Item = &'a str>, label: &str) -> Result<()> {
1168    let mut seen = HashSet::new();
1169    for id in ids {
1170        if id.is_empty() || !seen.insert(id) {
1171            return Err(Error::Snapshot(format!(
1172                "{label} ID {id:?} is empty or duplicated"
1173            )));
1174        }
1175    }
1176    Ok(())
1177}
1178
1179fn validate_responses(pending: &[Interrupt], entries: &[ResumeEntry], expiry: bool) -> Result<()> {
1180    if pending.is_empty() {
1181        return Err(Error::Request("there are no pending interrupts".into()));
1182    }
1183    let mut seen = HashSet::new();
1184    for entry in entries {
1185        if !seen.insert(&entry.interrupt_id) {
1186            return Err(Error::Request(format!(
1187                "duplicate interrupt ID {}",
1188                entry.interrupt_id
1189            )));
1190        }
1191        let interrupt = pending
1192            .iter()
1193            .find(|interrupt| interrupt.id == entry.interrupt_id)
1194            .ok_or_else(|| {
1195                Error::Request(format!("unknown interrupt ID {}", entry.interrupt_id))
1196            })?;
1197        if expiry {
1198            if let Some(timestamp) = &interrupt.expires_at {
1199                let expires = chrono::DateTime::parse_from_rfc3339(timestamp).map_err(|_| {
1200                    Error::Request(format!(
1201                        "interrupt {} has an invalid expiry timestamp",
1202                        interrupt.id
1203                    ))
1204                })?;
1205                // RFC 3339 leap seconds can only end a UTC month.
1206                if expires.timestamp_subsec_nanos() >= 1_000_000_000 {
1207                    let utc_date = expires.naive_utc().date();
1208                    let ends_month = utc_date
1209                        .succ_opt()
1210                        .is_some_and(|next| chrono::Datelike::day(&next) == 1);
1211                    if expires.timestamp().rem_euclid(86_400) != 86_399 || !ends_month {
1212                        return Err(Error::Request(format!(
1213                            "interrupt {} has an invalid expiry timestamp",
1214                            interrupt.id
1215                        )));
1216                    }
1217                }
1218                // Preserve the previous parser's leap-second clamp and full year range.
1219                let expires_nanos = i128::from(expires.timestamp()) * 1_000_000_000
1220                    + i128::from(expires.timestamp_subsec_nanos().min(999_999_999));
1221                if expires_nanos <= now_unix_nanos() {
1222                    return Err(Error::Request(format!(
1223                        "interrupt {} has expired",
1224                        interrupt.id
1225                    )));
1226                }
1227            }
1228        }
1229    }
1230    if seen.len() != pending.len() {
1231        return Err(Error::Request(
1232            "every pending interrupt must be answered exactly once".into(),
1233        ));
1234    }
1235    Ok(())
1236}
1237
1238fn validate_snapshot(snapshot: &ThreadSnapshot) -> Result<()> {
1239    if snapshot.version != 1 {
1240        return Err(Error::Snapshot(format!(
1241            "unsupported version {}",
1242            snapshot.version
1243        )));
1244    }
1245    if snapshot.thread_id.as_str().is_empty() {
1246        return Err(Error::Snapshot("empty thread ID".into()));
1247    }
1248    unique(
1249        snapshot
1250            .messages
1251            .iter()
1252            .map(|message| message.id().as_str()),
1253        "message",
1254    )?;
1255    unique(
1256        snapshot.reasoning.iter().map(|message| message.id.as_str()),
1257        "reasoning",
1258    )?;
1259    unique(
1260        snapshot
1261            .subagents
1262            .iter()
1263            .map(|subagent| subagent.run_id.as_str()),
1264        "subagent",
1265    )?;
1266    unique(
1267        snapshot
1268            .interrupts
1269            .iter()
1270            .map(|interrupt| interrupt.id.as_str()),
1271        "interrupt",
1272    )?;
1273    unique(snapshot.run_ids.iter().map(|id| id.as_str()), "run")?;
1274    if let Some(id) = &snapshot.active_run_id {
1275        if !snapshot.run_ids.contains(id) {
1276            return Err(Error::Snapshot(
1277                "active run refers to an unknown run ID".into(),
1278            ));
1279        }
1280    }
1281    for subagent in &snapshot.subagents {
1282        let mut seen = HashSet::from([subagent.run_id.as_str()]);
1283        let mut parent = subagent.parent_subagent_run_id.as_ref();
1284        while let Some(id) = parent {
1285            if !seen.insert(id.as_str()) {
1286                return Err(Error::Snapshot("cyclic subagent ancestry".into()));
1287            }
1288            let ancestor = snapshot
1289                .subagents
1290                .iter()
1291                .find(|subagent| &subagent.run_id == id)
1292                .ok_or_else(|| Error::Snapshot(format!("unknown parent subagent {id}")))?;
1293            parent = ancestor.parent_subagent_run_id.as_ref();
1294        }
1295    }
1296    if let Some(submission) = &snapshot.submission {
1297        if submission.status == SubmissionStatus::InFlight
1298            && snapshot.active_run_id.as_ref() != Some(&submission.run_id)
1299        {
1300            return Err(Error::Snapshot(
1301                "in-flight submission must reference the active run".into(),
1302            ));
1303        }
1304        if !snapshot.run_ids.contains(&submission.run_id) {
1305            return Err(Error::Snapshot(
1306                "submission refers to an unknown run ID".into(),
1307            ));
1308        }
1309        validate_responses(&snapshot.interrupts, &submission.entries, false)
1310            .map_err(|error| Error::Snapshot(error.to_string()))?;
1311    }
1312    Ok(())
1313}
1314
1315#[cfg(not(target_family = "wasm"))]
1316fn now_unix_nanos() -> i128 {
1317    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
1318        Ok(elapsed) => elapsed.as_nanos() as i128,
1319        Err(error) => -(error.duration().as_nanos() as i128),
1320    }
1321}
1322#[cfg(target_family = "wasm")]
1323fn now_unix_nanos() -> i128 {
1324    (js_sys::Date::now() * 1_000_000.0) as i128
1325}