mentra 0.30.0

An agent runtime for tool-using LLM applications
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
//! The exchange against an agent that streams: settling by its stream, and
//! falling back to polling — never to resending — when the stream fails.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use a2a_lf::TaskState;
use serde_json::{Value, json};

use crate::a2a::exchange::{A2aExchange, A2aExchangeError, A2aStillWorking, exchange};
use crate::a2a::testing::{A2aFixture, RpcAnswer, Script, StreamEnd, status_event, task_json};
use crate::a2a::{A2aAgentConfig, A2aBinding, A2aClient, A2aLimits, A2aRequest, remote_output};
use crate::runtime::{CancellationToken, RunOptions};

const BINDINGS: [A2aBinding; 2] = [A2aBinding::JsonRpc, A2aBinding::HttpJson];

fn limits() -> A2aLimits {
    A2aLimits {
        poll_interval: Duration::from_millis(10),
        max_wait: Duration::from_secs(5),
        stream_idle_timeout: Duration::from_secs(5),
        ..A2aLimits::default()
    }
}

/// An agent that streams, whose `SendMessage` answers with a working task.
fn streaming(binding: A2aBinding, subscribe: RpcAnswer) -> Script {
    Script {
        streaming: true,
        send: RpcAnswer::Result(json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})),
        subscribe: vec![subscribe],
        ..Script::over(binding)
    }
}

async fn client_with(fixture: &A2aFixture, limits: A2aLimits) -> Arc<A2aClient> {
    let config = A2aAgentConfig::new("nous", fixture.base()).with_limits(limits);
    Arc::new(A2aClient::connect(&config).await.expect("connect"))
}

fn artifact(text: &str, append: bool) -> Value {
    json!({"artifactUpdate": {"taskId": "t1", "contextId": "c1", "append": append, "artifact": {
        "artifactId": "a1", "parts": [{"text": text}],
    }}})
}

fn completed_with(text: &str) -> RpcAnswer {
    let mut task = task_json("t1", "c1", "TASK_STATE_COMPLETED");
    task["artifacts"] = json!([{"artifactId": "a1", "parts": [{"text": text}]}]);
    RpcAnswer::Result(task)
}

/// Runs one exchange, returning its outcome and the progress it reported.
async fn run(
    client: &Arc<A2aClient>,
    options: &RunOptions,
) -> (Result<A2aExchange, A2aExchangeError>, Vec<String>) {
    let heard = Mutex::new(Vec::new());
    let progress = |line: String| heard.lock().expect("progress").push(line);
    let outcome = exchange(client, A2aRequest::send("ask"), options, &progress).await;
    (outcome, heard.into_inner().expect("progress"))
}

fn sends(fixture: &A2aFixture) -> usize {
    fixture
        .operations()
        .iter()
        .filter(|operation| operation.contains("SendMessage"))
        .count()
}

#[tokio::test]
async fn a_streaming_agents_task_settles_by_its_stream() {
    for binding in BINDINGS {
        let events = vec![
            json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")}),
            status_event("TASK_STATE_WORKING", Some("reading\nthe code")),
            artifact("4", false),
            artifact("2", true),
            status_event("TASK_STATE_COMPLETED", None),
        ];
        let fixture = A2aFixture::start(Script {
            // Polling would fail; the stream is all there is to read.
            get: vec![RpcAnswer::Error(-32001)],
            ..streaming(binding, RpcAnswer::Events(events, StreamEnd::Hang))
        });
        let client = client_with(&fixture, limits()).await;

        let (outcome, heard) = run(&client, &RunOptions::default()).await;
        let Ok(A2aExchange::Settled(task)) = outcome else {
            panic!("{binding}: expected a settled task, got {outcome:?}");
        };
        assert_eq!(task.status.state, TaskState::Completed);
        // An appended chunk joins the artifact's parts, as the SDKs merge it.
        let artifacts = task.artifacts.as_deref().unwrap_or_default();
        assert_eq!(artifacts.len(), 1);
        assert_eq!(artifacts[0].parts.len(), 2);
        assert!(remote_output("nous", &task, 1024).contains("\n4\n2\n"));
        assert_eq!(fixture.operations(), ["SendMessage", "SubscribeToTask"]);
        assert_eq!(
            heard,
            [
                "remote task t1 is working: reading the code",
                "remote task t1 is completed",
            ]
        );
    }
}

