Skip to main content

Thread

Struct Thread 

Source
pub struct Thread<T, S = Value> { /* private fields */ }
Available on crate feature client only.
Expand description

One local conversation with an agent. T only supplies communication. S is the current state view, defaulting to JSON.

Implementations§

Source§

impl<T: Transport, S> Thread<T, S>

Source

pub fn merge_messages_from<U: Transport, R>( &mut self, other: &Thread<U, R>, ) -> Result<MergeReport>

Adds the messages another thread of the same conversation holds and this one lacks, by the rules of merge_messages: this thread’s messages are kept as they are, the other’s follow them in the other thread’s order, and a tool result stands behind the message that holds its call.

This is how two runs that were in flight together on one conversation come back to one thread, which then sends the next request; see the module docs. Nothing is sent, and other is not changed. Draw the conversation again afterwards, as after Update::Messages: a message may have been added between two this thread held.

§What the merge takes, leaves and refuses
Of the other threadAfter the merge
a message this thread lacksadded
a message both holdthis thread’s copy; an id whose copies differ is in MergeReport::differing
a tool message abandon_tool_call made there, for a call this thread holds an answer toleft out, and named in MergeReport::superseded
the subagents it lists (subagents)added where this thread lacks the invocation
the run ids it usedrefused for a run of this thread too
a tool call an interrupt decided therestays decided here, when its message was added
its statenot read: this thread’s raw_state is unchanged
pending interrupts, a resume submission, unanswered tool calls, a request in flightthe merge is refused, and likewise when this thread has any

State is the application’s to settle. AG-UI 1.0 does not say what two runs open at once on one thread do to the state they share, so nothing here chooses: read raw_state of both threads and call set_state with the value the next run should start from.

Both threads must be at rest, each able to start a run of its own. What a thread still owes belongs to the thread that owes it: an interrupt is answered where its submission is tracked, and a tool call is answered before another turn stands between the call and its result. Settle those first, on the thread that has them, with resume, a tool message or abandon_tool_call. Both threads were at rest, so the merged one can take the next request, and send checks it as it checks any other.

A tool call that both threads answered, each with a message of its own, is refused as well: a call has one result, and choosing between two is not this method’s to do. A stand-in is not a result. A thread remembers the tool messages its abandon_tool_call made, and so does its snapshot, so a stand-in on the other thread gives way to the answer this thread holds. The other way round, a stand-in here and a result there, is refused, because a merge changes and removes nothing of this thread’s: merge this thread into the other one instead, where the result stands and the stand-in gives way.

use ag_ui::Message;
use ag_ui::client::{Thread, transport::ReplayTransport};

let start = vec![Message::user("u-1", "Hello"), Message::assistant("a-1", "Hi")];
let thread = |added: [Message; 2]| {
    let mut messages = start.clone();
    messages.extend(added);
    Thread::<_>::builder(ReplayTransport::new([]), "thread-1")
        .messages(messages)
        .build()
};
let mut main = thread([
    Message::user("u-2", "Write the report"),
    Message::assistant("a-2", "Here it is."),
])?;
let side = thread([
    Message::user("u-3", "What time is it?"),
    Message::assistant("a-3", "Noon."),
])?;

let merged = main.merge_messages_from(&side)?;
assert_eq!(merged.added, ["u-3", "a-3"]);
assert!(merged.differing.is_empty());
let ids: Vec<_> = main.messages().iter().map(|message| message.id().as_str()).collect();
assert_eq!(ids, ["u-1", "a-1", "u-2", "a-2", "u-3", "a-3"]);
// Merging again adds nothing: every message is held now.
assert!(main.merge_messages_from(&side)?.added.is_empty());
§Errors

Error::Merge, with nothing changed, when the two threads have different thread ids, when either is not at rest, when a tool call has a result on each thread, when this thread gave up a call the other holds a result for, or when keeping this thread’s message would detach an incoming result from its call or leave the merged conversation with an unanswered call.

Source§

impl<T: Transport, S> Thread<T, S>

Source

pub fn resume( &mut self, interrupt: &Interrupt, payload: impl Into<Value>, ) -> Result<RunStream<'_, T, S>>

Answer the single outstanding interrupt. All pending IDs must be answered.

Source

pub fn decline(&mut self, interrupt: &Interrupt) -> Result<RunStream<'_, T, S>>

Decline the single outstanding interrupt. This is not execution cancellation.

An expired interrupt can still be declined: that is how a thread moves past a question nobody answered in time.

Source

pub fn resume_many( &mut self, entries: impl IntoIterator<Item = ResumeEntry>, ) -> Result<RunStream<'_, T, S>>

