ag-ui 0.1.0

An independent Rust SDK for the AG-UI protocol: protocol types and wire encoding, a server runtime for hosting an agent, and a client runtime for consuming one. Not affiliated with the AG-UI protocol organisation.
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
//! What an agent is handed for one run.

use std::future::Future;

use crate::{
    Context, Event, Message, MessageId, ResumeEntry, RunAgentInput, RunId, StepName,
    TextMessageRole, ThreadId, Tool, ToolCallId,
};
use futures_channel::mpsc;
use futures_util::future::{Either, select};
use serde_json::Value;

use crate::serve::agent::AgentState;
use crate::serve::cancel::{CancellationToken, Cancelled};
use crate::serve::emit::{
    EventReceiver, EventSink, MessageHandle, ReasoningHandle, StepGuard, ToolCallHandle,
};
use crate::serve::error::{Error, Result};
use crate::serve::state::RunState;
use crate::serve::transform::TransformerChain;

/// The request, the state, the event sink and the cancellation flag — one
/// run's whole world.
///
/// An agent gets `&mut RunContext<S>` and emits through it. Every emitter takes
/// `&mut self`, which is what makes two overlapping messages a borrow-check
/// error rather than a protocol violation discovered by a confused frontend.
///
/// ```
/// # use ag_ui::RunAgentInput;
/// # use ag_ui::serve::RunContext;
/// # let (mut ctx, _events) = RunContext::<()>::new(RunAgentInput::new("thread-1", "run-1"))?;
/// assert_eq!(ctx.thread_id().as_str(), "thread-1");
/// assert!(ctx.messages().is_empty());
///
/// let mut message = ctx.assistant_message()?;
/// message.delta("Hello")?;
/// message.end()?;
/// # Ok::<(), ag_ui::serve::Error>(())
/// ```
#[derive(Debug)]
pub struct RunContext<S> {
    input: RunAgentInput,
    state: RunState<S>,
    sink: EventSink,
    next_message: u64,
    next_tool_call: u64,
}

impl<S: AgentState> RunContext<S> {
    /// Builds a context and the receiving half of its event stream.
    ///
    /// This is the harness for unit-testing an [`Agent`](crate::serve::Agent) without
    /// the run driver: call the agent's body, then assert on
    /// [`EventReceiver::drain`]. Nothing emits `RUN_STARTED` here — that is the
    /// driver's job, and skipping it lets a test exercise one method in
    /// isolation.
    pub fn new(input: RunAgentInput) -> Result<(Self, EventReceiver)> {
        let (tx, rx) = mpsc::unbounded();
        let sink = EventSink::new(tx, TransformerChain::new(), CancellationToken::new());
        let state = decode_state(&input.state)?;
        Ok((Self::from_parts(input, state, sink), EventReceiver::new(rx)))
    }

    /// Assembles a context from an already-decoded state.
    ///
    /// The run driver decodes first so that a state that does not fit `S` is
    /// reported through the sink it still owns, as a `RUN_ERROR`.
    pub(crate) fn from_parts(input: RunAgentInput, state: S, sink: EventSink) -> Self {
        Self {
            input,
            state: RunState::new(state),
            sink,
            next_message: 0,
            next_tool_call: 0,
        }
    }

    /// The typed state, as of the last publish.
    pub fn state(&self) -> &S {
        self.state.get()
    }

    /// The typed state, mutably. Nothing is emitted until you call
    /// [`publish_state`](Self::publish_state).
    pub fn state_mut(&mut self) -> &mut S {
        self.state.get_mut()
    }

    /// Replaces the state and publishes the change.
    ///
    /// The first publish of a run is a `STATE_SNAPSHOT`; later ones are a
    /// `STATE_DELTA` unless the patch would be no smaller than the snapshot.
    /// See [`StateManager`](crate::serve::StateManager).
    pub fn set_state(&mut self, state: &S) -> Result<()> {
        self.state.replace(&mut self.sink, state)
    }

    /// Mutates the state in place and publishes the change.
    ///
    /// ```
    /// # use ag_ui::RunAgentInput;
    /// # use ag_ui::serve::RunContext;
    /// # use serde::{Deserialize, Serialize};
    /// #[derive(Default, Serialize, Deserialize)]
    /// struct Draft { revision: u32 }
    ///
    /// # let (mut ctx, _events) = RunContext::<Draft>::new(RunAgentInput::new("t", "r"))?;
    /// ctx.update_state(|draft| draft.revision += 1)?;
    /// assert_eq!(ctx.state().revision, 1);
    /// # Ok::<(), ag_ui::serve::Error>(())
    /// ```
    pub fn update_state(&mut self, update: impl FnOnce(&mut S)) -> Result<()> {
        update(self.state.get_mut());
        self.publish_state()
    }

