ag-ui 1.0.0

Rust SDK for AG-UI 1.0 with protocol types, SSE, a server runtime for hosting agents, and a client runtime for consuming them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Two threads on one conversation: bringing together what each of them added.

use std::collections::{HashMap, HashSet, hash_map::Entry};

use crate::client::error::{Error, Result};
use crate::client::transport::Transport;
use crate::{Message, MessageId, ToolCallId};

use super::Thread;

/// What [`Thread::merge_messages_from`] added to a thread, and what it left
/// as it was.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
#[must_use = "`differing` names the messages of the other thread that were not taken"]
pub struct MergeReport {
    /// The messages added, in the order the other thread holds them. Each is
    /// in [`Thread::messages`] now: a tool result behind the message that
    /// holds its call, every other message at the end.
    pub added: Vec<MessageId>,
    /// The ids both threads hold as different messages. This thread's copy
    /// was kept, and the other thread's was not taken. Empty when the two
    /// threads started from the same messages and each only added its own.
    pub differing: Vec<MessageId>,
    /// The tool messages of the other thread that
    /// [`abandon_tool_call`](Thread::abandon_tool_call) made there for a call
    /// this thread holds an answer to, in the order the other thread holds
    /// them. Each stood in for a result the other thread never got, and was
    /// not taken: the call keeps the answer this thread has.
    pub superseded: Vec<MessageId>,
}

/// Merges two copies of one conversation's messages, by message id.
///
/// AG-UI 1.0 makes a message id unique within its thread, so two lists that
/// hold the same conversation agree on which message is which. They differ in
/// what each holds that the other lacks, and that is all this adds: the
/// result is `ours` with the messages of `theirs` it does not hold.
///
/// | A message | In the result |
/// | --- | --- |
/// | only `ours` holds | as it is, in the order `ours` has them |
/// | both hold, the copies equal | once, in the place `ours` gives it |
/// | both hold, the copies different | the copy of `ours`, in the place `ours` gives it |
/// | only `theirs` holds | after every message of `ours`, in the order `theirs` has them |
/// | a tool result, of either list, whose call a message before it holds | directly behind that message, after the tool results and activity messages already behind it |
///
/// Two lists that started from the same messages and each grew at the end
/// therefore merge to: the common start, what `ours` added, what `theirs`
/// added. The result depends on the two lists and nothing else, so the same
/// arguments always give the same list. It is not symmetric: with the
/// arguments swapped, the other list's additions come first and the other
/// list's copies are the ones kept.
///
/// No message of `ours` is changed or left out, so a message one list saw
/// complete and the other only in part stays as `ours` has it. Pass as `ours`
/// the list whose copies should stand.
///
/// The last row is the one rule about a role. A tool result is placed by the
/// call it answers and not by where a list kept it, so that in the result it
/// follows the message that holds its call whichever way the two lists were
/// built: one that arrived after other messages and was kept at the end is
/// put behind its call, in `ours` as in `theirs`. A list whose results stand
/// behind their calls already comes through in its own order. The message
/// that holds a call is the assistant message with that call among its
/// `tool_calls`. Where several hold the id, as with a provider that numbers
/// its calls from zero in every turn, it is the newest one whose call has no
/// result yet, or the newest one when each has. A result whose call no
/// earlier message holds stays in the order of its list.
///
/// A reasoning message stays in front of the reply it led to because the
/// order of each list is kept, and an activity message is merged like any
/// other.
///
/// The function reads ids and nothing else. It does not know which
/// conversation a list belongs to, and it does not refuse a tool call both
/// lists answered: both results are in the list. Use it for a view of two
/// threads while either is still running. For the thread that will send the
/// next request, [`Thread::merge_messages_from`] applies the same rules and
/// checks what a list cannot say.
///
/// Each list is expected to hold an id once, as [`Thread::messages`] does. Of
/// a repeated id the first message is kept.
///
/// ```
/// use ag_ui::Message;
/// use ag_ui::client::merge_messages;
///
/// let start = vec![Message::user("u-1", "Hello"), Message::assistant("a-1", "Hi")];
/// // Two copies of the conversation, each of which went on by itself.
/// let mut ours = start.clone();
/// ours.push(Message::user("u-2", "Write the report"));
/// ours.push(Message::assistant("a-2", "Here it is."));
/// let mut theirs = start.clone();
/// theirs.push(Message::user("u-3", "What time is it?"));
/// theirs.push(Message::assistant("a-3", "Noon."));
///
/// let merged = merge_messages(&ours, &theirs);
/// let ids: Vec<_> = merged.iter().map(|message| message.id().as_str()).collect();
/// assert_eq!(ids, ["u-1", "a-1", "u-2", "a-2", "u-3", "a-3"]);
/// ```
#[must_use]
pub fn merge_messages(ours: &[Message], theirs: &[Message]) -> Vec<Message> {
    merge(ours, theirs, &HashSet::new()).messages
}

