rig-agentcore 0.47.10

Run a Rig agent on AWS Bedrock AgentCore Runtime: the HTTP protocol contract (/invocations, /ping), sessions, streaming and traces AgentCore Observability and Evaluations read.
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
//! The `/ws` endpoint: one JSON prompt per text message, answered with frames
//! on scripted models, over a real WebSocket.

use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use axum::http::{HeaderValue, StatusCode};
use futures::{SinkExt, StreamExt};
use rig_agent::AgentBuilder;
use rig_agentcore::{AgentCoreApp, SESSION_HEADER};
use rig_core::test_utils::{MockCompletionModel, MockStreamEvent};
use rig_core::tool::{Tool, ToolContext, ToolExecutionError};
use serde_json::{Value, json};
use tokio::sync::Notify;
use tokio::time::timeout;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;

type Client =
    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;

async fn serve(app: AgentCoreApp) -> SocketAddr {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move { axum::serve(listener, app.router()).await.unwrap() });
    address
}

async fn connect(address: SocketAddr, session: Option<&str>) -> Client {
    let mut request = format!("ws://{address}/ws").into_client_request().unwrap();
    if let Some(session) = session {
        request
            .headers_mut()
            .insert(SESSION_HEADER, HeaderValue::from_str(session).unwrap());
    }
    let (socket, _) = tokio_tungstenite::connect_async(request).await.unwrap();
    socket
}

async fn send(socket: &mut Client, text: impl Into<String>) {
    socket
        .send(Message::Text(text.into().into()))
        .await
        .unwrap();
}

/// Every frame up to and including the one that ends a run: a final answer or
/// an error.
async fn frames_until_end(socket: &mut Client) -> Vec<Value> {
    let mut frames = Vec::new();
    while let Some(Ok(Message::Text(text))) = socket.next().await {
        let frame: Value = serde_json::from_str(text.as_str()).unwrap();
        let ends = frame.get("message_type") != Some(&json!("agent_text"));
        frames.push(frame);
        if ends {
            break;
        }
    }
    frames
}

const WAIT: Duration = Duration::from_secs(5);

/// A tool that never returns. It tells the test when it starts, and when its
/// future is dropped, which is when its run is cancelled.
struct Parked {
    started: Arc<Notify>,
    dropped: Arc<Notify>,
}

/// Notifies on drop, so a dropped tool future is visible to the test.
struct OnDrop(Arc<Notify>);

impl Drop for OnDrop {
    fn drop(&mut self) {
        self.0.notify_one();
    }
}

impl Tool for Parked {
    const NAME: &'static str = "park";
    type Args = Value;
    type Output = String;
    type Error = ToolExecutionError;

    fn description(&self) -> String {
        "Waits forever".into()
    }

    fn parameters(&self) -> Value {
        json!({"type": "object", "properties": {}})
    }

    async fn call(&self, _: &mut ToolContext, _: Self::Args) -> Result<String, Self::Error> {
        let _dropped = OnDrop(Arc::clone(&self.dropped));
        self.started.notify_one();
        std::future::pending::<()>().await;
        Ok("never".into())
    }
}

/// A model that calls `park` on the first message and answers `fresh` after.
fn parking_model() -> MockCompletionModel {
    MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::tool_call("call-1", "park", json!({})),
            MockStreamEvent::final_response_with_default_usage(),
        ],
        vec![
            MockStreamEvent::text("fresh"),
            MockStreamEvent::final_response_with_default_usage(),
        ],
    ])
}

fn sent(model: &MockCompletionModel, request: usize) -> String {
    let requests = model.requests();
    serde_json::to_string(&requests.get(request).expect("request").chat_history).unwrap()
}

#[tokio::test]
async fn the_upgrade_succeeds() {
    let agent = AgentBuilder::new(MockCompletionModel::text("hi")).build();
    let address = serve(AgentCoreApp::new(agent)).await;
    let (mut socket, response) = tokio_tungstenite::connect_async(format!("ws://{address}/ws"))
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
    socket.close(None).await.unwrap();
}

#[tokio::test]
async fn a_prompt_streams_events_then_the_final_message() {
    let model = MockCompletionModel::from_stream_turns([vec![
        MockStreamEvent::text("Hel"),
        MockStreamEvent::text("lo."),
        MockStreamEvent::final_response_with_default_usage(),
    ]]);
    let address = serve(AgentCoreApp::new(AgentBuilder::new(model).build())).await;
    let mut socket = connect(address, Some("s")).await;

    send(&mut socket, json!({"prompt": "Say hello"}).to_string()).await;
    let frames = frames_until_end(&mut socket).await;

    // Deltas that arrive within the text window share a frame, so only the
    // joined text is fixed.
    let text: String = frames
        .iter()
        .filter_map(|frame| frame.get("text").and_then(Value::as_str))
        .collect();
    assert_eq!(text, "Hello.");
    assert!(
        frames
            .iter()
            .all(|frame| frame.get("session_id") == Some(&json!("s")))
    );
    assert_eq!(
        frames.last(),
        Some(&json!({"response": "Hello.", "session_id": "s", "message_type": "agent_response"}))
    );
}