#[tokio::test]
async fn a_stream_dropped_mid_task_falls_back_to_polling_without_resending() {
    for binding in BINDINGS {
        let events = vec![
            json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")}),
            status_event("TASK_STATE_WORKING", Some("halfway")),
        ];
        let fixture = A2aFixture::start(Script {
            get: vec![completed_with("42")],
            ..streaming(binding, RpcAnswer::Events(events, StreamEnd::Close))
        });
        let client = client_with(&fixture, limits()).await;

        let (outcome, heard) = run(&client, &RunOptions::default()).await;
        let Ok(A2aExchange::Settled(task)) = outcome else {
            panic!("{binding}: expected a settled task, got {outcome:?}");
        };
        assert!(remote_output("nous", &task, 1024).contains("\n42\n"));
        assert_eq!(
            fixture.operations(),
            ["SendMessage", "SubscribeToTask", "GetTask"]
        );
        assert_eq!(sends(&fixture), 1, "the message is never sent again");
        assert_eq!(
            heard,
            [
                "remote task t1 is working: halfway",
                "stopped following remote task t1 (the stream ended before the task \
                 settled); polling it instead",
                "remote task t1 is completed",
            ]
        );
    }
}

#[tokio::test]
async fn a_refused_or_silent_stream_falls_back_to_polling() {
    let silent = RpcAnswer::Events(
        vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})],
        StreamEnd::Hang,
    );
    for (subscribe, why) in [
        (RpcAnswer::Error(-32004), "refused"),
        (RpcAnswer::Http(503, String::new()), "unavailable"),
        (
            RpcAnswer::RawEvents("data: {not json\n\n".into(), StreamEnd::Hang),
            "malformed",
        ),
        (silent, "silent"),
    ] {
        let fixture = A2aFixture::start(Script {
            get: vec![completed_with("42")],
            ..streaming(A2aBinding::HttpJson, subscribe)
        });
        let client = client_with(
            &fixture,
            A2aLimits {
                stream_idle_timeout: Duration::from_millis(100),
                ..limits()
            },
        )
        .await;

        let (outcome, heard) = run(&client, &RunOptions::default()).await;
        assert!(
            matches!(outcome, Ok(A2aExchange::Settled(_))),
            "{why}: {outcome:?}"
        );
        // The host hears, once, why the stream was given up for polling.
        let gave_up: Vec<&String> = heard
            .iter()
            .filter(|line| line.starts_with("stopped following remote task t1 ("))
            .collect();
        assert_eq!(gave_up.len(), 1, "{why}: {heard:?}");
        assert!(
            gave_up[0].ends_with("; polling it instead"),
            "{why}: {heard:?}"
        );
        assert!(!gave_up[0].contains("server text"), "{why}: {heard:?}");
        assert_eq!(sends(&fixture), 1, "{why}");
        assert_eq!(
            fixture.operations().last().map(String::as_str),
            Some("GetTask")
        );
    }
}

#[tokio::test]
async fn a_followed_task_still_working_at_the_bound_is_handed_back() {
    let bound = Duration::from_millis(200);
    let fixture = A2aFixture::start(streaming(
        A2aBinding::JsonRpc,
        RpcAnswer::Events(
            vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})],
            StreamEnd::Hang,
        ),
    ));
    let client = client_with(
        &fixture,
        A2aLimits {
            max_wait: bound,
            ..limits()
        },
    )
    .await;

    let (outcome, _) = run(&client, &RunOptions::default()).await;
    let Ok(A2aExchange::StillWorking { task, reason }) = outcome else {
        panic!("expected a working task, got {outcome:?}");
    };
    assert_eq!(task.id, "t1");
    assert_eq!(reason, A2aStillWorking::WaitBound(bound));
    assert_eq!(fixture.operations(), ["SendMessage", "SubscribeToTask"]);
}