/// One merge, worked out before anything is changed.
struct Merge {
    messages: Vec<Message>,
    added: Vec<MessageId>,
    differing: Vec<MessageId>,
    /// Tool calls that had a result before the merge added another from the
    /// other list: the call, the result that was there, and the one added.
    answered_twice: Vec<(ToolCallId, MessageId, MessageId)>,
}

/// Merges `theirs` into `ours`, leaving out the messages of `theirs` named in
/// `skip`.
fn merge(ours: &[Message], theirs: &[Message], skip: &HashSet<&MessageId>) -> Merge {
    let mut merged = Merge {
        messages: Vec::with_capacity(ours.len() + theirs.len()),
        added: Vec::new(),
        differing: Vec::new(),
        answered_twice: Vec::new(),
    };
    // The calls some message of the result holds, so that a result with no
    // such message is placed without a search.
    let mut issued = HashSet::new();
    let mut held: HashMap<&MessageId, &Message> = HashMap::with_capacity(ours.len());
    for message in ours {
        if let Entry::Vacant(first) = held.entry(message.id()) {
            first.insert(message);
            place(&mut merged.messages, &mut issued, message);
        }
    }
    let mut met = HashSet::with_capacity(theirs.len());
    for message in theirs {
        if !met.insert(message.id()) || skip.contains(message.id()) {
            continue;
        }
        if let Some(mine) = held.get(message.id()) {
            if *mine != message {
                merged.differing.push(message.id().clone());
            }
            continue;
        }
        merged.added.push(message.id().clone());
        if let Some((call, answer)) = place(&mut merged.messages, &mut issued, message) {
            merged
                .answered_twice
                .push((call, answer, message.id().clone()));
        }
    }
    merged
}

/// Adds `message` to `messages` the way a client adds one it receives: a tool
/// result behind the message that holds its call, anything else at the end.
/// For a result whose call already had one, returns the call and that result.
fn place<'a>(
    messages: &mut Vec<Message>,
    issued: &mut HashSet<&'a ToolCallId>,
    message: &'a Message,
) -> Option<(ToolCallId, MessageId)> {
    issued.extend(calls_of(message));
    let call = match message {
        Message::Tool(result) if issued.contains(&result.tool_call_id) => &result.tool_call_id,
        _ => {
            messages.push(message.clone());
            return None;
        }
    };
    let (at, answer) = place_of_result(messages, call);
    let answer = answer.map(|index| (call.clone(), messages[index].id().clone()));
    messages.insert(at, message.clone());
    answer
}

/// The ids of the tool calls a message holds.
fn calls_of(message: &Message) -> impl Iterator<Item = &ToolCallId> {
    let calls = match message {
        Message::Assistant(assistant) => assistant.tool_calls.as_deref(),
        _ => None,
    };
    calls.into_iter().flatten().map(|call| &call.id)
}

/// Where a result for `call` goes in `messages`, and the index of the result
/// the call already has there, if it has one.
///
/// The reference client's placement for a `TOOL_CALL_RESULT`
/// (`client/src/apply/default.ts`): behind the newest message holding the
/// call that has no result for it yet, or behind the newest holder when each
/// has one; then past the tool and activity messages directly behind that
/// message, so results keep the order they came in. With no holder, the end.
fn place_of_result(messages: &[Message], call: &ToolCallId) -> (usize, Option<usize>) {
    let behind = |holder: usize| {
        let mut at = holder + 1;
        while matches!(
            messages.get(at),
            Some(Message::Tool(_) | Message::Activity(_))
        ) {
            at += 1;
        }
        at
    };
    // Read from the end: the first result met after a holder is the one
    // standing closest behind it.
    let mut answer = None;
    let mut newest = None;
    for (index, message) in messages.iter().enumerate().rev() {
        match message {
            Message::Tool(result) if result.tool_call_id == *call => answer = Some(index),
            _ if calls_of(message).any(|id| id == call) => {
                if answer.is_none() {
                    return (behind(index), None);
                }
                newest.get_or_insert((index, answer.take()));
            }
            _ => {}
        }
    }
    match newest {
        Some((holder, answer)) => (behind(holder), answer),
        None => (messages.len(), None),
    }
}