#[tokio::test]
async fn a_reply_over_the_frame_limit_is_an_error_frame_not_a_closed_connection() {
    let chunk = "a".repeat(20 * 1024);
    let mut turn: Vec<MockStreamEvent> = (0..5)
        .map(|_| MockStreamEvent::text(chunk.clone()))
        .collect();
    turn.push(MockStreamEvent::final_response_with_default_usage());
    let model = MockCompletionModel::from_stream_turns([
        turn,
        vec![
            MockStreamEvent::text("still here"),
            MockStreamEvent::final_response_with_default_usage(),
        ],
    ]);
    let address = serve(AgentCoreApp::new(AgentBuilder::new(model).build())).await;
    let mut socket = connect(address, None).await;

    send(&mut socket, json!({"prompt": "long"}).to_string()).await;
    let frames = frames_until_end(&mut socket).await;
    assert!(
        frames
            .iter()
            .all(|frame| frame.to_string().len() <= 64 * 1024)
    );
    assert_eq!(
        frames.last().and_then(|frame| frame.get("message_type")),
        Some(&json!("error"))
    );

    // The connection is still usable.
    send(&mut socket, json!({"prompt": "short"}).to_string()).await;
    let answered = frames_until_end(&mut socket).await;
    assert_eq!(
        answered.last().and_then(|frame| frame.get("response")),
        Some(&json!("still here"))
    );
}

#[tokio::test]
async fn the_session_header_ties_messages_to_one_history() {
    let model = MockCompletionModel::from_stream_turns([
        vec![
            MockStreamEvent::text("Hi Ana."),
            MockStreamEvent::final_response_with_default_usage(),
        ],
        vec![
            MockStreamEvent::text("Your name is Ana."),
            MockStreamEvent::final_response_with_default_usage(),
        ],
    ]);
    let address = serve(AgentCoreApp::new(AgentBuilder::new(model.clone()).build())).await;
    let mut socket = connect(address, Some("session-1")).await;

    send(&mut socket, json!({"prompt": "I am Ana"}).to_string()).await;
    frames_until_end(&mut socket).await;
    send(
        &mut socket,
        json!({"prompt": "What is my name?"}).to_string(),
    )
    .await;
    let second = frames_until_end(&mut socket).await;

    assert_eq!(
        second.last().and_then(|frame| frame.get("response")),
        Some(&json!("Your name is Ana."))
    );
    assert!(
        sent(&model, 1).contains("I am Ana"),
        "the second message carries the first"
    );
}

#[tokio::test]
async fn an_invalid_message_gets_an_error_frame_and_the_connection_stays_open() {
    let model = MockCompletionModel::from_stream_turns([vec![
        MockStreamEvent::text("ok"),
        MockStreamEvent::final_response_with_default_usage(),
    ]]);
    let address = serve(AgentCoreApp::new(AgentBuilder::new(model).build())).await;
    let mut socket = connect(address, None).await;

    send(&mut socket, "not json").await;
    let refused = frames_until_end(&mut socket).await;
    assert_eq!(refused.len(), 1, "{refused:?}");
    assert_eq!(
        refused.first().and_then(|frame| frame.get("message_type")),
        Some(&json!("error"))
    );

    send(&mut socket, json!({"prompt": "hi"}).to_string()).await;
    let answered = frames_until_end(&mut socket).await;
    assert_eq!(
        answered.last().and_then(|frame| frame.get("response")),
        Some(&json!("ok"))
    );
}

#[tokio::test]
async fn an_oversized_message_is_refused_before_the_agent_runs() {
    let model = MockCompletionModel::text("never");
    let app = AgentCoreApp::new(AgentBuilder::new(model.clone()).build()).max_request_bytes(256);
    let address = serve(app).await;
    let mut socket = connect(address, None).await;

    send(&mut socket, json!({"prompt": "x".repeat(1000)}).to_string()).await;
    let mut frames = Vec::new();
    while let Some(Ok(Message::Text(text))) = socket.next().await {
        frames.push(text.to_string());
    }

    assert!(
        frames.iter().all(|text| !text.contains("\"response\"")),
        "{frames:?}"
    );
    assert!(
        frames.iter().any(|text| text.contains("\"error\"")),
        "{frames:?}"
    );
    assert!(model.requests().is_empty(), "the agent was not called");
}