    /// Publishes whatever [`state_mut`](Self::state_mut) left behind.
    ///
    /// A no-op when nothing changed since the last publish.
    pub fn publish_state(&mut self) -> Result<()> {
        self.state.publish(&mut self.sink)
    }
}

impl<S> RunContext<S> {
    /// The whole request, for anything the accessors do not cover.
    pub fn input(&self) -> &RunAgentInput {
        &self.input
    }

    /// The conversation this run belongs to.
    pub fn thread_id(&self) -> &ThreadId {
        &self.input.thread_id
    }

    /// This run's id.
    pub fn run_id(&self) -> &RunId {
        &self.input.run_id
    }

    /// The run that spawned this one, for nested agents.
    pub fn parent_run_id(&self) -> Option<&RunId> {
        self.input.parent_run_id.as_ref()
    }

    /// Conversation history, oldest first.
    pub fn messages(&self) -> &[Message] {
        &self.input.messages
    }

    /// What the user said last, as text.
    ///
    /// The turn an agent is almost always answering. Non-text parts of a
    /// multimodal message are dropped — see
    /// [`UserContent::to_text`](https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/message/enum.UserContent.html#method.to_text); reach into
    /// [`RunContext::messages`] directly if the images matter.
    ///
    /// `None` when the history holds no user message at all, which is distinct
    /// from a user who sent an empty one.
    ///
    /// ```
    /// # use ag_ui::{RunAgentInput, Message};
    /// # use ag_ui::serve::RunContext;
    /// let mut input = RunAgentInput::new("thread-1", "run-1");
    /// input.messages = vec![Message::user("msg-1", "add milk")];
    /// let (ctx, _events) = RunContext::<()>::new(input)?;
    ///
    /// assert_eq!(ctx.last_user_text().as_deref(), Some("add milk"));
    /// # Ok::<(), ag_ui::serve::Error>(())
    /// ```
    pub fn last_user_text(&self) -> Option<String> {
        self.input
            .messages
            .iter()
            .rev()
            .find_map(|message| match message {
                Message::User(user) => Some(user.content.to_text()),
                _ => None,
            })
    }

    /// Tools the client is offering for this run.
    pub fn tools(&self) -> &[Tool] {
        &self.input.tools
    }

    /// One offered tool by name.
    pub fn tool(&self, name: &str) -> Option<&Tool> {
        self.input.tools.iter().find(|tool| tool.name == name)
    }

    /// Ambient context entries.
    pub fn context(&self) -> &[Context] {
        &self.input.context
    }

    /// Arbitrary passthrough properties, opaque to the protocol.
    pub fn forwarded_props(&self) -> &Value {
        &self.input.forwarded_props
    }

    /// Answers to the interrupts a previous run paused on.
    ///
    /// Empty unless this request resumes a paused run.
    pub fn resume(&self) -> &[ResumeEntry] {
        self.input.resume.as_deref().unwrap_or_default()
    }

    /// The answer to one interrupt, by its [`Interrupt::id`].
    ///
    /// [`Interrupt::id`]: https://kimsoungryoul.github.io/ag-ui-rust/api/ag_ui/outcome/struct.Interrupt.html#structfield.id
    pub fn resume_for(&self, interrupt_id: &str) -> Option<&ResumeEntry> {
        self.resume()
            .iter()
            .find(|entry| entry.interrupt_id == interrupt_id)
    }

    /// Whether this request resumes a paused run.
    pub fn is_resume(&self) -> bool {
        self.input.is_resume()
    }

    /// Whether the run has been cancelled.
    pub fn is_cancelled(&self) -> bool {
        self.sink.cancel_token().is_cancelled()
    }

    /// [`Error::Cancelled`] once the run is cancelled, for use with `?`.
    pub fn check_cancelled(&self) -> Result<()> {
        if self.is_cancelled() {
            return Err(Error::Cancelled);
        }
        Ok(())
    }

    /// A handle a transport can trip on client disconnect.
    pub fn cancel_token(&self) -> CancellationToken {
        self.sink.cancel_token().clone()
    }

    /// Resolves once the run is cancelled.
    pub fn cancelled(&self) -> Cancelled {
        self.sink.cancel_token().cancelled()
    }