Answer every pending question exactly once. Expiry is checked against the stored interrupt: an expired one can only be cancelled. Response schemas are retained for the application/server to validate; this transport-neutral API does not execute arbitrary schemas.

§Expiry

AG-UI 1.0 leaves the format of expiresAt open, so whether an interrupt has expired is the consumer’s reading of it. An interrupt has expired when its expiresAt names an instant that is now or earlier. Two forms name one: a date and time with its UTC offset, as RFC 3339 writes it (2026-01-31T12:00:00Z, 2026-01-31T21:00:00.5+09:00), and a date alone (2026-01-31), read as the start of that day in UTC.

Any other value is not evidence of expiry, a date and time with no offset included: the interrupt can be answered, the stream yields one Update::Warning naming it when the answer is sent, and the agent, which enforces expiry in any case, decides.

Source

pub fn unanswered_tool_calls(&self) -> Vec<ToolCallId>

Tool calls the next run must answer first, in call order.

Every call in the transcript that no later tool message answers: the frontend calls a run left for the application, and calls a failed or aborted run never answered. send, run and resume_many refuse to start a run while one is listed — AG-UI 1.0 requires a thread that continues to answer each one first, and many models reject a history with a dangling call. Answer one with a tool message (push_message or send_message), or give it up with abandon_tool_call. A call a pending interrupt concerns is answered by resuming that interrupt.

use ag_ui::client::{Thread, transport::ReplayTransport};
use ag_ui::{AssistantMessage, Message, ToolCall};

let call = Message::Assistant(AssistantMessage {
    id: "m-1".into(),
    tool_calls: Some(vec![ToolCall::new("call-1", "pick_file", "{}")]),
    ..Default::default()
});
let mut thread = Thread::<_>::builder(ReplayTransport::new([]), "thread-1")
    .messages(vec![call])
    .build()?;
assert_eq!(thread.unanswered_tool_calls(), ["call-1"]);
assert!(thread.send("Hello").is_err());

thread.push_message(Message::tool("m-2", "call-1", "report.pdf"))?;
assert!(thread.unanswered_tool_calls().is_empty());
Source

pub fn abandon_tool_call( &mut self, id: &ToolCallId, reason: impl Into<String>, ) -> Result<()>

Give up an unanswered tool call, answering it with a tool message whose content and error both carry reason.

For a call nobody will execute, such as one a failed or aborted run left behind. AG-UI 1.0 answers such a call rather than dropping it: a failure is still an answer, as a tool message with error set. The call and its answer both stay in messages and in a snapshot, and the next run sends them. Nothing is sent now.

Rejects a call that is not in unanswered_tool_calls, and one a pending interrupt concerns: resume or decline that interrupt instead.

let mut thread = Thread::<_>::new(transport, "thread-1");
let report = thread.send("look it up").unwrap().collect_report().await;
assert!(matches!(report.end, RunEnd::Failed { .. }));

// The failed run left `call-1` without a result, so nothing can follow it ...
assert!(thread.send("try again").is_err());
for call in thread.unanswered_tool_calls() {
    thread.abandon_tool_call(&call, "not run: the run that made this call failed").unwrap();
}
// ... until it is answered, and the answer stays in the transcript.
assert!(matches!(thread.messages().last(), Some(Message::Tool(answer)) if answer.error.is_some()));
let report = thread.send("try again").unwrap().collect_report().await;
assert_eq!(report.end, RunEnd::Success { result: None });
Source§

impl<T, S> Thread<T, S>

Source

pub fn snapshot(&self) -> ThreadSnapshot

Save local conversation data. Transport settings and callbacks are excluded.

What a run leaves can be restored: Thread::restore accepts the snapshot of a thread whatever the streams it read carried.

Source§

impl<T, S: DeserializeOwned> Thread<T, S>

Source

pub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>
where T: Transport,

Restore local state using a new transport. No server query is performed.

A version 1 snapshot kept reasoning in a list of its own, and nothing in it says where a reasoning message stood among the others. Its entries are put before every message of the conversation, in the order the list held them. Reasoning comes before the reply it led to, and there each entry still does; after the messages, each would follow its own reply and stand in front of whatever the agent says next. From there they are sent with the next run, like any other reasoning message.

Two kinds of entry are not moved. One whose id a message of the conversation already has, because an id names one message. And one with no content, encrypted value or metadata: that is what version 1 kept for a REASONING_START whose id no reasoning message shared, and it holds no reasoning.

§Errors

Error::Snapshot for a version this build does not read, an empty thread id, an id a list holds twice, a subagent whose parent is not listed or is one of its own descendants, and a submission that does not fit the rest; Error::State for a state that does not fit S. An id may be the empty string: AG-UI 1.0 sets no minimum length for one.

Source§

impl<T: Transport> Thread<T>

Source

pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self

