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
//! State: snapshots, patches, and what happens when a patch does not apply.

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

use ag_ui::client::apply::{Applier, Changed};
use ag_ui::client::transport::ReplayTransport;
use ag_ui::client::{Error, MessageChangeKind, Thread, Update};
use ag_ui::{Event, PatchOperation};
use futures_util::StreamExt;
use serde::Deserialize;
use serde_json::json;

#[test]
fn a_snapshot_replaces_the_state_and_a_delta_patches_it() {
    let mut applier = Applier::new();
    assert_eq!(applier.state(), &json!({}));

    let changed = applier
        .apply(&Event::state_snapshot(
            json!({ "items": ["a"], "count": 1 }),
        ))
        .expect("applies");
    assert_eq!(changed, Changed::State);

    applier
        .apply(&Event::state_delta(vec![
            PatchOperation::add("/items/-", json!("b")),
            PatchOperation::replace("/count", json!(2)),
            PatchOperation::add("/nested", json!({ "ok": true })),
        ]))
        .expect("applies");

    assert_eq!(
        applier.state(),
        &json!({ "items": ["a", "b"], "count": 2, "nested": { "ok": true } })
    );

    // A snapshot after a delta replaces everything, including keys the delta
    // added.
    applier
        .apply(&Event::state_snapshot(json!({ "count": 9 })))
        .expect("applies");
    assert_eq!(applier.state(), &json!({ "count": 9 }));
}

#[test]
fn a_patch_that_cannot_apply_is_an_error_and_changes_nothing() {
    let mut applier = Applier::new().with_state(json!({ "count": 1 }));

    let error = applier
        .apply(&Event::state_delta(vec![PatchOperation::replace(
            "/missing/deeply",
            json!(2),
        )]))
        .expect_err("replacing a path that does not exist must fail");

    assert!(
        matches!(&error, Error::Patch { target, .. } if target == "state"),
        "unexpected error: {error:?}"
    );
    assert!(error.to_string().contains("state patch failed"));
    // The state is exactly what it was: no half-applied patch.
    assert_eq!(applier.state(), &json!({ "count": 1 }));
}

#[test]
fn a_failed_operation_rolls_back_the_ones_before_it() {
    // RFC 6902 patches are all-or-nothing. The first operation here succeeds
    // and must still be undone when the second fails.
    let mut applier = Applier::new().with_state(json!({ "count": 1 }));

    applier
        .apply(&Event::state_delta(vec![
            PatchOperation::add("/added", json!(true)),
            PatchOperation::test("/count", json!(99)),
        ]))
        .expect_err("the test operation should fail");

    assert_eq!(applier.state(), &json!({ "count": 1 }));
}

#[test]
fn a_malformed_json_pointer_is_rejected_before_anything_is_mutated() {
    let mut applier = Applier::new().with_state(json!({ "count": 1 }));

    let error = applier
        .apply(&Event::state_delta(vec![PatchOperation::add(
            "not-a-pointer",
            json!(1),
        )]))
        .expect_err("a pointer must start with a slash");

    assert!(matches!(
        error,
        Error::InvalidPatchDocument { target, .. } if target == "state"
    ));
    assert_eq!(applier.state(), &json!({ "count": 1 }));
}

#[test]
fn a_delta_whose_value_the_producer_dropped_applies_as_null() {
    // `JSON.stringify` drops a key holding `undefined`, so a JavaScript agent
    // diffing state over such a key emits `{"op":"add","path":"/draft"}` with no
    // `value` at all. It has to arrive off the wire: building the operation in
    // Rust cannot reproduce the omission. Rejecting it took the whole
    // STATE_DELTA down, and in an SSE stream a failed event is a failed run.
    let event: Event = serde_json::from_str(
        r#"{"type":"STATE_DELTA","delta":[{"op":"add","path":"/draft"},{"op":"replace","path":"/count"}]}"#,
    )
    .expect("a producer's dropped value must not fail the event");

    let mut applier = Applier::new().with_state(json!({ "count": 1 }));
    applier.apply(&event).expect("applies");

    // Null, which is what the JavaScript patch libraries would have written —
    // not the key left untouched and not the key removed.
    assert_eq!(applier.state(), &json!({ "draft": null, "count": null }));
}