/// Providers may reuse a tool-call ID in a later assistant message.
#[derive(Debug, PartialEq, Eq, Hash)]
struct IssuedCall<'a> {
    assistant_id: &'a MessageId,
    call_id: &'a ToolCallId,
}

/// Index each tool result by its message ID. A result before its call has no entry.
fn calls_by_result(messages: &[Message]) -> HashMap<&MessageId, IssuedCall<'_>> {
    #[derive(Default)]
    struct Issuers<'a> {
        latest: Option<&'a MessageId>,
        unanswered: Vec<&'a MessageId>,
    }

    let mut issuers: HashMap<&ToolCallId, Issuers<'_>> = HashMap::new();
    let mut results = HashMap::new();
    for message in messages {
        for call_id in calls_of(message) {
            let history = issuers.entry(call_id).or_default();
            history.latest = Some(message.id());
            history.unanswered.push(message.id());
        }
        if let Message::Tool(result) = message {
            let call_id = &result.tool_call_id;
            let history = issuers.entry(call_id).or_default();
            // Answer the newest outstanding call first, then fall back to the
            // latest issuer if every occurrence already has a result.
            if let Some(assistant_id) = history.unanswered.pop().or(history.latest) {
                results.insert(
                    &result.id,
                    IssuedCall {
                        assistant_id,
                        call_id,
                    },
                );
            }
        }
    }
    results
}

/// Ids, for an error message.
fn list<'a>(ids: impl Iterator<Item = &'a str>) -> String {
    ids.collect::<Vec<_>>().join(", ")
}

impl<T: Transport, S> Thread<T, S> {
    /// 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](super#two-runs-at-once). Nothing is sent, and `other` is
    /// not changed. Draw the conversation again afterwards, as after
    /// [`Update::Messages`](super::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`](Thread::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`](Thread::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`](Thread::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`](Thread::raw_state) of both threads and
    /// call [`set_state`](Thread::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`](Thread::resume), a tool message or
    /// [`abandon_tool_call`](Thread::abandon_tool_call). Both threads were at
    /// rest, so the merged one can take the next request, and
    /// [`send`](Thread::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](Thread::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());
    /// # Ok::<(), ag_ui::client::Error>(())
    /// ```
    ///
    /// # 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.
    pub fn merge_messages_from<U: Transport, R>(
        &mut self,
        other: &Thread<U, R>,
    ) -> Result<MergeReport> {
        if self.thread_id != other.thread_id {
            return Err(Error::Merge(format!(
                "thread {:?} is another conversation than thread {:?}",
                other.thread_id.as_str(),
                self.thread_id.as_str()
            )));
        }
        self.at_rest("this thread")?;
        other.at_rest("the other thread")?;

        // A stand-in the other thread made for a call this thread holds an
        // answer to is left out: the call has its answer here. Told from a
        // result by the record `abandon_tool_call` keeps, not by what the
        // message says.
        let answered: HashSet<_> = calls_by_result(self.messages()).into_values().collect();
        let incoming_calls = calls_by_result(other.messages());
        let superseded: Vec<&MessageId> = other
            .messages()
            .iter()
            .map(Message::id)
            .filter(|id| {
                other.abandoned.contains(*id)
                    && self.applier.message(id).is_none()
                    && incoming_calls
                        .get(*id)
                        .is_some_and(|call| answered.contains(call))
            })
            .collect();
        let skip: HashSet<&MessageId> = superseded.iter().copied().collect();

        let merged = merge(self.messages(), other.messages(), &skip);
        if let Some((call, here, there)) = merged
            .answered_twice
            .iter()
            .find(|(_, here, _)| self.applier.message(here).is_some())
        {
            // Giving a call up here does not undo a result there, and a merge
            // changes and removes nothing of this thread's: the result is
            // merged the other way.
            if self.abandoned.contains(here) {
                return Err(Error::Merge(format!(
                    "tool call {call} was given up on this thread, with message {here}, and has \
                     a result on the other thread, message {there}: merge this thread into the \
                     one that holds the result"
                )));
            }
            return Err(Error::Merge(format!(
                "tool call {call} has a result on each thread, message {here} on this one and \
                 message {there} on the other"
            )));
        }

        // A conflicting retained message can discard the assistant's call
        // while its result is still added. Check the settled transcript
        // before mutating either the messages or the thread's bookkeeping.
        let merged_calls = calls_by_result(&merged.messages);
        for id in &merged.added {
            let Some(call) = incoming_calls.get(id) else {
                continue;
            };
            if merged_calls.get(id) != Some(call) {
                return Err(Error::Merge(format!(
                    "tool result {id} would no longer answer call {} on message {}",
                    call.call_id, call.assistant_id
                )));
            }
        }

        // A retained message can also displace the incoming result itself.
        // Project the decisions first: an interrupt may already have settled
        // that call, even if no tool message survives for it.
        let mut decided = self.decided_interrupt_tool_call_ids.clone();
        for id in &merged.added {
            let Some(message) = other.applier.message(id) else {
                continue;
            };
            for call in calls_of(message) {
                if other.decided_interrupt_tool_call_ids.contains(call)
                    && other.applier.tool_call_holder(call) == Some(id)
                {
                    decided.insert(call.clone());
                } else {
                    decided.remove(call);
                }
            }
        }
        let pending = self.unanswered_tool_calls_in(&merged.messages, &decided);
        if !pending.is_empty() {
            return Err(Error::Merge(format!(
                "the merged history would have unanswered tool calls {}",
                list(pending.iter().map(ToolCallId::as_str))
            )));
        }

        let superseded = superseded.into_iter().cloned().collect();
        self.decided_interrupt_tool_call_ids = decided;
        self.abandoned.extend(
            merged
                .added
                .iter()
                .filter(|id| other.abandoned.contains(*id))
                .cloned(),
        );
        self.applier = std::mem::take(&mut self.applier).with_messages(merged.messages);
        self.run_ids.extend(other.run_ids.iter().cloned());
        let announced: Vec<_> = other
            .subagents()
            .iter()
            .filter(|subagent| self.subagent(&subagent.run_id).is_none())
            .cloned()
            .collect();
        if !announced.is_empty() {
            let mut subagents = self.subagents().to_vec();
            subagents.extend(announced);
            let interrupts = self.applier.interrupts().to_vec();
            self.applier.restore_auxiliary(subagents, interrupts);
        }
        Ok(MergeReport {
            added: merged.added,
            differing: merged.differing,
            superseded,
        })
    }