    /// Races `future` against cancellation, returning `None` if cancellation
    /// won.
    ///
    /// The way to make a long model call interruptible:
    ///
    /// ```
    /// # use ag_ui::RunAgentInput;
    /// # use ag_ui::serve::{Error, RunContext};
    /// # let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
    /// # rt.block_on(async {
    /// # let (ctx, _events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
    /// let answer = ctx
    ///     .until_cancelled(async { "the model's reply" })
    ///     .await
    ///     .ok_or(Error::Cancelled)?;
    /// assert_eq!(answer, "the model's reply");
    /// # Ok::<(), Error>(())
    /// # })?;
    /// # Ok::<(), Error>(())
    /// ```
    /// Deliberately not an `async fn`: that would capture `&self` in the
    /// returned future, and a future holding a borrow of the run context is
    /// only `Send` if the context is `Sync` — which it is not, since a
    /// transformer only has to be `Send`.
    pub fn until_cancelled<F: Future>(&self, future: F) -> impl Future<Output = Option<F::Output>> {
        let cancelled = self.cancelled();
        async move {
            futures_util::pin_mut!(future, cancelled);
            match select(future, cancelled).await {
                Either::Left((output, _)) => Some(output),
                Either::Right(((), _)) => None,
            }
        }
    }

    /// Emits an event as-is — the escape hatch under the typed emitters.
    ///
    /// Everything the handles emit goes through here, so a raw event is
    /// transformed and verified like any other.
    pub fn emit(&mut self, event: Event) -> Result<()> {
        self.sink.emit(event)
    }

    /// A fresh message id, unique within the run.
    ///
    /// Derived from the run id and a counter rather than a UUID: the protocol
    /// asks for opaque strings, this crate takes no `uuid` dependency, and a
    /// deterministic id makes a recorded stream diffable. Pass your own id to
    /// [`message_with_id`](Self::message_with_id) when you need one.
    pub fn new_message_id(&mut self) -> MessageId {
        self.next_message += 1;
        MessageId::new(format!("{}-msg-{}", self.id_prefix(), self.next_message))
    }

    /// A fresh tool call id, unique within the run.
    pub fn new_tool_call_id(&mut self) -> ToolCallId {
        self.next_tool_call += 1;
        ToolCallId::new(format!("{}-call-{}", self.id_prefix(), self.next_tool_call))
    }

    fn id_prefix(&self) -> &str {
        if self.input.run_id.is_empty() {
            "run"
        } else {
            self.input.run_id.as_str()
        }
    }

    /// Opens an assistant message under a fresh id — `TEXT_MESSAGE_START`.
    pub fn assistant_message(&mut self) -> Result<MessageHandle<'_, S>> {
        self.message(TextMessageRole::Assistant)
    }

    /// Opens a message with the given role under a fresh id.
    pub fn message(&mut self, role: TextMessageRole) -> Result<MessageHandle<'_, S>> {
        let id = self.new_message_id();
        self.message_with_id(id, role)
    }

    /// Opens a message under an id you choose.
    pub fn message_with_id(
        &mut self,
        id: impl Into<MessageId>,
        role: TextMessageRole,
    ) -> Result<MessageHandle<'_, S>> {
        // Two disjoint field borrows, not a borrow of the context: the handle
        // reaches the state without being able to open a second block.
        MessageHandle::start(&mut self.sink, &mut self.state, id.into(), role)
    }

    /// Emits a whole assistant message — start, content, end — and returns its
    /// id.
    pub fn say(&mut self, text: impl Into<String>) -> Result<MessageId> {
        let mut message = self.message(TextMessageRole::Assistant)?;
        message.delta(text)?;
        let id = message.id().clone();
        message.end()?;
        Ok(id)
    }

    /// Opens a reasoning block under a fresh id — `REASONING_START`.
    pub fn reasoning(&mut self) -> Result<ReasoningHandle<'_, S>> {
        let id = self.new_message_id();
        self.reasoning_with_id(id)
    }

    /// Opens a reasoning block under an id you choose.
    pub fn reasoning_with_id(
        &mut self,
        id: impl Into<MessageId>,
    ) -> Result<ReasoningHandle<'_, S>> {
        ReasoningHandle::start(&mut self.sink, &mut self.state, id.into())
    }

    /// Emits a whole reasoning block in one call and returns its id.
    pub fn think(&mut self, text: impl Into<String>) -> Result<MessageId> {
        let mut reasoning = self.reasoning()?;
        reasoning.delta(text)?;
        let id = reasoning.id().clone();
        reasoning.end()?;
        Ok(id)
    }

    /// Opens a call to `name` under a fresh id — `TOOL_CALL_START`.
    pub fn tool_call(&mut self, name: &str) -> Result<ToolCallHandle<'_, S>> {
        let id = self.new_tool_call_id();
        self.tool_call_with_id(id, name)
    }

    /// Opens a call to `name` under an id you choose.
    pub fn tool_call_with_id(
        &mut self,
        id: impl Into<ToolCallId>,
        name: &str,
    ) -> Result<ToolCallHandle<'_, S>> {
        let id = id.into();
        let result_message_id = self.new_message_id();
        ToolCallHandle::start(
            &mut self.sink,
            &mut self.state,
            id,
            name,
            None,
            result_message_id,
        )
    }

    /// Opens a named step — `STEP_STARTED`.
    ///
    /// The returned guard dereferences to this context, and emits
    /// `STEP_FINISHED` when it drops.
    pub fn step(&mut self, name: impl Into<StepName>) -> Result<StepGuard<'_, S>> {
        StepGuard::start(self, name.into())
    }

    /// Whether a terminal event has already gone out.
    pub(crate) fn is_terminated(&self) -> bool {
        self.sink.is_terminated()
    }

    /// Recovers the sink so the run driver can emit the terminal event through
    /// the same transformers and the same verifier the agent used.
    pub(crate) fn into_sink(self) -> EventSink {
        self.sink
    }
}

