Skip to main content

ag_ui/client/thread/
pending.rs

1//! What a conversation owes before another run: an answer to each interrupt
2//! it is paused on, a submission the server has not confirmed, and a result
3//! for each tool call nothing answered.
4
5use std::collections::HashSet;
6
7use crate::client::{
8    error::{Error, Result},
9    interrupts::InterruptExt,
10    transport::Transport,
11};
12use crate::{
13    Interrupt, Message, MessageId, ResumeEntry, ResumeStatus, RunId, ToolCallId, ToolContent,
14    ToolMessage,
15};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use super::Thread;
20use super::run::{RunEnd, RunStream};
21
22/// Local observation of an interrupt response submission.
23#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
24#[non_exhaustive]
25pub struct ResumeSubmission {
26    /// The request that carried these responses.
27    pub run_id: RunId,
28    /// Exact answers, retained for reconciliation by the application.
29    pub entries: Vec<ResumeEntry>,
30    /// Whether a valid terminal response has confirmed the request.
31    pub status: SubmissionStatus,
32}
33
34/// A submission is never retried automatically.
35///
36/// A thread holds one from the dispatch of a resume until the requested run
37/// reports `RUN_FINISHED`, whatever its outcome. `#[non_exhaustive]`: match
38/// with a wildcard arm. A match without one does not compile outside this
39/// crate:
40///
41/// ```compile_fail,E0004
42/// use ag_ui::client::SubmissionStatus;
43///
44/// fn word(status: &SubmissionStatus) -> &'static str {
45///     match status {
46///         SubmissionStatus::InFlight => "in flight",
47///         SubmissionStatus::Unconfirmed => "unconfirmed",
48///     }
49/// }
50/// ```
51#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
52#[non_exhaustive]
53pub enum SubmissionStatus {
54    /// Dispatched and still being observed. Restoring this becomes `Unconfirmed`.
55    InFlight,
56    /// Reading stopped before the requested run reported `RUN_FINISHED`: the
57    /// run failed, the stream was cut short or rejected, or it never carried
58    /// the requested run. Nothing says whether the agent took the answers.
59    Unconfirmed,
60}
61
62impl<T, S> Thread<T, S> {
63    pub(super) fn unconfirm(&mut self) {
64        if let Some(submission) = &mut self.submission {
65            submission.status = SubmissionStatus::Unconfirmed;
66        }
67    }
68    pub(super) fn confirm_interrupt_tool_decisions(
69        &mut self,
70        started_in_run: &HashSet<ToolCallId>,
71    ) {
72        let Some(submission) = &self.submission else {
73            return;
74        };
75        for interrupt in &self.interrupts {
76            if submission
77                .entries
78                .iter()
79                .any(|entry| entry.interrupt_id == interrupt.id)
80            {
81                if let Some(id) = &interrupt.tool_call_id {
82                    if started_in_run.contains(id) {
83                        continue;
84                    }
85                    self.decided_interrupt_tool_call_ids.insert(id.clone());
86                }
87            }
88        }
89    }
90}
91
92impl<T: Transport, S> Thread<T, S> {
93    /// Answer the single outstanding interrupt. All pending IDs must be answered.
94    pub fn resume(
95        &mut self,
96        interrupt: &Interrupt,
97        payload: impl Into<Value>,
98    ) -> Result<RunStream<'_, T, S>> {
99        self.resume_many([interrupt.resolve(payload)])
100    }
101    /// Decline the single outstanding interrupt. This is not execution cancellation.
102    ///
103    /// An expired interrupt can still be declined: that is how a thread moves
104    /// past a question nobody answered in time.
105    pub fn decline(&mut self, interrupt: &Interrupt) -> Result<RunStream<'_, T, S>> {
106        self.resume_many([interrupt.cancel()])
107    }
108    /// Answer every pending question exactly once. Expiry is checked against the
109    /// stored interrupt: an expired one can only be cancelled. Response schemas
110    /// are retained for the application/server to validate; this
111    /// transport-neutral API does not execute arbitrary schemas.
112    ///
113    /// # Expiry
114    ///
115    /// AG-UI 1.0 leaves the format of `expiresAt` open, so whether an
116    /// interrupt has expired is the consumer's reading of it. An interrupt
117    /// has expired when its `expiresAt` names an instant that is now or
118    /// earlier. Two forms name one: a date and time with its UTC offset, as
119    /// RFC 3339 writes it (`2026-01-31T12:00:00Z`,
120    /// `2026-01-31T21:00:00.5+09:00`), and a date alone (`2026-01-31`), read
121    /// as the start of that day in UTC.
122    ///
123    /// Any other value is not evidence of expiry, a date and time with no
124    /// offset included: the interrupt can be answered, the stream yields one
125    /// [`Update::Warning`](super::Update::Warning) naming it when the answer
126    /// is sent, and the agent, which enforces expiry in any case, decides.
127    pub fn resume_many(
128        &mut self,
129        entries: impl IntoIterator<Item = ResumeEntry>,
130    ) -> Result<RunStream<'_, T, S>> {
131        let entries: Vec<_> = entries.into_iter().collect();
132        self.preflight(Some(&entries), None)?;
133        self.start(None, Some(entries))
134    }
135    pub(super) fn preflight(
136        &self,
137        resume: Option<&[ResumeEntry]>,
138        message: Option<&Message>,
139    ) -> Result<()> {
140        if self.thread_id.as_str().is_empty() {
141            return Err(Error::Request("thread ID must not be empty".into()));
142        }
143        if self.submission.is_some() {
144            return Err(Error::Request("an unconfirmed submission requires reconciliation with server state before another run".into()));
145        }
146        match resume {
147            None if !self.interrupts.is_empty() => {
148                return Err(Error::PendingInterrupts(
149                    self.interrupts
150                        .iter()
151                        .map(|interrupt| interrupt.id.clone())
152                        .collect(),
153                ));
154            }
155            Some(entries) => validate_responses(&self.interrupts, entries, true)?,
156            None => {}
157        }
158        let mut pending_tools = self.unanswered_tool_calls();
159        if let Some(Message::Tool(answer)) = message {
160            // The new answer enters the request on first poll. Check that
161            // prospective history without inserting it during preflight.
162            pending_tools.retain(|id| id != &answer.tool_call_id);
163        }
164        if resume.is_some() {
165            // A matching resume entry answers the interrupt, including an
166            // approval concerning this tool call. It needs no ToolMessage.
167            let approval_ids: HashSet<_> = self
168                .interrupts
169                .iter()
170                .filter_map(|interrupt| interrupt.tool_call_id.as_ref())
171                .collect();
172            pending_tools.retain(|id| !approval_ids.contains(id));
173        }
174        if !pending_tools.is_empty() {
175            return Err(Error::UnansweredToolCalls(pending_tools));
176        }
177        if let Some(id) = &self.next_run_id {
178            if id.as_str().is_empty() || self.run_ids.contains(id) {
179                return Err(Error::Request(format!(
180                    "run ID {id} is empty or already used"
181                )));
182            }
183        }
184        Ok(())
185    }
186    /// Tool calls the next run must answer first, in call order.
187    ///
188    /// Every call in the transcript that no later tool message answers: the
189    /// frontend calls a run left for the application, and calls a failed or
190    /// aborted run never answered. `send`, `run` and `resume_many` refuse to
191    /// start a run while one is listed — AG-UI 1.0 requires a thread that
192    /// continues to answer each one first, and many models reject a history
193    /// with a dangling call. Answer one with a tool message
194    /// ([`push_message`](Thread::push_message) or [`send_message`](Self::send_message)),
195    /// or give it up with [`abandon_tool_call`](Self::abandon_tool_call). A call
196    /// a pending interrupt concerns is answered by resuming that interrupt.
197    ///
198    /// ```
199    /// use ag_ui::client::{Thread, transport::ReplayTransport};
200    /// use ag_ui::{AssistantMessage, Message, ToolCall};
201    ///
202    /// let call = Message::Assistant(AssistantMessage {
203    ///     id: "m-1".into(),
204    ///     tool_calls: Some(vec![ToolCall::new("call-1", "pick_file", "{}")]),
205    ///     ..Default::default()
206    /// });
207    /// let mut thread = Thread::<_>::builder(ReplayTransport::new([]), "thread-1")
208    ///     .messages(vec![call])
209    ///     .build()?;
210    /// assert_eq!(thread.unanswered_tool_calls(), ["call-1"]);
211    /// assert!(thread.send("Hello").is_err());
212    ///
213    /// thread.push_message(Message::tool("m-2", "call-1", "report.pdf"))?;
214    /// assert!(thread.unanswered_tool_calls().is_empty());
215    /// # Ok::<(), Box<dyn std::error::Error>>(())
216    /// ```
217    pub fn unanswered_tool_calls(&self) -> Vec<ToolCallId> {
218        self.unanswered_tool_calls_in(self.messages(), &self.decided_interrupt_tool_call_ids)
219    }
220
221    /// The same preflight applies before committing a proposed history merge.
222    pub(super) fn unanswered_tool_calls_in(
223        &self,
224        messages: &[Message],
225        decided: &HashSet<ToolCallId>,
226    ) -> Vec<ToolCallId> {
227        // Read the ordered transcript, because an answer preceding a call does
228        // not answer that call. A server-side TOOL_CALL_RESULT is already a tool
229        // message here, so it clears the same debt as a frontend response.
230        let mut pending = Vec::new();
231        let mut seen = HashSet::new();
232        let mut answered = HashSet::new();
233        for message in messages {
234            match message {
235                Message::Assistant(assistant) => {
236                    for call in assistant.tool_calls.iter().flatten() {
237                        answered.remove(&call.id);
238                        if seen.insert(call.id.clone()) {
239                            pending.push(call.id.clone());
240                        }
241                    }
242                }
243                Message::Tool(tool) => {
244                    answered.insert(tool.tool_call_id.clone());
245                }
246                _ => {}
247            }
248        }
249        if let Some(RunEnd::SuccessWithPendingToolCalls {
250            pending_tool_call_ids,
251            ..
252        }) = &self.last_run_end
253        {
254            for id in pending_tool_call_ids {
255                if seen.insert(id.clone()) {
256                    pending.push(id.clone());
257                }
258            }
259        }
260        let explicit_pending = match &self.last_run_end {
261            Some(RunEnd::SuccessWithPendingToolCalls {
262                pending_tool_call_ids,
263                ..
264            }) => pending_tool_call_ids.iter().collect::<HashSet<_>>(),
265            _ => HashSet::new(),
266        };
267        pending.retain(|id| {
268            !answered.contains(id) && (!decided.contains(id) || explicit_pending.contains(id))
269        });
270        pending
271    }
272    /// Give up an unanswered tool call, answering it with a tool message whose
273    /// `content` and `error` both carry `reason`.
274    ///
275    /// For a call nobody will execute, such as one a failed or aborted run left
276    /// behind. AG-UI 1.0 answers such a call rather than dropping it: a failure
277    /// is still an answer, as a tool message with `error` set. The call and its
278    /// answer both stay in [`messages`](Thread::messages) and in a snapshot,
279    /// and the next run sends them. Nothing is sent now.
280    ///
281    /// Rejects a call that is not in [`unanswered_tool_calls`](Self::unanswered_tool_calls),
282    /// and one a pending interrupt concerns: resume or decline that interrupt
283    /// instead.
284    ///
285    /// ```
286    /// # use ag_ui::client::{RunEnd, Thread, transport::ReplayTransport};
287    /// # use ag_ui::{Event, Message};
288    /// # let transport = ReplayTransport::with_runs([
289    /// #     vec![
290    /// #         Event::run_started("thread-1", "run-1"),
291    /// #         Event::tool_call_start("call-1", "lookup"),
292    /// #         Event::run_error("the model provider went away"),
293    /// #     ],
294    /// #     vec![
295    /// #         Event::run_started("thread-1", "run-2"),
296    /// #         Event::run_finished_success("thread-1", "run-2"),
297    /// #     ],
298    /// # ]).matching_requests();
299    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
300    /// # rt.block_on(async {
301    /// let mut thread = Thread::<_>::new(transport, "thread-1");
302    /// let report = thread.send("look it up").unwrap().collect_report().await;
303    /// assert!(matches!(report.end, RunEnd::Failed { .. }));
304    ///
305    /// // The failed run left `call-1` without a result, so nothing can follow it ...
306    /// assert!(thread.send("try again").is_err());
307    /// for call in thread.unanswered_tool_calls() {
308    ///     thread.abandon_tool_call(&call, "not run: the run that made this call failed").unwrap();
309    /// }
310    /// // ... until it is answered, and the answer stays in the transcript.
311    /// assert!(matches!(thread.messages().last(), Some(Message::Tool(answer)) if answer.error.is_some()));
312    /// let report = thread.send("try again").unwrap().collect_report().await;
313    /// assert_eq!(report.end, RunEnd::Success { result: None });
314    /// # });
315    /// ```
316    pub fn abandon_tool_call(&mut self, id: &ToolCallId, reason: impl Into<String>) -> Result<()> {
317        if !self.unanswered_tool_calls().contains(id) {
318            return Err(Error::Request(format!(
319                "tool call {id} is not awaiting an answer"
320            )));
321        }
322        if let Some(interrupt) = self
323            .interrupts
324            .iter()
325            .find(|interrupt| interrupt.tool_call_id.as_ref() == Some(id))
326        {
327            return Err(Error::Request(format!(
328                "tool call {id} awaits the decision of interrupt {}; resume or decline it instead",
329                interrupt.id
330            )));
331        }
332        let reason = reason.into();
333        let message_id = MessageId::new(self.fresh_id(false)?);
334        self.applier.push_message(Message::Tool(ToolMessage {
335            id: message_id.clone(),
336            content: ToolContent::Text(reason.clone()),
337            tool_call_id: id.clone(),
338            error: Some(reason),
339            ..Default::default()
340        }));
341        // Remembered as a stand-in: a merge leaves it out when the other
342        // thread holds the result this one never got.
343        self.abandoned.insert(message_id);
344        Ok(())
345    }
346}
347
348pub(super) fn validate_responses(
349    pending: &[Interrupt],
350    entries: &[ResumeEntry],
351    expiry: bool,
352) -> Result<()> {
353    if pending.is_empty() {
354        return Err(Error::Request("there are no pending interrupts".into()));
355    }
356    let mut seen = HashSet::new();
357    for entry in entries {
358        if !seen.insert(&entry.interrupt_id) {
359            return Err(Error::Request(format!(
360                "duplicate interrupt ID {}",
361                entry.interrupt_id
362            )));
363        }
364        let interrupt = pending
365            .iter()
366            .find(|interrupt| interrupt.id == entry.interrupt_id)
367            .ok_or_else(|| {
368                Error::Request(format!("unknown interrupt ID {}", entry.interrupt_id))
369            })?;
370        // Expiry ends answering, not abandoning: an interrupt nobody answered
371        // in time is cancelled, which is how the thread moves past it. Only
372        // an `expiresAt` that names an instant is evidence of expiry.
373        if expiry && entry.status == ResumeStatus::Resolved {
374            let expires = interrupt.expires_at.as_deref().and_then(instant);
375            if expires.is_some_and(|expires| expires <= now_unix_nanos()) {
376                return Err(Error::Request(format!(
377                    "interrupt {} has expired; it can only be declined",
378                    interrupt.id
379                )));
380            }
381        }
382    }
383    if seen.len() != pending.len() {
384        return Err(Error::Request(
385            "every pending interrupt must be answered exactly once".into(),
386        ));
387    }
388    Ok(())
389}
390
391/// One warning for each interrupt `entries` answer whose `expiresAt` the
392/// thread cannot read as a date, for the request that sends the answers.
393pub(super) fn unread_expiries(pending: &[Interrupt], entries: &[ResumeEntry]) -> Vec<String> {
394    entries
395        .iter()
396        .filter(|entry| entry.status == ResumeStatus::Resolved)
397        .filter_map(|entry| {
398            let interrupt = pending
399                .iter()
400                .find(|interrupt| interrupt.id == entry.interrupt_id)?;
401            let timestamp = interrupt.expires_at.as_deref()?;
402            instant(timestamp).is_none().then(|| {
403                format!(
404                    "interrupt \"{}\" carries an expiresAt this thread does not read as a date, \
405                     \"{}\": the answer is sent as in time, and the agent decides whether it is",
406                    crate::protocol::excerpt(&interrupt.id, false),
407                    crate::protocol::excerpt(timestamp, false)
408                )
409            })
410        })
411        .collect()
412}
413
414/// The instant an `expiresAt` names, in nanoseconds since the Unix epoch, or
415/// `None` for a value that names none this thread can compare with now.
416///
417/// AG-UI 1.0 leaves the format open (`basic/patterns/interrupt-resume`:
418/// "whether an interrupt has expired is the judging consumer's own reading
419/// of it — the reference reads it as a date and treats now-or-earlier as
420/// expired") and names ISO 8601 as the convention. Two forms are read, the
421/// two the reference reads the same in every time zone:
422///
423/// - a date and time with its UTC offset, as RFC 3339 writes it;
424/// - a date alone, `YYYY-MM-DD`, as the start of that day in UTC, which is
425///   what ECMAScript makes of it.
426///
427/// A date and time with no offset is not read. The reference reads it in the
428/// viewer's own time zone, so there is no reading that agrees with it
429/// everywhere, and 1.0 names no zone. Nor is anything else: a value that
430/// cannot be read is not evidence of expiry (1.0, the schema: "a value that
431/// is not one leaves the interrupt looking permanently unexpired"), and the
432/// agent enforces expiry whatever the consumer makes of the value.
433fn instant(timestamp: &str) -> Option<i128> {
434    use jiff::civil::{Date, Time, date};
435
436    let (calendar, rest) = timestamp.split_at_checked(10)?;
437    if calendar.as_bytes()[4] != b'-' || calendar.as_bytes()[7] != b'-' {
438        return None;
439    }
440    let calendar: Date = calendar.parse().ok()?;
441    let midnight = calendar.duration_since(date(1970, 1, 1)).as_secs();
442    if rest.is_empty() {
443        return Some(i128::from(midnight) * 1_000_000_000);
444    }
445
446    let rest = rest.strip_prefix(['T', 't', ' '])?;
447    let (clock, zone) = rest.split_at(rest.find(['Z', 'z', '+', '-', '−'])?);
448    let offset = match zone {
449        "Z" | "z" => 0,
450        _ => {
451            let digits = zone.strip_prefix(['+', '-', '−'])?;
452            let (hour, minute) = digits.split_once(':')?;
453            if hour.len() != 2
454                || minute.len() != 2
455                || !digits.bytes().all(|b| b == b':' || b.is_ascii_digit())
456            {
457                return None;
458            }
459            let (hour, minute) = (hour.parse::<i64>().ok()?, minute.parse::<i64>().ok()?);
460            if hour > 23 || minute > 59 {
461                return None;
462            }
463            let seconds = (hour * 60 + minute) * 60;
464            if zone.starts_with('+') {
465                seconds
466            } else {
467                -seconds
468            }
469        }
470    };
471
472    let (hms, fraction) = clock.split_at_checked(8)?;
473    if hms.as_bytes()[2] != b':' || hms.as_bytes()[5] != b':' {
474        return None;
475    }
476    if !fraction.is_empty() {
477        let digits = fraction.strip_prefix('.')?;
478        if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
479            return None;
480        }
481    }
482    // RFC 3339 allows more fractional digits than the nanosecond clock stores.
483    let time: Time = clock.get(..clock.len().min(18))?.parse().ok()?;
484    let utc =
485        i64::from(time.hour()) * 3600 + i64::from(time.minute()) * 60 + i64::from(time.second())
486            - offset;
487    let nanos = if hms.ends_with(":60") {
488        // Jiff constrains :60 to :59. Only the end of a UTC month can leap.
489        // A negative UTC time-of-day here falls on the previous local date.
490        let ends_month = if utc < 0 {
491            calendar.day() == 1
492        } else {
493            calendar.day() == calendar.days_in_month()
494        };
495        if utc.rem_euclid(86_400) != 86_399 || !ends_month {
496            return None;
497        }
498        999_999_999
499    } else {
500        time.subsec_nanosecond()
501    };
502    Some(i128::from(midnight + utc) * 1_000_000_000 + i128::from(nanos))
503}
504
505#[cfg(not(target_family = "wasm"))]
506fn now_unix_nanos() -> i128 {
507    match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
508        Ok(elapsed) => elapsed.as_nanos() as i128,
509        Err(error) => -(error.duration().as_nanos() as i128),
510    }
511}
512#[cfg(target_family = "wasm")]
513fn now_unix_nanos() -> i128 {
514    (js_sys::Date::now() * 1_000_000.0) as i128
515}
516
517#[cfg(test)]
518mod expiry_tests {
519    use super::instant;
520
521    #[test]
522    fn expiry_preserves_nanoseconds_and_validates_utc_leap_seconds() {
523        assert_eq!(instant("1969-12-31T23:59:59.999999999Z"), Some(-1));
524        assert_eq!(
525            instant("1970-01-01 00:00:00.123456789123z"),
526            Some(123_456_789)
527        );
528        assert_eq!(instant("1970-01-01T23:59:00+23:59"), Some(0));
529        assert_eq!(instant("1969-12-31T00:01:00−23:59"), Some(0));
530        assert_eq!(
531            instant("2017-01-01T08:59:60+09:00"),
532            instant("2016-12-31T23:59:59.999999999Z")
533        );
534        for invalid in [
535            "2017-01-02T08:59:60+09:00",
536            "2000-01-01T24:00:00Z",
537            "1970-01-01T00:00:00+24:00",
538            "1970-01-01T00:00:00+00:60",
539            "1970-01-01T00:00:00.123456789xZ",
540            "1970-01-01T00:00:00Z[UTC]",
541        ] {
542            assert_eq!(instant(invalid), None, "{invalid}");
543        }
544    }
545}