ag_ui/client/thread/mod.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 request borrows the thread until dropped. Requests are dispatched on first poll.
6//!
7//! # Several runs on one stream
8//!
9//! A request asks for one run, and AG-UI 1.0 lets the stream that answers it
10//! carry several in sequence: the runs the producer replays, then the
11//! requested one, which echoes the request's run id. A [`RunStream`] reads
12//! to the end of the stream. Messages accumulate and state persists across
13//! the runs; each run yields one [`Update::RunEnded`], and is listed in
14//! [`RunReport::runs`]; one [`Update::Done`] ends the stream.
15//!
16//! What a run's end means for the thread depends on where the run stands:
17//!
18//! | Run | Ends | The thread |
19//! | --- | --- | --- |
20//! | replayed, before the requested run | any way | keeps what it delivered and reports it; owes nothing new |
21//! | requested | success, interrupt | confirms a resume [submission](Thread::submission); pending [interrupts](Thread::interrupts) cleared, or set |
22//! | requested | cancelled | settles a resume submission; pending interrupts cleared |
23//! | requested | `RUN_ERROR`, cut short | leaves a submission unconfirmed, and the interrupts as they were |
24//! | after the requested run | success, cancelled | pending interrupts cleared |
25//! | after the requested run | interrupt | pending interrupts set |
26//! | after the requested run | `RUN_ERROR`, cut short | pending interrupts left |
27//! | after the requested run, a submission unconfirmed | any `RUN_FINISHED` | pending interrupts left, with an [`Update::Warning`] |
28//!
29//! A requested run that ends `cancelled` took the answers of a resume and
30//! reported how it ended, so the submission is settled like a confirmed one.
31//! AG-UI 1.0 (`events/lifecycle`, "Cancelled runs"): "A cancelled run waits
32//! for nothing. Its outcome carries no interrupts, and the next run on the
33//! thread is an ordinary new run, not a resume." It did not complete, so a
34//! tool call one of the answers approved is still in
35//! [`Thread::unanswered_tool_calls`] when the run left it without a result.
36//!
37//! A `RUN_ERROR` that opens the stream belongs to no run. With nothing after
38//! it, it is the requested run failing before it began, and is read as the
39//! requested run above. With a run after it, it is history, like a replayed
40//! run: at most one run of a stream is the requested one.
41//!
42//! The request went the way the last run from the requested one on ended:
43//! that is [`Update::Done`], [`RunReport::end`] and [`Thread::last_run_end`].
44//! 1.0 makes the requested run the last of its stream, so on a conforming
45//! stream it is the requested run's end. A producer that keeps the stream
46//! open may send a run after it all the same, and the agent then stands
47//! where that run left it. A stream that ends without the requested run does
48//! not answer the request, and fails it.
49//!
50//! [`Thread::unanswered_tool_calls`] reads the conversation, so a call any
51//! run left without a result is owed.
52//!
53//! # Two runs at once
54//!
55//! A request borrows its thread until its stream ends, so one [`Thread`] has
56//! one request in flight. A second one does not compile:
57//!
58//! ```compile_fail,E0499
59//! use ag_ui::client::{Thread, transport::ReplayTransport};
60//!
61//! let mut thread = Thread::new(ReplayTransport::new([]), "thread-1");
62//! let long = thread.send("Write the report").unwrap();
63//! let quick = thread.send("What time is it?").unwrap(); // `thread` is still borrowed
64//! drop((long, quick));
65//! ```
66//!
67//! That is deliberate. A thread tracks what one request owes: its resume
68//! submission, the interrupts it left pending, how it ended. AG-UI 1.0
69//! describes a thread as runs in sequence and does not say how two runs open
70//! at once reconcile their messages or the state they share.
71//!
72//! For a quick question while a long run works on the same conversation, use
73//! two threads with the same thread id, each holding the conversation as it
74//! stood, and merge their messages once both streams have ended:
75//!
76//! ```
77//! use ag_ui::client::{RunEnd, Thread, merge_messages, transport::ReplayTransport};
78//! # use ag_ui::{Event, TextMessageRole};
79//! use futures_util::StreamExt;
80//! # fn reply(id: &str, text: &str) -> Vec<Event> {
81//! # vec![
82//! # Event::run_started("thread-1", "run"),
83//! # Event::text_message_start(id, TextMessageRole::Assistant),
84//! # Event::text_message_content(id, text),
85//! # Event::text_message_end(id),
86//! # Event::run_finished_success("thread-1", "run"),
87//! # ]
88//! # }
89//! # let transport = ReplayTransport::with_runs([
90//! # reply("report", "Here is the report."),
91//! # reply("time", "It is noon."),
92//! # reply("welcome", "You are welcome."),
93//! # ])
94//! # .matching_requests();
95//! # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
96//! # rt.block_on(async {
97//! let mut main = Thread::new(transport.clone(), "thread-1");
98//! // A second thread on the same conversation, holding the same messages.
99//! let mut side = Thread::<_>::restore(transport.clone(), main.snapshot())?;
100//!
101//! // The long run starts, and borrows `main` until its stream ends ...
102//! let mut long = main.send("Write the report")?;
103//! long.next().await;
104//! // ... so the quick question goes to `side`, and is answered meanwhile.
105//! let quick = side.send("What time is it?")?.collect_report().await;
106//! assert_eq!(quick.end, RunEnd::Success { result: None });
107//! // Both can be drawn as one list at any moment.
108//! let on_screen = merge_messages(long.thread().messages(), side.messages());
109//! assert_eq!(on_screen.len(), 4);
110//! long.collect_report().await;
111//!
112//! // Both streams have ended: `main` takes the messages it lacks ...
113//! let merged = main.merge_messages_from(&side)?;
114//! assert_eq!(merged.added.len(), 2);
115//! assert!(merged.differing.is_empty());
116//! // ... and its next request carries both runs.
117//! main.send("Thanks")?.collect_report().await;
118//! assert_eq!(transport.last_request().unwrap().messages.len(), 5);
119//! # Ok::<(), ag_ui::client::Error>(())
120//! # })
121//! # .unwrap();
122//! ```
123//!
124//! Make the second thread from a [snapshot](Thread::snapshot) taken before
125//! the long run is polled, as above, so that both start from the same
126//! messages; with `HttpAgent` that is `agent.restore_thread(main.snapshot())`.
127//! A restored thread has the defaults for what a snapshot does not hold: set
128//! its tools, context and forwarded properties again. A second thread made
129//! later, from `long.thread().snapshot()` while the long run is being read,
130//! holds what had arrived by then. A message it holds only in part stays as
131//! the thread that finished it has it, and is named in
132//! [`MergeReport::differing`].
133//!
134//! Two things the long run had in flight then are the copy's to settle, as
135//! on any restored thread. A tool call the run made and has not had the
136//! result of yet is unanswered on the copy, which sends nothing until it has
137//! an answer: give the call up there first, with
138//! [`abandon_tool_call`](Thread::abandon_tool_call). When the long run then
139//! receives the result, merging the copy into `main` leaves the copy's
140//! stand-in out and names it in [`MergeReport::superseded`]. Merging `main`
141//! into the copy is refused: a merge removes nothing of the thread it adds
142//! to, and the copy gave the call up. And a copy
143//! taken while a resume is in flight holds that
144//! [submission](Thread::submission) unconfirmed, and runs and merges once
145//! the application has reconciled it.
146//!
147//! [`Thread::merge_messages_from`] says what the merge takes, leaves and
148//! refuses, and [`merge_messages`] has the rules for the list. In short:
149//! messages are merged by id, this thread's copy of a message stays, and a
150//! tool result is put behind the message that holds its call. State is not
151//! merged. Pending interrupts, a resume submission and unanswered tool calls
152//! are not carried over: a thread that has any is not merged until it has
153//! settled them itself.
154
155mod merge;
156mod pending;
157mod run;
158mod snapshot;
159
160pub use merge::{MergeReport, merge_messages};
161pub use pending::{ResumeSubmission, SubmissionStatus};
162pub use run::{
163 AbortHandle, MessageUpdate, ReasoningUpdate, RunDiagnostic, RunEnd, RunReport, RunStream,
164 RunSummary, SubagentUpdate, Update,
165};
166pub use snapshot::ThreadSnapshot;
167
168use std::collections::HashSet;
169use std::sync::Arc;
170
171use crate::client::{
172 agent::RemoteAgent,
173 apply::{Applier, Subagent},
174 error::{Error, Result},
175 transport::Transport,
176};
177use crate::{
178 Context, Event, Interrupt, Message, MessageId, ReasoningMessage, RunId, ThreadId, Tool,
179 ToolCallId,
180};
181use serde::de::DeserializeOwned;
182use serde_json::Value;
183
184#[cfg(not(target_family = "wasm"))]
185type Observer = Box<dyn FnMut(&Event) + Send>;
186#[cfg(target_family = "wasm")]
187type Observer = Box<dyn FnMut(&Event)>;
188#[cfg(not(target_family = "wasm"))]
189type IdGenerator = Box<dyn FnMut() -> Result<String> + Send>;
190#[cfg(target_family = "wasm")]
191type IdGenerator = Box<dyn FnMut() -> Result<String>>;
192
193/// A typed view of current raw state could not be constructed.
194#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
195#[error("state does not match the expected type: {message}")]
196pub struct StateViewError {
197 /// The deserializer's explanation.
198 pub message: String,
199}
200
201/// One local conversation with an agent. `T` only supplies communication.
202/// `S` is the current state view, defaulting to JSON.
203pub struct Thread<T, S = Value> {
204 agent: RemoteAgent<Arc<T>>,
205 thread_id: ThreadId,
206 applier: Applier,
207 state: core::result::Result<S, StateViewError>,
208 tools: Vec<Tool>,
209 context: Vec<Context>,
210 forwarded_props: Value,
211 protocol_version: Option<String>,
212 verify: bool,
213 interrupts: Vec<Interrupt>,
214 decided_interrupt_tool_call_ids: HashSet<ToolCallId>,
215 /// The tool messages `abandon_tool_call` made, by id: stand-ins for a
216 /// result, which a merge tells from one by this record and not by what
217 /// the message says.
218 abandoned: HashSet<MessageId>,
219 submission: Option<ResumeSubmission>,
220 run_ids: HashSet<RunId>,
221 next_run_id: Option<RunId>,
222 last_run_end: Option<RunEnd>,
223 active_run_id: Option<RunId>,
224 observer: Option<Observer>,
225 id_generator: IdGenerator,
226 diagnostic_limit: usize,
227}
228
229impl<T, S: std::fmt::Debug> std::fmt::Debug for Thread<T, S> {
230 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
231 f.debug_struct("Thread")
232 .field("thread_id", &self.thread_id)
233 .field("state", &self.state)
234 .field("messages", &self.messages())
235 .field("interrupts", &self.interrupts)
236 .finish_non_exhaustive()
237 }
238}
239
240impl<T: Transport> Thread<T> {
241 /// Creates an empty JSON conversation. No request is sent.
242 pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self {
243 Self::from_shared(Arc::new(transport), thread_id)
244 }
245
246 pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
247 ThreadBuilder::from_shared(transport, thread_id)
248 .build()
249 .expect("an empty JSON object always deserializes to Value")
250 }
251}
252
253impl<T, S> Thread<T, S> {
254 /// Configures a conversation and validates its initial typed state at `build`.
255 pub fn builder(transport: T, thread_id: impl Into<ThreadId>) -> ThreadBuilder<T, S>
256 where
257 T: Transport,
258 {
259 ThreadBuilder::new(transport, thread_id)
260 }
261 /// The remote conversation identifier.
262 pub fn thread_id(&self) -> &ThreadId {
263 &self.thread_id
264 }
265 /// The current assembled conversation, reasoning and activity messages
266 /// included. A run sends all of it but the activity messages.
267 ///
268 /// To draw the conversation without the agent's reasoning, leave that
269 /// role out: `messages().iter().filter(|m| m.role() != Role::Reasoning)`.
270 pub fn messages(&self) -> &[Message] {
271 self.applier.messages()
272 }
273 /// The current typed view. A remote type mismatch invalidates the old view.
274 pub fn state(&self) -> core::result::Result<&S, StateViewError> {
275 self.state.as_ref().map_err(Clone::clone)
276 }
277 /// The latest raw state, even when it does not fit `S`.
278 pub fn raw_state(&self) -> &Value {
279 self.applier.state()
280 }
281 /// The reasoning messages in [`messages`](Self::messages), oldest first:
282 /// a view over that list, for a UI that draws reasoning in a pane of its
283 /// own.
284 pub fn reasoning(&self) -> impl Iterator<Item = &ReasoningMessage> {
285 self.applier.reasoning()
286 }
287 /// Pending human input. Dispatching a response does not remove it.
288 pub fn interrupts(&self) -> &[Interrupt] {
289 &self.interrupts
290 }
291 /// Unconfirmed or currently in-flight response submission.
292 pub fn submission(&self) -> Option<&ResumeSubmission> {
293 self.submission.as_ref()
294 }
295 /// Announced subagents across runs.
296 pub fn subagents(&self) -> &[Subagent] {
297 self.applier.subagents()
298 }
299 /// Find a subagent by invocation ID.
300 pub fn subagent(&self, id: &crate::SubagentRunId) -> Option<&Subagent> {
301 self.applier.subagent(id)
302 }
303 /// The current materialized protocol data.
304 pub fn applier(&self) -> &Applier {
305 &self.applier
306 }
307 /// The low-level agent using the same owned transport handle.
308 pub fn agent(&self) -> &RemoteAgent<Arc<T>> {
309 &self.agent
310 }
311 /// How the last request went: what its stream's [`Update::Done`] carried.
312 /// Dropping a dispatched request before its stream ends records `Aborted`,
313 /// unless the last run from the requested one on had already ended: that
314 /// ending stays.
315 pub fn last_run_end(&self) -> Option<&RunEnd> {
316 self.last_run_end.as_ref()
317 }
318 /// Append a client-owned message, rejecting an ID already in the transcript.
319 pub fn push_message(&mut self, message: Message) -> Result<()> {
320 if self.applier.message(message.id()).is_some() {
321 return Err(Error::Request(format!(
322 "duplicate message ID {}",
323 message.id()
324 )));
325 }
326 self.append_local_message(message);
327 Ok(())
328 }
329 fn append_local_message(&mut self, message: Message) {
330 if let Message::Assistant(assistant) = &message {
331 for call in assistant.tool_calls.iter().flatten() {
332 self.decided_interrupt_tool_call_ids.remove(&call.id);
333 }
334 }
335 self.applier.push_message(message);
336 }
337 /// Tools offered on subsequent runs. AG-UI does not discover tools.
338 pub fn set_tools(&mut self, tools: impl Into<Vec<Tool>>) {
339 self.tools = tools.into();
340 }
341 /// Context sent on subsequent runs.
342 pub fn set_context(&mut self, context: impl Into<Vec<Context>>) {
343 self.context = context.into();
344 }
345 /// Passthrough request properties supplied by the application.
346 pub fn set_forwarded_props(&mut self, props: impl Into<Value>) {
347 self.forwarded_props = props.into();
348 }
349 /// Configure protocol ordering verification. Identity and resume safety checks stay enabled.
350 pub fn set_verify(&mut self, verify: bool) {
351 self.verify = verify;
352 }
353 /// Retained diagnostics per request. Excess errors are still yielded as updates.
354 pub fn set_diagnostic_limit(&mut self, limit: usize) {
355 self.diagnostic_limit = limit;
356 }
357 /// Reserve an explicit run ID. Reuse is rejected during request preflight.
358 pub fn set_next_run_id(&mut self, id: impl Into<RunId>) {
359 self.next_run_id = Some(id.into());
360 }
361 /// Remove the event observer.
362 pub fn clear_event_observer(&mut self) {
363 self.observer = None;
364 }
365
366 /// Replace the synchronous read-only observer. Called once per checked
367 /// event, before chunk normalization and ordering verification. Queue slow
368 /// work in the application.
369 #[cfg(not(target_family = "wasm"))]
370 pub fn on_event(&mut self, observer: impl FnMut(&Event) + Send + 'static) {
371 self.observer = Some(Box::new(observer));
372 }
373 /// Replace the local read-only observer on wasm.
374 #[cfg(target_family = "wasm")]
375 pub fn on_event(&mut self, observer: impl FnMut(&Event) + 'static) {
376 self.observer = Some(Box::new(observer));
377 }
378}
379
380impl<T, S: DeserializeOwned> Thread<T, S> {
381 /// Validates local JSON before atomically replacing both raw and typed state.
382 pub fn set_state(&mut self, state: impl Into<Value>) -> Result<()> {
383 let state = state.into();
384 let typed = S::deserialize(&state).map_err(Error::State)?;
385 self.applier.set_state(state);
386 self.state = Ok(typed);
387 Ok(())
388 }
389}
390
391impl<T: Transport, S> Thread<T, S> {
392 /// Prepare a user turn. Pending decisions and ambiguous submissions are checked
393 /// before changing history. Dispatch and history insertion occur on first poll.
394 ///
395 /// # Errors
396 ///
397 /// Like [`send_message`](Self::send_message), [`run`](Self::run) and
398 /// [`resume_many`](Self::resume_many), this refuses a request the
399 /// conversation is not ready for, before anything is sent:
400 /// [`Error::UnansweredToolCalls`] names the tool calls still awaiting a
401 /// result, [`Error::PendingInterrupts`] the interrupts still awaiting an
402 /// answer, and [`Error::Request`] says why in any other case.
403 pub fn send(&mut self, text: impl Into<String>) -> Result<RunStream<'_, T, S>> {
404 self.preflight(None, None)?;
405 let id = self.fresh_id(false)?;
406 self.start(Some(Message::user(id, text.into())), None)
407 }
408 /// Prepare a message of any role, rejecting existing IDs.
409 pub fn send_message(&mut self, message: Message) -> Result<RunStream<'_, T, S>> {
410 if self.applier.message(message.id()).is_some() {
411 return Err(Error::Request(format!(
412 "duplicate message ID {}",
413 message.id()
414 )));
415 }
416 self.preflight(None, Some(&message))?;
417 self.start(Some(message), None)
418 }
419 /// Prepare a run with the existing conversation and no new message.
420 pub fn run(&mut self) -> Result<RunStream<'_, T, S>> {
421 self.preflight(None, None)?;
422 self.start(None, None)
423 }
424 fn fresh_id(&mut self, run: bool) -> Result<String> {
425 for _ in 0..64 {
426 let id = (self.id_generator)()?;
427 let exists = if run {
428 self.run_ids.contains(&RunId::new(&id))
429 } else {
430 self.applier.message(&MessageId::new(&id)).is_some()
431 };
432 if !id.is_empty() && !exists {
433 return Ok(id);
434 }
435 }
436 Err(Error::Request(
437 "ID generator repeatedly returned empty or existing IDs".into(),
438 ))
439 }
440}
441
442/// Configures a thread. `build` checks history IDs and typed initial state.
443pub struct ThreadBuilder<T, S = Value> {
444 transport: Arc<T>,
445 thread_id: ThreadId,
446 messages: Vec<Message>,
447 state: Value,
448 tools: Vec<Tool>,
449 context: Vec<Context>,
450 forwarded_props: Value,
451 protocol_version: Option<String>,
452 verify: bool,
453 diagnostic_limit: usize,
454 id_generator: IdGenerator,
455 marker: std::marker::PhantomData<fn() -> S>,
456}
457impl<T, S> std::fmt::Debug for ThreadBuilder<T, S> {
458 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
459 f.debug_struct("ThreadBuilder")
460 .field("thread_id", &self.thread_id)
461 .finish_non_exhaustive()
462 }
463}
464impl<T, S> ThreadBuilder<T, S> {
465 /// Configure a thread using any transport.
466 pub fn new(transport: T, thread_id: impl Into<ThreadId>) -> Self
467 where
468 T: Transport,
469 {
470 Self::from_shared(Arc::new(transport), thread_id)
471 }
472 pub(crate) fn from_shared(transport: Arc<T>, thread_id: impl Into<ThreadId>) -> Self {
473 Self {
474 transport,
475 thread_id: thread_id.into(),
476 messages: Vec::new(),
477 state: serde_json::json!({}),
478 tools: Vec::new(),
479 context: Vec::new(),
480 forwarded_props: Value::Null,
481 protocol_version: Some(crate::input::PROTOCOL_VERSION.to_owned()),
482 verify: true,
483 diagnostic_limit: 100,
484 id_generator: Box::new(random_id),
485 marker: std::marker::PhantomData,
486 }
487 }
488 /// Existing conversation, checked for duplicate IDs at build time.
489 #[must_use]
490 pub fn messages(mut self, messages: impl Into<Vec<Message>>) -> Self {
491 self.messages = messages.into();
492 self
493 }
494 /// Initial JSON, deserialized to `S` at build time.
495 #[must_use]
496 pub fn state(mut self, state: impl Into<Value>) -> Self {
497 self.state = state.into();
498 self
499 }
500 /// Tools offered on each run.
501 #[must_use]
502 pub fn tools(mut self, tools: impl Into<Vec<Tool>>) -> Self {
503 self.tools = tools.into();
504 self
505 }
506 /// Ambient context supplied on each run.
507 #[must_use]
508 pub fn context(mut self, context: impl Into<Vec<Context>>) -> Self {
509 self.context = context.into();
510 self
511 }
512 /// Application-specific request properties.
513 #[must_use]
514 pub fn forwarded_props(mut self, props: impl Into<Value>) -> Self {
515 self.forwarded_props = props.into();
516 self
517 }
518 /// Declares this SDK's version in each request. Use `None` only for a
519 /// known legacy peer whose request parser predates `protocolVersion`.
520 #[must_use]
521 pub fn protocol_version(mut self, version: Option<String>) -> Self {
522 self.protocol_version = version;
523 self
524 }
525 /// Toggle optional protocol ordering verification.
526 #[must_use]
527 pub fn verify(mut self, verify: bool) -> Self {
528 self.verify = verify;
529 self
530 }
531 /// Maximum diagnostics retained in each report (default 100).
532 #[must_use]
533 pub fn diagnostic_limit(mut self, limit: usize) -> Self {
534 self.diagnostic_limit = limit;
535 self
536 }
537 /// Inject deterministic IDs for tests. Empty or duplicate IDs are retried up to 64 times.
538 #[cfg(not(target_family = "wasm"))]
539 #[must_use]
540 pub fn id_generator(mut self, mut generator: impl FnMut() -> String + Send + 'static) -> Self {
541 self.id_generator = Box::new(move || Ok(generator()));
542 self
543 }
544 /// Inject a local deterministic ID generator on wasm.
545 #[cfg(target_family = "wasm")]
546 #[must_use]
547 pub fn id_generator(mut self, mut generator: impl FnMut() -> String + 'static) -> Self {
548 self.id_generator = Box::new(move || Ok(generator()));
549 self
550 }
551 /// Validate state and history, then construct the conversation.
552 pub fn build(self) -> Result<Thread<T, S>>
553 where
554 S: DeserializeOwned,
555 {
556 unique(
557 self.messages.iter().map(|message| message.id().as_str()),
558 "message",
559 )?;
560 let state = S::deserialize(&self.state).map_err(Error::State)?;
561 Ok(Thread {
562 agent: RemoteAgent::new(self.transport),
563 thread_id: self.thread_id,
564 applier: Applier::new()
565 .with_messages(self.messages)
566 .with_state(self.state),
567 state: Ok(state),
568 tools: self.tools,
569 context: self.context,
570 forwarded_props: self.forwarded_props,
571 protocol_version: self.protocol_version,
572 verify: self.verify,
573 interrupts: Vec::new(),
574 decided_interrupt_tool_call_ids: HashSet::new(),
575 abandoned: HashSet::new(),
576 submission: None,
577 run_ids: HashSet::new(),
578 next_run_id: None,
579 last_run_end: None,
580 active_run_id: None,
581 observer: None,
582 id_generator: self.id_generator,
583 diagnostic_limit: self.diagnostic_limit,
584 })
585 }
586}
587
588pub(crate) fn random_id() -> Result<String> {
589 let mut bytes = [0u8; 16];
590 getrandom::getrandom(&mut bytes)
591 .map_err(|error| Error::Config(format!("could not obtain ID entropy: {error}")))?;
592 use std::fmt::Write;
593 let mut id = String::with_capacity(32);
594 for byte in bytes {
595 write!(id, "{byte:02x}").expect("writing to String cannot fail");
596 }
597 Ok(id)
598}
599
600/// Rejects a list that holds an id twice.
601///
602/// Not an empty id: AG-UI 1.0 makes every identifier an opaque string and
603/// its schema sets no minimum length, so the empty string is an id like any
604/// other, and a run may leave one.
605fn unique<'a>(ids: impl IntoIterator<Item = &'a str>, label: &str) -> Result<()> {
606 let mut seen = HashSet::new();
607 for id in ids {
608 if !seen.insert(id) {
609 return Err(Error::Snapshot(format!(
610 "{label} ID {id:?} is held more than once"
611 )));
612 }
613 }
614 Ok(())
615}