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
//! Cancellation stops a run, whether or not the agent thought about it.

#![cfg(feature = "server")]

use ag_ui::server::{Agent, CancellationToken, Error, Result, RunContext, Runner};
use ag_ui::{Event, EventType, RunAgentInput, RunOutcome};
use futures_util::StreamExt as _;

fn input() -> RunAgentInput {
    RunAgentInput::new("t", "r")
}

fn text(events: &[Event]) -> Vec<&str> {
    events
        .iter()
        .filter_map(|event| match event {
            Event::TextMessageContent(payload) => Some(payload.delta.as_str()),
            _ => None,
        })
        .collect()
}

#[tokio::test]
async fn cancelling_mid_run_stops_the_agent_at_its_next_emit() {
    struct Chatty;

    impl Agent for Chatty {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            ctx.say("one")?;
            // Stand in for the transport noticing the client disconnected.
            ctx.cancellation_token().cancel();
            ctx.say("two")?;
            ctx.say("three")?;
            Ok(RunOutcome::Success)
        }
    }

    let events: Vec<Event> = Runner::new(Chatty).run(input()).collect().await;

    assert_eq!(text(&events), ["one"]);
    let Event::RunFinished(finished) = events.last().expect("a terminal event") else {
        panic!("expected RUN_FINISHED, got {:?}", events.last());
    };
    assert_eq!(finished.outcome, Some(RunOutcome::Cancelled));
}

#[tokio::test]
async fn a_run_cancelled_before_it_starts_emits_nothing_but_the_brackets() {
    struct Chatty;

    impl Agent for Chatty {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            ctx.say("never")?;
            Ok(RunOutcome::Success)
        }
    }

    let token = CancellationToken::new();
    token.cancel();

    let events: Vec<Event> = Runner::new(Chatty)
        .cancellation(token)
        .run(input())
        .collect()
        .await;

    assert_eq!(
        events.iter().map(Event::event_type).collect::<Vec<_>>(),
        [EventType::RunStarted, EventType::RunFinished]
    );
    let Event::RunFinished(finished) = events.last().unwrap() else {
        unreachable!()
    };
    assert_eq!(finished.outcome, Some(RunOutcome::Cancelled));
}

#[tokio::test]
async fn cancellation_wakes_an_agent_that_is_waiting() {
    struct Waiter;

    impl Agent for Waiter {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            ctx.say("working")?;
            // A stand-in for a model call that never returns.
            let answer = ctx.until_cancelled(std::future::pending::<&str>()).await;
            assert!(answer.is_none(), "cancellation should have won the race");
            ctx.say("unreachable")?;
            Ok(RunOutcome::Success)
        }
    }

    let runner = Runner::new(Waiter);
    let token = runner.cancellation_token();
    let mut stream = Box::pin(runner.run(input()));

    let first = stream.next().await.expect("a first event");
    assert_eq!(first.event_type(), EventType::RunStarted);

    // The agent is parked inside `until_cancelled` by now.
    token.cancel();

    let rest: Vec<Event> = stream.collect().await;

    assert_eq!(text(&rest), ["working"]);
    let Event::RunFinished(finished) = rest.last().expect("a terminal event") else {
        panic!("expected RUN_FINISHED, got {:?}", rest.last());
    };
    assert_eq!(finished.outcome, Some(RunOutcome::Cancelled));
}

#[tokio::test]
async fn an_agent_can_check_cancellation_itself() {
    struct Polite;

    impl Agent for Polite {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            for chunk in ["a", "b", "c"] {
                if ctx.is_cancelled() {
                    return Err(Error::Cancelled);
                }
                ctx.say(chunk)?;
                ctx.cancellation_token().cancel();
            }
            Ok(RunOutcome::Success)
        }
    }

    let events: Vec<Event> = Runner::new(Polite).run(input()).collect().await;

    assert_eq!(text(&events), ["a"]);
    assert!(matches!(
        events.last(),
        Some(Event::RunFinished(finished)) if finished.outcome == Some(RunOutcome::Cancelled)
    ));
}

// ---- cancelling with something open ---------------------------------------
//
// AG-UI 1.0, "Cancelled runs": a producer MUST close what the run opened —
// messages, tool calls, steps, subagents — before the RUN_FINISHED that
// cancels it. The handles close on `Drop` even after cancellation, and the
// driver closes the subagents nothing else will.

