pub struct Thread<T, S = Value> { /* private fields */ }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>
impl<T: Transport, S> Thread<T, S>
Sourcepub fn merge_messages_from<U: Transport, R>(
&mut self,
other: &Thread<U, R>,
) -> Result<MergeReport>
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 thread | After the merge |
|---|---|
| a message this thread lacks | added |
| a message both hold | this 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 to | left out, and named in MergeReport::superseded |
the subagents it lists (subagents) | added where this thread lacks the invocation |
| the run ids it used | refused for a run of this thread too |
| a tool call an interrupt decided there | stays decided here, when its message was added |
| its state | not read: this thread’s raw_state is unchanged |
| pending interrupts, a resume submission, unanswered tool calls, a request in flight | the 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>
impl<T: Transport, S> Thread<T, S>
Sourcepub fn resume(
&mut self,
interrupt: &Interrupt,
payload: impl Into<Value>,
) -> Result<RunStream<'_, T, S>>
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.
Sourcepub fn decline(&mut self, interrupt: &Interrupt) -> Result<RunStream<'_, T, S>>
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.
Sourcepub fn resume_many(
&mut self,
entries: impl IntoIterator<Item = ResumeEntry>,
) -> Result<RunStream<'_, T, S>>
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.
Sourcepub fn unanswered_tool_calls(&self) -> Vec<ToolCallId>
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());Sourcepub fn abandon_tool_call(
&mut self,
id: &ToolCallId,
reason: impl Into<String>,
) -> Result<()>
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>
impl<T, S> Thread<T, S>
Sourcepub fn snapshot(&self) -> ThreadSnapshot
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>
impl<T, S: DeserializeOwned> Thread<T, S>
Sourcepub fn restore(transport: T, snapshot: ThreadSnapshot) -> Result<Self>where
T: Transport,
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, S> Thread<T, S>
impl<T, S> Thread<T, S>
Sourcepub fn builder(
transport: T,
thread_id: impl Into<ThreadId>,
) -> ThreadBuilder<T, S>where
T: Transport,
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.
Sourcepub fn messages(&self) -> &[Message]
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).
Sourcepub fn state(&self) -> Result<&S, StateViewError>
pub fn state(&self) -> Result<&S, StateViewError>
The current typed view. A remote type mismatch invalidates the old view.
Sourcepub fn reasoning(&self) -> impl Iterator<Item = &ReasoningMessage>
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.
Sourcepub fn interrupts(&self) -> &[Interrupt]
pub fn interrupts(&self) -> &[Interrupt]
Pending human input. Dispatching a response does not remove it.
Sourcepub fn submission(&self) -> Option<&ResumeSubmission>
pub fn submission(&self) -> Option<&ResumeSubmission>
Unconfirmed or currently in-flight response submission.
Sourcepub fn subagent(&self, id: &SubagentRunId) -> Option<&Subagent>
pub fn subagent(&self, id: &SubagentRunId) -> Option<&Subagent>
Find a subagent by invocation ID.
Sourcepub fn agent(&self) -> &RemoteAgent<Arc<T>>
pub fn agent(&self) -> &RemoteAgent<Arc<T>>
The low-level agent using the same owned transport handle.
Sourcepub fn last_run_end(&self) -> Option<&RunEnd>
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.
Sourcepub fn push_message(&mut self, message: Message) -> Result<()>
pub fn push_message(&mut self, message: Message) -> Result<()>
Append a client-owned message, rejecting an ID already in the transcript.
Sourcepub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>)
pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>)
Tools offered on subsequent runs. AG-UI does not discover tools.
Sourcepub fn set_context(&mut self, context: impl Into<Vec<Context>>)
pub fn set_context(&mut self, context: impl Into<Vec<Context>>)
Context sent on subsequent runs.
Sourcepub fn set_forwarded_props(&mut self, props: impl Into<Value>)
pub fn set_forwarded_props(&mut self, props: impl Into<Value>)
Passthrough request properties supplied by the application.
Sourcepub fn set_verify(&mut self, verify: bool)
pub fn set_verify(&mut self, verify: bool)
Configure protocol ordering verification. Identity and resume safety checks stay enabled.
Sourcepub fn set_diagnostic_limit(&mut self, limit: usize)
pub fn set_diagnostic_limit(&mut self, limit: usize)
Retained diagnostics per request. Excess errors are still yielded as updates.
Sourcepub fn set_next_run_id(&mut self, id: impl Into<RunId>)
pub fn set_next_run_id(&mut self, id: impl Into<RunId>)
Reserve an explicit run ID. Reuse is rejected during request preflight.
Sourcepub fn clear_event_observer(&mut self)
pub fn clear_event_observer(&mut self)
Remove the event observer.
Source§impl<T, S: DeserializeOwned> Thread<T, S>
impl<T, S: DeserializeOwned> Thread<T, S>
Source§impl<T: Transport, S> Thread<T, S>
impl<T: Transport, S> Thread<T, S>
Sourcepub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>>
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.
Sourcepub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>>
pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>>
Prepare a message of any role, rejecting existing IDs.