/// Reads `RunAgentInput::state` as `S`.
///
/// An absent state — JSON `null`, or the empty object clients send for "no
/// state yet" — becomes `S::default()` rather than a deserialization error, so
/// a stateless agent (`State = ()`) works against every client.
pub(crate) fn decode_state<S: AgentState>(value: &Value) -> Result<S> {
    let empty = value.is_null() || value.as_object().is_some_and(serde_json::Map::is_empty);
    if empty {
        return Ok(S::default());
    }
    Ok(serde_json::from_value(value.clone())?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};
    use serde_json::json;

    #[derive(Debug, Default, PartialEq, Serialize, Deserialize)]
    struct Counter {
        clicks: u32,
    }

    fn context<S: AgentState>(input: RunAgentInput) -> (RunContext<S>, EventReceiver) {
        RunContext::new(input).expect("state should decode")
    }

    #[test]
    fn ids_are_derived_from_the_run_id() {
        let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "run-7"));
        assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-1");
        assert_eq!(ctx.new_message_id().as_str(), "run-7-msg-2");
        assert_eq!(ctx.new_tool_call_id().as_str(), "run-7-call-1");
    }

    #[test]
    fn the_last_user_turn_is_the_one_returned_and_absence_is_not_emptiness() {
        let (ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
        assert_eq!(ctx.last_user_text(), None, "no user message is not \"\"");

        let mut input = RunAgentInput::new("t", "r");
        input.messages = vec![
            Message::user("m-1", "add milk"),
            Message::assistant("m-2", "milk it is"),
            Message::user("m-3", "and bread"),
        ];
        let (ctx, _events) = context::<()>(input);
        assert_eq!(ctx.last_user_text().as_deref(), Some("and bread"));
    }

    #[test]
    fn an_empty_state_object_decodes_to_the_default() {
        let mut input = RunAgentInput::new("t", "r");
        input.state = json!({});
        let (ctx, _events) = context::<Counter>(input);
        assert_eq!(ctx.state(), &Counter::default());
    }

    #[test]
    fn typed_state_comes_from_the_input() {
        let mut input = RunAgentInput::new("t", "r");
        input.state = json!({"clicks": 3});
        let (ctx, _events) = context::<Counter>(input);
        assert_eq!(ctx.state().clicks, 3);
    }

    #[test]
    fn a_state_that_does_not_fit_is_an_error() {
        let mut input = RunAgentInput::new("t", "r");
        input.state = json!({"clicks": "three"});
        let error = RunContext::<Counter>::new(input).expect_err("should not decode");
        assert!(matches!(error, Error::Json(_)), "{error}");
    }

    #[test]
    fn resume_entries_are_addressable_by_interrupt_id() {
        let mut input = RunAgentInput::new("t", "r");
        input.resume = Some(vec![ResumeEntry::resolved("i-1", json!(true))]);
        let (ctx, _events) = context::<()>(input);
        assert!(ctx.is_resume());
        assert_eq!(ctx.resume().len(), 1);
        assert!(ctx.resume_for("i-1").is_some());
        assert!(ctx.resume_for("i-2").is_none());
    }

    #[test]
    fn a_cancelled_run_fails_every_emit() {
        let (mut ctx, _events) = context::<()>(RunAgentInput::new("t", "r"));
        ctx.cancel_token().cancel();
        assert!(ctx.is_cancelled());
        let error = ctx.say("too late").expect_err("emit should fail");
        assert!(error.is_cancelled(), "{error}");
    }

    #[test]
    fn a_dropped_receiver_disconnects_the_run() {
        let (mut ctx, events) = context::<()>(RunAgentInput::new("t", "r"));
        drop(events);
        let error = ctx.say("nobody home").expect_err("emit should fail");
        assert!(error.is_disconnected(), "{error}");
    }
}