/// Runs `agent` to the end and checks the stream ends `RUN_FINISHED`
/// cancelled, with nothing left open along the way.
async fn cancelled_run(agent: impl Agent<State = ()>) -> Vec<Event> {
    let events: Vec<Event> = Runner::new(agent).run(input()).collect().await;
    let Some(Event::RunFinished(finished)) = events.last() else {
        panic!("expected RUN_FINISHED, got {events:#?}");
    };
    assert_eq!(finished.outcome, Some(RunOutcome::Cancelled), "{events:#?}");
    // Replayed through a fresh verifier, so "well formed" does not rest on the
    // run's own verifier having been consulted.
    #[cfg(feature = "verify")]
    {
        let mut verifier = ag_ui::server::EventVerifier::new();
        for event in &events {
            verifier
                .observe(event)
                .unwrap_or_else(|error| panic!("{error}\n{events:#?}"));
        }
    }
    events
}

fn types(events: &[Event]) -> Vec<EventType> {
    events.iter().map(Event::event_type).collect()
}

#[tokio::test]
async fn cancelling_mid_message_closes_the_message_and_finishes_cancelled() {
    struct InterruptedMessage;

    impl Agent for InterruptedMessage {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut message = ctx.assistant_message()?;
            message.delta("partial")?;
            token.cancel();
            message.delta("never sent")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(InterruptedMessage).await;
    assert_eq!(text(&events), ["partial"]);
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::RunFinished,
        ]
    );
}

#[tokio::test]
async fn cancelling_mid_tool_call_closes_the_call_and_finishes_cancelled() {
    struct InterruptedCall;

    impl Agent for InterruptedCall {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut call = ctx.tool_call("search")?;
            call.args(r#"{"q":"#)?;
            token.cancel();
            call.args(r#""rust"}"#)?;
            call.result("never sent")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(InterruptedCall).await;
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,
            EventType::ToolCallArgs,
            EventType::ToolCallEnd,
            EventType::RunFinished,
        ]
    );
}

#[tokio::test]
async fn a_result_after_cancellation_closes_the_call_but_is_not_sent() {
    struct LateResult;

    impl Agent for LateResult {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut call = ctx.tool_call("search")?;
            call.args("{}")?;
            token.cancel();
            call.result("the answer")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(LateResult).await;
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ToolCallStart,
            EventType::ToolCallArgs,
            EventType::ToolCallEnd,
            EventType::RunFinished,
        ]
    );
}

#[tokio::test]
async fn cancelling_mid_reasoning_closes_both_halves_and_finishes_cancelled() {
    struct InterruptedThought;

    impl Agent for InterruptedThought {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut reasoning = ctx.reasoning()?;
            reasoning.delta("first")?;
            token.cancel();
            reasoning.delta("second")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(InterruptedThought).await;
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::ReasoningStart,
            EventType::ReasoningMessageStart,
            EventType::ReasoningMessageContent,
            EventType::ReasoningMessageEnd,
            EventType::ReasoningEnd,
            EventType::RunFinished,
        ]
    );
}

#[tokio::test]
async fn cancelling_mid_step_closes_the_step_and_finishes_cancelled() {
    struct InterruptedStep;

    impl Agent for InterruptedStep {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut outer = ctx.step("plan")?;
            let mut inner = outer.step("search")?;
            inner.say("looking")?;
            token.cancel();
            inner.say("never sent")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(InterruptedStep).await;
    assert_eq!(text(&events), ["looking"]);
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::StepStarted,
            EventType::StepStarted,
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::StepFinished,
            EventType::StepFinished,
            EventType::RunFinished,
        ]
    );
}