#[test]
fn an_activity_patch_that_cannot_apply_is_an_error_naming_the_activity() {
    let mut applier = Applier::new();
    let mut content = ag_ui::JsonObject::new();
    content.insert("status".into(), json!("running"));
    applier
        .apply(&Event::activity_snapshot("act-1", "web_search", content))
        .expect("applies");

    let error = applier
        .apply(&Event::activity_delta(
            "act-1",
            "web_search",
            vec![PatchOperation::replace("/nope", json!(1))],
        ))
        .expect_err("replacing a missing key must fail");

    assert!(
        matches!(&error, Error::Patch { target, .. } if target == "activity act-1"),
        "unexpected error: {error:?}"
    );

    // And the activity kept the content it had.
    let ag_ui::Message::Activity(activity) = &applier.messages()[0] else {
        panic!("expected an activity message");
    };
    assert_eq!(activity.content["status"], json!("running"));
}

#[test]
fn an_activity_patch_that_replaces_the_whole_document_is_refused() {
    // RFC 6902 lets an operation target the root, but an activity's content is
    // an object and a number cannot be one. Applying it used to succeed and
    // leave the activity holding `{}` — the content silently gone, with
    // `Ok(..)` returned and nothing to tell a view it had happened.
    let mut applier = Applier::new();
    let mut content = ag_ui::JsonObject::new();
    content.insert("percent".into(), json!(40));
    applier
        .apply(&Event::activity_snapshot("act-1", "progress", content))
        .expect("applies");

    let error = applier
        .apply(&Event::activity_delta(
            "act-1",
            "progress",
            vec![PatchOperation::replace("", json!("wiped"))],
        ))
        .expect_err("replacing the root with a string must fail");

    assert!(
        matches!(&error, Error::Patch { target, .. } if target == "activity act-1"),
        "unexpected error: {error:?}"
    );
    assert!(error.to_string().contains("a string"), "{error}");

    let ag_ui::Message::Activity(activity) = &applier.messages()[0] else {
        panic!("expected an activity message");
    };
    assert_eq!(
        activity.content["percent"],
        json!(40),
        "the activity must keep the content it had"
    );
}

#[test]
fn an_activity_patch_may_replace_the_whole_document_with_another_object() {
    // The other side of that check: targeting the root is legal RFC 6902 and
    // an object is a content an activity can hold, so this one lands. Refusing
    // every root-targeting operation would be the easy over-correction.
    let mut applier = Applier::new();
    let mut content = ag_ui::JsonObject::new();
    content.insert("percent".into(), json!(40));
    applier
        .apply(&Event::activity_snapshot("act-1", "progress", content))
        .expect("applies");

    applier
        .apply(&Event::activity_delta(
            "act-1",
            "progress",
            vec![PatchOperation::replace("", json!({ "percent": 100 }))],
        ))
        .expect("replacing the root with an object is fine");

    let ag_ui::Message::Activity(activity) = &applier.messages()[0] else {
        panic!("expected an activity message");
    };
    assert_eq!(activity.content["percent"], json!(100));
}

#[test]
fn an_activity_snapshot_with_replace_false_leaves_an_existing_activity_as_it_stands() {
    // AG-UI 1.0: `replace: false` asks the consumer to leave the existing
    // message alone, content and `activityType`; "it is not a merge". The
    // snapshot's own values apply only when it creates the message.
    let keep = |activity_type: &str, content: serde_json::Value| {
        let serde_json::Value::Object(content) = content else {
            unreachable!()
        };
        Event::ActivitySnapshot(ag_ui::ActivitySnapshotEvent {
            replace: false,
            ..ag_ui::ActivitySnapshotEvent::new("act-1", activity_type, content)
        })
    };
    let mut applier = Applier::new();
    let created = applier
        .apply(&keep(
            "web_search",
            json!({ "query": "weather", "hits": 0 }),
        ))
        .expect("applies");
    assert!(matches!(created, Changed::Message(_)));

    let unchanged = applier
        .apply(&keep("file_search", json!({ "hits": 3, "extra": true })))
        .expect("applies");
    assert_eq!(unchanged, Changed::Nothing);

    let ag_ui::Message::Activity(activity) = &applier.messages()[0] else {
        panic!("expected an activity message");
    };
    assert_eq!(applier.messages().len(), 1);
    assert_eq!(activity.activity_type, "web_search");
    assert_eq!(
        serde_json::Value::Object(activity.content.clone()),
        json!({ "query": "weather", "hits": 0 })
    );
}