    /// Refuses a merge while this thread owes something only it can settle.
    fn at_rest(&self, which: &str) -> Result<()> {
        let owes = if self.active_run_id.is_some() {
            "has a request in flight, and is merged once its stream has ended".to_owned()
        } else if self.submission.is_some() {
            "holds an unconfirmed resume submission, which is reconciled with the server before \
             the thread is merged"
                .to_owned()
        } else if !self.interrupts.is_empty() {
            format!(
                "is paused on interrupts {}, which are answered on the thread that holds them \
                 before it is merged",
                list(
                    self.interrupts
                        .iter()
                        .map(|interrupt| interrupt.id.as_str())
                )
            )
        } else {
            let calls = self.unanswered_tool_calls();
            if calls.is_empty() {
                return Ok(());
            }
            format!(
                "has unanswered tool calls {}, which are answered or abandoned on the thread \
                 that holds them before it is merged",
                list(calls.iter().map(ToolCallId::as_str))
            )
        };
        Err(Error::Merge(format!("{which} {owes}")))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AssistantMessage, ToolCall};

    #[test]
    fn reused_call_ids_match_outstanding_calls_before_falling_back_to_the_latest_issuer() {
        let issue = |id: &str| {
            Message::Assistant(AssistantMessage {
                id: id.into(),
                tool_calls: Some(vec![ToolCall::new("c", "lookup", "{}")]),
                ..Default::default()
            })
        };
        let result = |id: &str| Message::tool(id, "c", "answer");
        let messages = [
            result("early"),
            issue("a"),
            issue("b"),
            result("first"),
            result("second"),
            result("extra"),
        ];
        let calls = calls_by_result(&messages);
        let issuer = |result: &str| {
            calls
                .get(&MessageId::new(result))
                .map(|call| call.assistant_id.as_str())
        };

        assert_eq!(issuer("early"), None);
        assert_eq!(issuer("first"), Some("b"));
        assert_eq!(issuer("second"), Some("a"));
        assert_eq!(issuer("extra"), Some("b"));
    }
}