#[tokio::test]
async fn a_run_cancelled_while_following_cancels_the_task() {
    let fixture = A2aFixture::start(streaming(
        A2aBinding::HttpJson,
        RpcAnswer::Events(
            vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})],
            StreamEnd::Hang,
        ),
    ));
    let client = client_with(&fixture, limits()).await;
    let token = CancellationToken::default();
    let options = RunOptions {
        cancellation: Some(token.clone()),
        ..RunOptions::default()
    };

    let canceller = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(100)).await;
        token.cancel();
    });
    let (outcome, _) = run(&client, &options).await;
    canceller.await.expect("canceller");

    let Err(A2aExchangeError::Abandoned { task_id, canceled }) = outcome else {
        panic!("expected an abandoned task, got {outcome:?}");
    };
    assert_eq!(task_id, "t1");
    assert!(canceled.is_ok());
    assert_eq!(
        fixture.operations(),
        ["SendMessage", "SubscribeToTask", "CancelTask"]
    );
}

#[tokio::test]
async fn a_run_stopping_while_following_hands_the_task_back() {
    let fixture = A2aFixture::start(streaming(
        A2aBinding::JsonRpc,
        RpcAnswer::Events(
            vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})],
            StreamEnd::Hang,
        ),
    ));
    let client = client_with(&fixture, limits()).await;
    let stop = CancellationToken::default();
    let options = RunOptions {
        stop: Some(stop.clone()),
        ..RunOptions::default()
    };

    let stopper = tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(100)).await;
        stop.cancel();
    });
    let (outcome, _) = run(&client, &options).await;
    stopper.await.expect("stopper");

    let Ok(A2aExchange::StillWorking { reason, .. }) = outcome else {
        panic!("expected a working task, got {outcome:?}");
    };
    assert_eq!(reason, A2aStillWorking::RunStopping);
    assert!(!fixture.operations().contains(&"CancelTask".to_string()));
}

#[tokio::test]
async fn an_agent_that_does_not_stream_is_never_subscribed_to() {
    let fixture = A2aFixture::start(Script {
        send: RpcAnswer::Result(json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})),
        get: vec![completed_with("42")],
        ..Script::default()
    });
    let client = client_with(&fixture, limits()).await;

    let (outcome, _) = run(&client, &RunOptions::default()).await;
    assert!(
        matches!(outcome, Ok(A2aExchange::Settled(_))),
        "{outcome:?}"
    );
    assert_eq!(fixture.operations(), ["SendMessage", "GetTask"]);
}

#[tokio::test]
async fn an_exchange_dropped_while_following_cancels_the_task() {
    let fixture = A2aFixture::start(streaming(
        A2aBinding::JsonRpc,
        RpcAnswer::Events(
            vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})],
            StreamEnd::Hang,
        ),
    ));
    let client = client_with(&fixture, limits()).await;

    let dropped = tokio::time::timeout(
        Duration::from_millis(150),
        run(&client, &RunOptions::default()),
    )
    .await;
    assert!(dropped.is_err(), "the exchange should still be following");

    for _ in 0..50 {
        if fixture.operations().contains(&"CancelTask".to_string()) {
            assert_eq!(sends(&fixture), 1);
            return;
        }
        tokio::time::sleep(Duration::from_millis(20)).await;
    }
    panic!(
        "no CancelTask after the exchange was dropped: {:?}",
        fixture.operations()
    );
}