#[test]
fn an_activity_delta_gives_the_activity_its_own_type() {
    // AG-UI 1.0, `ACTIVITY_DELTA`: "The delta's `activityType` replaces the
    // message's — a delta MAY retype the activity it amends".
    let mut applier = Applier::new();
    let mut content = ag_ui::JsonObject::new();
    content.insert("found".into(), json!(0));
    applier
        .apply(&Event::activity_snapshot("act-1", "web_search", content))
        .expect("applies");
    let activity_type = |applier: &Applier| {
        let ag_ui::Message::Activity(activity) = &applier.messages()[0] else {
            panic!("expected an activity message");
        };
        (
            activity.activity_type.clone(),
            activity.content["found"].clone(),
        )
    };

    applier
        .apply(&Event::activity_delta(
            "act-1",
            "search_results",
            vec![PatchOperation::replace("/found", json!(3))],
        ))
        .expect("applies");
    assert_eq!(
        activity_type(&applier),
        ("search_results".to_owned(), json!(3))
    );

    // A patch that does not apply changes nothing, the type included.
    applier
        .apply(&Event::activity_delta(
            "act-1",
            "web_search",
            vec![PatchOperation::replace("/absent", json!(1))],
        ))
        .expect_err("the path does not resolve");
    assert_eq!(
        activity_type(&applier),
        ("search_results".to_owned(), json!(3))
    );
}

#[test]
fn an_activity_delta_with_no_activity_to_patch_is_skipped_and_reported() {
    // AG-UI 1.0: a delta naming a message that does not exist, or one that is
    // not an activity, is skipped with a warning. It creates nothing.
    let mut applier = Applier::new();
    applier
        .apply(&Event::text_message_start(
            "msg-1",
            ag_ui::TextMessageRole::Assistant,
        ))
        .expect("applies");
    let before = applier.messages().to_vec();

    for target in ["never-created", "msg-1"] {
        let error = applier
            .apply(&Event::activity_delta(
                target,
                "web_search",
                vec![PatchOperation::replace("/found", json!(3))],
            ))
            .expect_err("there is no activity to patch");
        assert!(
            matches!(&error, Error::Patch { target: named, .. } if *named == format!("activity {target}")),
            "{error:?}"
        );
        assert!(error.to_string().contains("was skipped"), "{error}");
        assert_eq!(applier.messages(), before, "{target}");
    }
}

#[tokio::test]
async fn a_thread_reports_a_skipped_activity_delta_without_failing_the_run() {
    use ag_ui::client::RunEnd;
    let transport = ReplayTransport::new([
        Event::run_started("t", "r"),
        Event::activity_delta(
            "never-created",
            "web_search",
            vec![PatchOperation::replace("/found", json!(3))],
        ),
        Event::run_finished_success("t", "r"),
    ])
    .matching_requests();
    let mut thread = Thread::new(transport, "t");
    let report = thread.run().unwrap().collect_report().await;
    assert_eq!(report.end, RunEnd::Success { result: None });
    let kinds: Vec<_> = report.diagnostics.iter().map(|d| d.kind).collect();
    assert_eq!(kinds, ["patch"], "{:?}", report.diagnostics);
    assert!(thread.messages().is_empty());
}

#[derive(Clone, Debug, Deserialize, PartialEq)]
struct Counter {
    count: u32,
}

#[test]
fn the_state_can_be_read_as_a_caller_defined_type() {
    let mut applier = Applier::new();
    applier
        .apply(&Event::state_snapshot(json!({ "count": 3 })))
        .expect("applies");

    assert_eq!(
        applier.state_as::<Counter>().expect("deserializes"),
        Counter { count: 3 }
    );

    applier
        .apply(&Event::state_snapshot(json!({ "count": "three" })))
        .expect("applies");
    let error = applier
        .state_as::<Counter>()
        .expect_err("a string is not a u32");
    assert!(matches!(error, Error::State(_)), "unexpected: {error:?}");
    // The raw state is still exactly what the agent sent.
    assert_eq!(applier.state(), &json!({ "count": "three" }));
}