#[tokio::test]
async fn cancelling_inside_a_subagent_closes_it_and_finishes_cancelled() {
    struct InterruptedSubagents;

    impl Agent for InterruptedSubagents {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let token = ctx.cancellation_token();
            let mut planner = ctx.subagent("planner")?;
            let mut estimator = planner.subagent("estimator")?;
            let mut message = estimator.assistant_message()?;
            message.delta("About a")?;
            token.cancel();
            message.delta(" day")?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(InterruptedSubagents).await;
    assert_eq!(
        types(&events),
        [
            EventType::RunStarted,
            EventType::SubagentStarted,
            EventType::SubagentStarted,
            EventType::TextMessageStart,
            EventType::TextMessageContent,
            EventType::TextMessageEnd,
            EventType::SubagentError,
            EventType::SubagentError,
            EventType::RunFinished,
        ]
    );
    // Innermost first, and each one says why it ended. A cancelled
    // invocation neither succeeded nor is waiting, and an error naming the
    // cancellation is the only ending the schema has for that.
    let closed: Vec<(&str, Option<&str>)> = events
        .iter()
        .filter_map(|event| match event {
            Event::SubagentError(error) => {
                Some((error.subagent_run_id.as_str(), error.code.as_deref()))
            }
            _ => None,
        })
        .collect();
    assert_eq!(
        closed,
        [
            ("r-sub-2", Some("CANCELLED")),
            ("r-sub-1", Some("CANCELLED"))
        ]
    );
}

#[tokio::test]
async fn a_subagent_can_still_be_closed_explicitly_after_cancellation() {
    struct ClosesItsOwn;

    impl Agent for ClosesItsOwn {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let mut worker = ctx.subagent("worker")?;
            worker.say("halfway")?;
            worker.cancellation_token().cancel();
            worker.fail_with_code("stopped by the user", "USER_STOP")?;
            ctx.check_cancelled()?;
            Ok(RunOutcome::Success)
        }
    }

    let events = cancelled_run(ClosesItsOwn).await;
    let errors: Vec<Option<&str>> = events
        .iter()
        .filter_map(|event| match event {
            Event::SubagentError(error) => Some(error.code.as_deref()),
            _ => None,
        })
        .collect();
    assert_eq!(errors, [Some("USER_STOP")], "closed once, by the agent");
}

#[tokio::test]
async fn an_agent_that_reports_cancelled_itself_has_its_subagents_closed_too() {
    struct StopsItself;

    impl Agent for StopsItself {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let mut worker = ctx.subagent("worker")?;
            worker.say("over budget")?;
            drop(worker);
            Ok(RunOutcome::Cancelled)
        }
    }

    let events = cancelled_run(StopsItself).await;
    assert_eq!(
        types(&events)[events.len() - 2..],
        [EventType::SubagentError, EventType::RunFinished]
    );
}

/// Without the `verify` feature too: the sink itself refuses anything after
/// the terminal event, so a run can never put events past its end on the wire.
#[tokio::test]
async fn nothing_is_sent_after_the_run_ended() {
    struct TalksPastTheEnd;

    impl Agent for TalksPastTheEnd {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            ctx.emit(Event::run_finished_success("t", "r"))?;
            let late = ctx.say("too late");
            assert!(late.is_err(), "an emit after RUN_FINISHED must fail");
            Ok(RunOutcome::Success)
        }
    }

    let events: Vec<Event> = Runner::new(TalksPastTheEnd).run(input()).collect().await;
    assert_eq!(
        types(&events),
        [EventType::RunStarted, EventType::RunFinished]
    );
}

#[tokio::test]
async fn dropping_the_stream_mid_run_disconnects_the_agent() {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    struct Waiting(Arc<AtomicBool>);
    struct DropMarker(Arc<AtomicBool>);

    impl Drop for DropMarker {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    impl Agent for Waiting {
        type State = ();

        async fn run(&self, ctx: &mut RunContext<()>) -> Result<RunOutcome> {
            let _guard = DropMarker(self.0.clone());
            ctx.say("waiting")?;
            std::future::pending().await
        }
    }

    let dropped = Arc::new(AtomicBool::new(false));
    let runner = Runner::new(Waiting(dropped.clone()));
    let mut stream = Box::pin(runner.run(input()));
    tokio::time::timeout(std::time::Duration::from_secs(5), async {
        loop {
            let event = stream.next().await.expect("the waiting run must stay open");
            if matches!(event, Event::TextMessageContent(_)) {
                return;
            }
        }
    })
    .await
    .expect("the waiting agent should start streaming");
    assert!(!dropped.load(Ordering::SeqCst));
    drop(stream);
    assert!(
        dropped.load(Ordering::SeqCst),
        "the pending agent future was retained"
    );
}