#[tokio::test]
async fn a_frame_far_over_the_limit_is_refused_before_the_agent_runs() {
    let model = MockCompletionModel::text("never");
    let app = AgentCoreApp::new(AgentBuilder::new(model.clone()).build()).max_request_bytes(1024);
    let address = serve(app).await;
    let mut socket = connect(address, None).await;

    // The server may close while this write is still going out; that is the refusal.
    let _ = socket
        .send(Message::Text(
            json!({"prompt": "x".repeat(4 * 1024 * 1024)})
                .to_string()
                .into(),
        ))
        .await;
    let mut frames = Vec::new();
    while let Some(Ok(Message::Text(text))) = socket.next().await {
        frames.push(text.to_string());
    }

    assert!(
        frames.iter().all(|text| !text.contains("\"response\"")),
        "{frames:?}"
    );
    assert!(model.requests().is_empty(), "the agent was not called");
}

#[tokio::test]
async fn a_run_stops_when_the_client_goes_away() {
    let started = Arc::new(Notify::new());
    let dropped = Arc::new(Notify::new());
    let model = parking_model();
    let agent = AgentBuilder::new(model.clone())
        .tool(Parked {
            started: Arc::clone(&started),
            dropped: Arc::clone(&dropped),
        })
        .build();
    let address = serve(AgentCoreApp::new(agent)).await;

    let mut socket = connect(address, Some("s")).await;
    send(&mut socket, json!({"prompt": "abandoned"}).to_string()).await;
    timeout(WAIT, started.notified())
        .await
        .expect("the run started");
    drop(socket);
    timeout(WAIT, dropped.notified())
        .await
        .expect("the run was cancelled with its client");

    // The abandoned turn was never saved: the session starts from the new prompt.
    let mut socket = connect(address, Some("s")).await;
    send(&mut socket, json!({"prompt": "after"}).to_string()).await;
    let frames = frames_until_end(&mut socket).await;
    assert_eq!(
        frames.last().and_then(|frame| frame.get("response")),
        Some(&json!("fresh"))
    );
    assert!(sent(&model, 1).contains("after"));
    assert!(
        !sent(&model, 1).contains("abandoned"),
        "the abandoned turn was kept"
    );
}

#[tokio::test]
async fn during_a_run_pings_are_answered_and_another_message_is_busy() {
    let started = Arc::new(Notify::new());
    let agent = AgentBuilder::new(parking_model())
        .tool(Parked {
            started: Arc::clone(&started),
            dropped: Arc::new(Notify::new()),
        })
        .build();
    let address = serve(AgentCoreApp::new(agent)).await;
    let mut socket = connect(address, None).await;

    send(&mut socket, json!({"prompt": "first"}).to_string()).await;
    timeout(WAIT, started.notified())
        .await
        .expect("the run started");

    socket.send(Message::Ping(vec![7].into())).await.unwrap();
    let reply = timeout(WAIT, socket.next()).await.expect("a pong");
    assert!(
        matches!(&reply, Some(Ok(Message::Pong(payload))) if payload.as_ref() == [7u8].as_slice()),
        "{reply:?}"
    );

    send(&mut socket, json!({"prompt": "second"}).to_string()).await;
    let busy = frames_until_end(&mut socket).await;
    assert_eq!(busy.len(), 1, "{busy:?}");
    assert_eq!(
        busy.first().and_then(|frame| frame.get("message_type")),
        Some(&json!("error"))
    );
    assert!(
        busy.first()
            .and_then(|frame| frame.get("error"))
            .and_then(Value::as_str)
            .is_some_and(|text| text.contains("busy")),
        "{busy:?}"
    );
}

#[tokio::test]
async fn a_dropped_client_releases_its_slot_for_the_next_run() {
    let started = Arc::new(Notify::new());
    let dropped = Arc::new(Notify::new());
    let agent = AgentBuilder::new(parking_model())
        .tool(Parked {
            started: Arc::clone(&started),
            dropped: Arc::clone(&dropped),
        })
        .build();
    let address = serve(AgentCoreApp::new(agent).max_concurrent_tasks(1)).await;

    let mut socket = connect(address, Some("s")).await;
    send(&mut socket, json!({"prompt": "abandoned"}).to_string()).await;
    timeout(WAIT, started.notified())
        .await
        .expect("the run started");
    drop(socket);
    timeout(WAIT, dropped.notified())
        .await
        .expect("the run was cancelled with its client");

    // The slot is released as the cancelled task ends, a moment after the tool
    // future drops, so a refused run is retried until the slot is free.
    let mut socket = connect(address, Some("s")).await;
    let answered = timeout(WAIT, async {
        loop {
            send(&mut socket, json!({"prompt": "after"}).to_string()).await;
            let frames = frames_until_end(&mut socket).await;
            if frames
                .last()
                .and_then(|frame| frame.get("response"))
                .is_some()
            {
                return frames;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("a second run started");
    assert_eq!(
        answered.last().and_then(|frame| frame.get("response")),
        Some(&json!("fresh"))
    );
}