#[tokio::test]
async fn an_agent_that_subscribes_by_post_is_still_followed() {
    let events = vec![
        json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")}),
        status_event("TASK_STATE_COMPLETED", None),
    ];
    let fixture = A2aFixture::start(Script {
        subscribe_by_post: true,
        get: vec![RpcAnswer::Error(-32001)],
        ..streaming(
            A2aBinding::HttpJson,
            RpcAnswer::Events(events, StreamEnd::Close),
        )
    });
    let client = client_with(&fixture, limits()).await;

    let (outcome, heard) = run(&client, &RunOptions::default()).await;
    assert!(
        matches!(outcome, Ok(A2aExchange::Settled(_))),
        "{outcome:?}"
    );
    assert_eq!(
        fixture.operations(),
        ["SendMessage", "SubscribeToTask", "SubscribeToTask"]
    );
    assert_eq!(heard, ["remote task t1 is completed"]);
}

/// An artifact update for `a1` carrying `text`, replacing what was held.
fn replacing(text: &str) -> Value {
    artifact(text, false)
}

#[tokio::test]
async fn replacing_an_artifact_does_not_count_as_growth() {
    // Each replacement is a third of the bound; ten of them, counted as
    // growth, would outgrow it three times over.
    let mut events = vec![json!({"task": task_json("t1", "c1", "TASK_STATE_WORKING")})];
    events.extend((0..10).map(|n| replacing(&format!("{n}{}", "x".repeat(300)))));
    events.push(status_event("TASK_STATE_COMPLETED", None));
    let fixture = A2aFixture::start(Script {
        get: vec![RpcAnswer::Error(-32001)],
        ..streaming(
            A2aBinding::JsonRpc,
            RpcAnswer::Events(events, StreamEnd::Close),
        )
    });
    let client = client_with(
        &fixture,
        A2aLimits {
            max_response_bytes: 1024,
            max_event_bytes: 64 * 1024,
            ..limits()
        },
    )
    .await;

    let (outcome, heard) = run(&client, &RunOptions::default()).await;
    let Ok(A2aExchange::Settled(task)) = outcome else {
        panic!("expected a settled task, got {outcome:?}");
    };
    assert!(remote_output("nous", &task, 4096).contains("\n9xxx"));
    assert_eq!(fixture.operations(), ["SendMessage", "SubscribeToTask"]);
    assert_eq!(heard, ["remote task t1 is completed"]);
}

#[tokio::test]
async fn a_snapshot_larger_than_a_reply_may_be_is_left_to_polling() {
    let mut snapshot = task_json("t1", "c1", "TASK_STATE_WORKING");
    snapshot["artifacts"] = json!([{"artifactId": "a1", "parts": [{"text": "x".repeat(2048)}]}]);
    let fixture = A2aFixture::start(Script {
        get: vec![completed_with("42")],
        ..streaming(
            A2aBinding::JsonRpc,
            RpcAnswer::Events(vec![json!({"task": snapshot})], StreamEnd::Hang),
        )
    });
    let client = client_with(
        &fixture,
        A2aLimits {
            max_response_bytes: 1024,
            max_event_bytes: 64 * 1024,
            ..limits()
        },
    )
    .await;

    let (outcome, heard) = run(&client, &RunOptions::default()).await;
    assert!(
        matches!(outcome, Ok(A2aExchange::Settled(_))),
        "{outcome:?}"
    );
    assert_eq!(
        fixture.operations(),
        ["SendMessage", "SubscribeToTask", "GetTask"]
    );
    assert!(
        heard[0].contains("its artifacts outgrew the 1024 byte reply bound"),
        "{heard:?}"
    );
}

#[tokio::test]
async fn a_task_id_reaches_progress_as_one_clean_line() {
    let id = "t1\u{1b}[2J\nforged line";
    let fixture = A2aFixture::start(Script {
        send: RpcAnswer::Result(json!({"task": task_json(id, "c1", "TASK_STATE_WORKING")})),
        get: vec![RpcAnswer::Result(task_json(
            id,
            "c1",
            "TASK_STATE_COMPLETED",
        ))],
        ..Script::default()
    });
    let client = client_with(&fixture, limits()).await;

    let (outcome, heard) = run(&client, &RunOptions::default()).await;
    assert!(
        matches!(outcome, Ok(A2aExchange::Settled(_))),
        "{outcome:?}"
    );
    assert_eq!(heard, ["remote task t1 [2J forged line is completed"]);
}