#[tokio::test]
async fn a_thread_reports_a_failed_patch_and_keeps_the_state_it_had() {
    let transport = ReplayTransport::new([
        Event::run_started("thread-1", "run-1"),
        Event::state_snapshot(json!({ "count": 1 })),
        // A move removes its source before noticing the missing destination.
        // Rejecting the entire delta must restore the source and the earlier add.
        Event::state_delta(vec![
            PatchOperation::add("/temporary", true),
            PatchOperation::mv("/count", "/missing/count"),
        ]),
        Event::state_delta(vec![PatchOperation::replace("/count", json!(2))]),
        Event::run_finished_success("thread-1", "run-1"),
    ])
    .matching_requests();
    let mut thread = Thread::<_>::new(transport, "thread-1");

    let updates: Vec<_> = thread.send("go").unwrap().collect().await;
    let errors: Vec<String> = updates
        .iter()
        .filter_map(|update| match update {
            Update::Error(error) => Some(error.to_string()),
            _ => None,
        })
        .collect();

    assert_eq!(errors.len(), 1, "expected exactly one failure: {errors:?}");
    assert!(errors[0].contains("state patch failed"));

    // The run carried on, and the later delta still applied.
    assert_eq!(thread.raw_state(), &json!({ "count": 2 }));
    let states: Vec<_> = updates
        .iter()
        .filter(|update| matches!(update, Update::State(_)))
        .collect();
    assert_eq!(states.len(), 2);
}

/// An agent that does a tool's work while the call is open publishes state
/// between `TOOL_CALL_START` and `TOOL_CALL_END`. `STATE_*` is unordered, so
/// that is a well-formed stream and the client folds it like any other — the
/// update arrives while the call is still open, which is the point of sending
/// it there.
#[tokio::test]
async fn state_published_inside_an_open_tool_call_applies_like_any_other() {
    let transport = ReplayTransport::new([
        Event::run_started("thread-1", "run-1"),
        Event::state_snapshot(json!({ "count": 0 })),
        Event::tool_call_start("call-1", "increment"),
        Event::tool_call_args("call-1", r#"{"by":1}"#),
        Event::state_delta(vec![PatchOperation::replace("/count", json!(1))]),
        Event::tool_call_end("call-1"),
        Event::tool_call_result("msg-1", "call-1", r#"{"count":1}"#),
        Event::run_finished_success("thread-1", "run-1"),
    ])
    .matching_requests();
    let mut thread = Thread::<_, Counter>::builder(transport, "thread-1")
        .state(json!({"count": 0}))
        .build()
        .unwrap();

    let updates: Vec<_> = thread.send("increment").unwrap().collect().await;
    assert!(
        !updates
            .iter()
            .any(|update| matches!(update, Update::Error(_))),
        "the stream should apply cleanly: {updates:?}"
    );

    let order: Vec<&str> = updates
        .iter()
        .filter_map(|update| match update {
            Update::State(_) => Some("state"),
            Update::Message(message) => match message.change {
                MessageChangeKind::ToolCallArgs { .. } => Some("args"),
                MessageChangeKind::ToolCallEnded { .. } => Some("call ended"),
                _ => None,
            },
            _ => None,
        })
        .collect();
    assert_eq!(order, ["state", "args", "state", "call ended"]);

    assert_eq!(thread.state().unwrap(), &Counter { count: 1 });
}

#[tokio::test]
async fn a_state_that_does_not_fit_the_typed_view_is_reported_without_losing_it() {
    // The agent publishes a partial state first. A strict type cannot hold it,
    // and saying so beats leaving the caller wondering why `state()` is `None`.
    let transport = ReplayTransport::new([
        Event::run_started("thread-1", "run-1"),
        Event::state_snapshot(json!({ "unrelated": true })),
        Event::state_snapshot(json!({ "count": 7 })),
        Event::run_finished_success("thread-1", "run-1"),
    ])
    .matching_requests();
    let mut thread = Thread::<_, Counter>::builder(transport, "thread-1")
        .state(json!({"count": 0}))
        .build()
        .unwrap();

    let updates: Vec<_> = thread.send("go").unwrap().collect().await;
    let errors: Vec<String> = updates
        .iter()
        .filter_map(|update| match update {
            Update::Error(error) => Some(error.to_string()),
            _ => None,
        })
        .collect();

    assert_eq!(errors.len(), 1);
    assert!(errors[0].contains("does not match the expected type"));

    // The typed view caught up on the next snapshot, and the raw state was
    // never wrong.
    assert_eq!(thread.state().unwrap(), &Counter { count: 7 });
    assert_eq!(thread.raw_state(), &json!({ "count": 7 }));
}