Creates an empty JSON conversation. No request is sent.

Source§

impl<T, S> Thread<T, S>

Source

pub fn builder( transport: T, thread_id: impl Into<ThreadId>, ) -> ThreadBuilder<T, S>
where T: Transport,

Configures a conversation and validates its initial typed state at build.

Source

pub fn thread_id(&self) -> &ThreadId

The remote conversation identifier.

Source

pub fn messages(&self) -> &[Message]

The current assembled conversation, reasoning and activity messages included. A run sends all of it but the activity messages.

To draw the conversation without the agent’s reasoning, leave that role out: messages().iter().filter(|m| m.role() != Role::Reasoning).

Source

pub fn state(&self) -> Result<&S, StateViewError>

The current typed view. A remote type mismatch invalidates the old view.

Source

pub fn raw_state(&self) -> &Value

The latest raw state, even when it does not fit S.

Source

pub fn reasoning(&self) -> impl Iterator<Item = &ReasoningMessage>

The reasoning messages in messages, oldest first: a view over that list, for a UI that draws reasoning in a pane of its own.

Source

pub fn interrupts(&self) -> &[Interrupt]

Pending human input. Dispatching a response does not remove it.

Source

pub fn submission(&self) -> Option<&ResumeSubmission>

Unconfirmed or currently in-flight response submission.

Source

pub fn subagents(&self) -> &[Subagent]

Announced subagents across runs.

Source

pub fn subagent(&self, id: &SubagentRunId) -> Option<&Subagent>

Find a subagent by invocation ID.

Source

pub fn applier(&self) -> &Applier

The current materialized protocol data.

Source

pub fn agent(&self) -> &RemoteAgent<Arc<T>>

The low-level agent using the same owned transport handle.

Source

pub fn last_run_end(&self) -> Option<&RunEnd>

How the last request went: what its stream’s Update::Done carried. Dropping a dispatched request before its stream ends records Aborted, unless the last run from the requested one on had already ended: that ending stays.

Source

pub fn push_message(&mut self, message: Message) -> Result<()>

Append a client-owned message, rejecting an ID already in the transcript.

Source

pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>)

Tools offered on subsequent runs. AG-UI does not discover tools.

Source

pub fn set_context(&mut self, context: impl Into<Vec<Context>>)

Context sent on subsequent runs.

Source

pub fn set_forwarded_props(&mut self, props: impl Into<Value>)

Passthrough request properties supplied by the application.

Source

pub fn set_verify(&mut self, verify: bool)

Configure protocol ordering verification. Identity and resume safety checks stay enabled.

Source

pub fn set_diagnostic_limit(&mut self, limit: usize)

Retained diagnostics per request. Excess errors are still yielded as updates.

Source

pub fn set_next_run_id(&mut self, id: impl Into<RunId>)

Reserve an explicit run ID. Reuse is rejected during request preflight.

Source

pub fn clear_event_observer(&mut self)

Remove the event observer.

Source

pub fn on_event(&mut self, observer: impl FnMut(&Event) + Send + 'static)

Available on non-target_family=wasm only.

Replace the synchronous read-only observer. Called once per checked event, before chunk normalization and ordering verification. Queue slow work in the application.

Source§

impl<T, S: DeserializeOwned> Thread<T, S>

Source

pub fn set_state(&mut self, state: impl Into<Value>) -> Result<()>

Validates local JSON before atomically replacing both raw and typed state.

Source§

impl<T: Transport, S> Thread<T, S>

Source

pub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>>

Prepare a user turn. Pending decisions and ambiguous submissions are checked before changing history. Dispatch and history insertion occur on first poll.

§Errors

Like send_message, run and resume_many, this refuses a request the conversation is not ready for, before anything is sent: Error::UnansweredToolCalls names the tool calls still awaiting a result, Error::PendingInterrupts the interrupts still awaiting an answer, and Error::Request says why in any other case.

Source

pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>>

Prepare a message of any role, rejecting existing IDs.

Source

pub fn run(&mut self) -> Result<RunStream<'_, T, S>>

Prepare a run with the existing conversation and no new message.

Trait Implementations§

Source§

impl<T, S: Debug> Debug for Thread<T, S>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<T, S = Value> !RefUnwindSafe for Thread<T, S>

§

impl<T, S = Value> !Sync for Thread<T, S>

§

impl<T, S = Value> !UnwindSafe for Thread<T, S>

§

impl<T, S> Forget for Thread<T, S>

§

impl<T, S> Freeze for Thread<T, S>

§

impl<T, S> Move for Thread<T, S>

§

impl<T, S> Send for Thread<T, S>

§

impl<T, S> Unpin for Thread<T, S>

§

impl<T, S> UnsafeUnpin for Thread<T, S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more