rig-agentcore 0.47.6

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
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
//! Run a [Rig](https://github.com/0xPlaygrounds/rig) agent on AWS Bedrock
//! AgentCore Runtime.
//!
//! AgentCore runs an agent as an ARM64 container that serves its HTTP
//! protocol contract on port 8080: `POST /invocations` with a JSON body,
//! answered with JSON or server-sent events, `GET /ping`, and the WebSocket
//! `/ws`, where each text message is one JSON prompt. Each runtime
//! session (the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header) is one
//! conversation. [`AgentCoreApp`] serves that contract for a Rig agent:
//!
//! - the session's conversation is kept between invocations, in memory or in
//!   any [`rig_memory`] store (see [`AgentCoreApp::history_store`]);
//! - the reply streams as server-sent events when the caller asks for
//!   `text/event-stream`, and is one JSON object otherwise;
//! - each invocation runs in a span that continues the caller's trace and
//!   carries the session as `session.id` (through [`rig_otel`]), which is what
//!   AgentCore Observability and Evaluations group a session's traces by;
//! - `/ping` answers `HealthyBusy` while an invocation or background work from
//!   [`AgentCoreApp::spawn_task`] is open, so AgentCore Runtime keeps the
//!   session running until that work ends.
//!
//! - prompts and replies go on the spans only with
//!   [`AgentCoreApp::record_content`] (off by default, as in Rig). AgentCore
//!   Evaluations needs them to judge a session. The app's setting overrides
//!   the agent's own `record_content_telemetry`, so set it on the app.
//!
//! ```no_run
//! async fn run(agent: rig_agent::Agent) -> Result<(), rig_agentcore::ServeError> {
//!     rig_agentcore::AgentCoreApp::new(agent)
//!         .record_content(true)
//!         .serve()
//!         .await
//! }
//! ```

#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(
    test,
    allow(
        clippy::expect_used,
        clippy::panic,
        clippy::unwrap_used,
        clippy::unreachable
    )
)]

mod busy;
mod history;

use std::convert::Infallible;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;

use axum::Json;
use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
use axum::extract::{DefaultBodyLimit, State};
use axum::http::{HeaderMap, StatusCode, header};
use axum::response::sse::{Event, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use futures::StreamExt;
use rig_agent::Agent;
use rig_agent::agent::MultiTurnStreamItem;
use rig_core::message::Message;
use rig_core::streaming::{Item, StreamEvent};
use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
use rig_memory::AsyncStore;
use rig_memory::recent::{Recent, TokenBudget, view};
use serde::Deserialize;
use serde_json::json;
use tokio::sync::mpsc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tracing::Instrument;

use crate::busy::Busy;
use crate::history::{
    HistoryError, HistoryStore, InMemory, Persistent, Retained, Summarizing, is_summary, local_id,
    summarize,
};

/// The header AgentCore Runtime names the session with.
pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";

/// The port AgentCore Runtime sends the HTTP protocol to.
pub const DEFAULT_PORT: u16 = 8080;

/// How many sessions an app keeps by default. AgentCore gives each session
/// its own microVM, so one process usually sees one; this bounds the memory
/// when the app runs elsewhere.
pub const DEFAULT_MAX_SESSIONS: usize = 1000;

/// How many tokens of history a session keeps by default.
pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;

/// The largest `/invocations` body by default, in bytes: the limit Axum's JSON
/// extractor already applied. A larger body gets 413.
pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;

pub use busy::BusyGuard;
/// The session stores and history windows conversations are kept with.
pub use rig_memory;

/// Why the app stopped serving.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ServeError {
    /// The port could not be bound.
    #[error("could not listen on {address}: {source}")]
    Bind {
        /// The address.
        address: SocketAddr,
        /// The error.
        #[source]
        source: std::io::Error,
    },
    /// Serving failed.
    #[error("serving failed: {0}")]
    Serve(#[source] std::io::Error),
}

/// A Rig agent served on AgentCore Runtime's HTTP protocol contract.
#[derive(Clone)]
pub struct AgentCoreApp {
    inner: Arc<Inner>,
}

#[derive(Clone)]
struct Inner {
    agent: Agent,
    history: Arc<dyn HistoryStore>,
    window: Arc<dyn Recent>,
    summarizing: Option<Summarizing>,
    record_content: bool,
    slots: Option<Arc<Semaphore>>,
    max_run: Option<Duration>,
    max_request_bytes: usize,
    busy: Arc<Busy>,
}

impl AgentCoreApp {
    /// Serve `agent`.
    pub fn new(agent: Agent) -> Self {
        Self {
            inner: Arc::new(Inner {
                agent,
                history: Arc::new(InMemory::new(DEFAULT_MAX_SESSIONS)),
                window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
                summarizing: None,
                record_content: false,
                slots: None,
                max_run: None,
                max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
                busy: Busy::new(),
            }),
        }
    }

    /// Keep at most `max` sessions' conversations in memory, forgetting the
    /// oldest. This is the default, with [`DEFAULT_MAX_SESSIONS`]. It replaces
    /// a store set with [`history_store`](Self::history_store).
    #[must_use]
    pub fn max_sessions(self, max: usize) -> Self {
        self.rebuild(|inner| inner.history = Arc::new(InMemory::new(max)))
    }

    /// Keep sessions in `store`, one session log per session id, so they
    /// survive restarts and several apps can share them: any [`rig_memory`]
    /// store, such as `rig_memory::DirStore` (feature `fs`) or the
    /// `rig-sqlite` and `rig-postgres` stores. Any session id works: one that
    /// is 1 to 128 ASCII letters, digits, `-` or `_` names its log as it is,
    /// any other is hashed into a safe log name. Two apps, or concurrent
    /// invocations of one session, saving at once do not lose either turn: a
    /// save that loses a race rereads and retries up to 10 times with a short
    /// jittered backoff. If a save still fails, the invocation's answer is
    /// returned anyway, the failure is logged, and that run's turn is not
    /// persisted, so later invocations do not see it. A load that fails is
    /// reported to the caller as an error, before the agent runs. The store
    /// keeps each session's whole conversation;
    /// [`history_window`](Self::history_window) limits only what an invocation
    /// sends. Replaces the in-memory store set by [`max_sessions`](Self::max_sessions).
    #[must_use]
    pub fn history_store<S>(self, store: S) -> Self
    where
        S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
    {
        self.rebuild(|inner| inner.history = Arc::new(Persistent(store)))
    }

    /// Which newest messages of a session each invocation sends the model,
    /// such as `rig_memory::recent::TokenBudget::new(8_000)` or
    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
    /// tool result is never sent without its call. An empty window
    /// (`TokenBudget::new(0)`, `LastMessages(0)`) sends no history.
    ///
    /// With [`summarize_history`](Self::summarize_history), the summary is
    /// sent first, and the window limits only the messages after it.
    ///
    /// What the window also does depends on the store. In memory, messages
    /// beyond it are forgotten when a run is saved, so memory stays bounded.
    /// With [`history_store`](Self::history_store), the store keeps the whole
    /// conversation and the window only limits what is sent, so a later,
    /// wider window sees older turns again.
    #[must_use]
    pub fn history_window(self, window: impl Recent + 'static) -> Self {
        self.rebuild(|inner| inner.window = Arc::new(window))
    }

    /// Summarize a session's older history with `summarizer` once the session
    /// holds more than `trigger_messages` messages. The messages before the
    /// newest `keep_recent` are replaced by one summary, which becomes the
    /// session's first message: a user message in rig-memory's compaction frame
    /// ("The conversation history before this point was compacted into the
    /// following summary: <summary>...</summary>"). The newest messages stay
    /// verbatim, and the cut never separates a tool call from its result.
    ///
    /// The summary is always sent first, before the messages the window keeps,
    /// even when the window is narrower than the summary and the kept messages.
    /// In a session this option summarizes, a first message that opens with
    /// rig-memory's summary frame text is treated as the summary, even if a
    /// caller wrote it.
    /// `summarizer` should be an agent without tools: a tool call in its reply
    /// is not used. `trigger_messages` is raised to `keep_recent + 1` when it is
    /// not larger, since a cut needs something older than the kept messages.
    ///
    /// Summarizing runs before the invocation answers. Two concurrent
    /// invocations of one session may both summarize. A summary whose session
    /// changed under it (a concurrent summary, or a refused save to the store)
    /// is skipped and the history is kept, not lost.
    ///
    /// If a summary fails (the summarizer errors or returns no text, or the
    /// store refuses the change), a warning is logged, the session keeps its
    /// history, and the invocation answers as usual. The next invocation tries
    /// again. Without a store, a session whose summaries keep failing keeps at
    /// least its newest `2 * trigger_messages` messages, so memory stays
    /// bounded; older messages are dropped. With
    /// [`history_store`](Self::history_store), the store keeps the whole
    /// conversation as it does without summaries.
    ///
    /// Without a store, the summary is kept in memory with the session. With
    /// [`history_store`](Self::history_store), the summary is written to the
    /// store's log in place of the messages it replaces, which the log keeps in
    /// its history.
    ///
    /// Each attempt is traced as an `agentcore.summarize` span under the
    /// invocation span. It records the messages summarized and kept, the
    /// outcome (`summarized`, `skipped_changed`, `skipped_nothing_older` or
    /// `failed`), and the summarizer's token usage when the provider reports
    /// it. The prompt and the summary text are recorded only with
    /// [`record_content`](Self::record_content), as the other GenAI content is.
    #[must_use]
    pub fn summarize_history(
        self,
        summarizer: Agent,
        keep_recent: usize,
        trigger_messages: usize,
    ) -> Self {
        let trigger_messages = trigger_messages.max(keep_recent.saturating_add(1));
        self.rebuild(|inner| {
            inner.summarizing = Some(Summarizing {
                summarizer,
                keep_recent,
                trigger_messages,
            });
        })
    }

    /// Record prompts and replies on the GenAI spans. AgentCore Evaluations
    /// needs them to judge a session; they are off by default, as in Rig,
    /// because they put conversation content into your telemetry.
    ///
    /// This setting always overrides the agent's own
    /// `AgentBuilder::record_content_telemetry`. The app passes its value to
    /// every invocation, so the agent's setting is ignored when the agent is
    /// served through `AgentCoreApp`. To record content, call
    /// `.record_content(true)` on the app. The default here is `false`, so an
    /// agent built with `record_content_telemetry(true)` still records nothing
    /// unless the app sets it too. This is planned to change in 0.48 (PR #42),
    /// so that an app setting left unset keeps the agent's.
    #[must_use]
    pub fn record_content(self, record: bool) -> Self {
        self.rebuild(|inner| inner.record_content = record)
    }

    /// Run at most `max` invocations at once (at least one). An invocation
    /// beyond that gets 429 Too Many Requests before the agent runs; 429 is the
    /// conventional throttle status. Without this there is no cap, which is the
    /// default: AgentCore Runtime gives each session its own microVM. Outside
    /// AgentCore Runtime, a cap around 32 suits most single-process apps.
    #[must_use]
    pub fn max_concurrent_tasks(self, max: usize) -> Self {
        self.rebuild(|inner| inner.slots = Some(Arc::new(Semaphore::new(max.max(1)))))
    }

    /// Stop an invocation that runs longer than `max`, counting the summarizing
    /// step that can run before it. A stopped invocation answers 504 Gateway
    /// Timeout (or an `{"error"}` event when streaming), and its turn is not
    /// added to the session. Without this there is no limit, which is the
    /// default. Outside AgentCore Runtime, ten minutes suits most agents.
    #[must_use]
    pub fn max_run_duration(self, max: Duration) -> Self {
        self.rebuild(|inner| inner.max_run = Some(max))
    }

    /// Refuse an `/invocations` body larger than `bytes` with 413 Payload Too
    /// Large, before it is parsed. Defaults to [`DEFAULT_MAX_REQUEST_BYTES`].
    #[must_use]
    pub fn max_request_bytes(self, bytes: usize) -> Self {
        self.rebuild(|inner| inner.max_request_bytes = bytes)
    }

    /// Mark background work as open until the returned guard drops. While any
    /// guard is alive, `/ping` answers `HealthyBusy`, so AgentCore Runtime keeps
    /// the session running; once they are all dropped it answers `Healthy`
    /// again. Use it for work that outlives an invocation, such as a task the
    /// app starts on its own.
    pub fn track_task(&self) -> BusyGuard {
        Busy::open(&self.inner.busy)
    }

    /// Run `future` on the Tokio runtime as background work. `/ping` answers
    /// `HealthyBusy` until it finishes, or until its task is aborted. Dropping
    /// the returned handle does not stop the task. Call it on a running Tokio
    /// runtime, as for [`tokio::spawn`].
    ///
    /// ```no_run
    /// # async fn run(app: &rig_agentcore::AgentCoreApp) {
    /// app.spawn_task(async {
    ///     // Work that outlives the invocation that started it.
    /// });
    /// # }
    /// ```
    pub fn spawn_task<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
    where
        F: Future + Send + 'static,
        F::Output: Send + 'static,
    {
        let guard = self.track_task();
        tokio::spawn(async move {
            let _guard = guard;
            future.await
        })
    }

    fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
        let mut inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| (*shared).clone());
        change(&mut inner);
        Self {
            inner: Arc::new(inner),
        }
    }

    /// The contract's routes, `/invocations`, `/ping` and the WebSocket `/ws`,
    /// as an Axum router.
    pub fn router(self) -> axum::Router {
        let limit = self.inner.max_request_bytes;
        axum::Router::new()
            .route(
                "/invocations",
                post(invoke).layer(DefaultBodyLimit::max(limit)),
            )
            .route("/ping", get(ping))
            .route("/ws", get(socket))
            .with_state(self)
    }

    /// Serve on `0.0.0.0` at `PORT` (default 8080, what AgentCore sends to)
    /// until the process gets Ctrl-C or SIGTERM. A `PORT` that is set but is
    /// not a port number logs a warning and serves on the default.
    pub async fn serve(self) -> Result<(), ServeError> {
        let listener = listen(port_from_env(std::env::var("PORT"))).await?;
        axum::serve(listener, self.router())
            .with_graceful_shutdown(shutdown())
            .await
            .map_err(ServeError::Serve)
    }
}

/// Resolves when the process is asked to stop.
async fn shutdown() {
    let interrupt = async {
        let _ = tokio::signal::ctrl_c().await;
    };
    #[cfg(unix)]
    let terminate = async {
        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
            Ok(mut signal) => {
                signal.recv().await;
            }
            Err(_) => std::future::pending::<()>().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    tokio::select! {
        () = interrupt => {}
        () = terminate => {}
    }
}

/// The `/invocations` body: AgentCore passes the caller's payload as is.
#[derive(Deserialize)]
struct Invocation {
    prompt: String,
}

/// `Healthy`, or `HealthyBusy` while work is open, with the Unix time (in
/// seconds) the status last changed. The time moves only on a change, as
/// AgentCore's contract asks: a time that advanced on every ping would keep the
/// idle timeout from firing.
async fn ping(State(app): State<AgentCoreApp>) -> Json<serde_json::Value> {
    let (busy, since) = app.inner.busy.status();
    let status = if busy { "HealthyBusy" } else { "Healthy" };
    Json(json!({"status": status, "time_of_last_update": since}))
}

async fn invoke(
    State(app): State<AgentCoreApp>,
    headers: HeaderMap,
    body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
) -> Response {
    let invocation = match body {
        Ok(Json(invocation)) => invocation,
        Err(rejection) => {
            if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
                return error(
                    StatusCode::PAYLOAD_TOO_LARGE,
                    &format!(
                        "the request body is larger than {} bytes",
                        app.inner.max_request_bytes
                    ),
                );
            }
            return error(
                StatusCode::BAD_REQUEST,
                "the body must be a JSON object with a \"prompt\" string",
            );
        }
    };
    let streams = headers
        .get(header::ACCEPT)
        .and_then(|value| value.to_str().ok())
        .is_some_and(|accept| accept.contains("text/event-stream"));
    let session = session_header(&headers).unwrap_or_else(local_id);
    let Some(run) = start_run(&app, &headers, session, invocation.prompt) else {
        return error(StatusCode::TOO_MANY_REQUESTS, BUSY);
    };
    if streams {
        stream(app, run)
    } else {
        let span = run.span.clone();
        whole(app, run.session, run.prompt, run.slot, run.busy)
            .instrument(span)
            .await
    }
}

const BUSY: &str = "the agent is busy; try again shortly";

/// The session the caller names in the session header, when it names one.
fn session_header(headers: &HeaderMap) -> Option<String> {
    headers
        .get(SESSION_HEADER)
        .and_then(|value| value.to_str().ok())
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
}

/// A run the app has accepted: its session and prompt, its span, and the slot
/// and busy guard that count it against the app's limits and `/ping`.
struct Run {
    session: String,
    prompt: String,
    span: tracing::Span,
    slot: Option<OwnedSemaphorePermit>,
    busy: BusyGuard,
}

/// Start a run, or `None` when the app is at its concurrency cap. Checked
/// before the session is loaded, so a refused run never touches the agent or
/// the history.
fn start_run(
    app: &AgentCoreApp,
    headers: &HeaderMap,
    session: String,
    prompt: String,
) -> Option<Run> {
    // Held until the run ends, however it ends.
    let slot = match &app.inner.slots {
        None => None,
        Some(slots) => Some(Arc::clone(slots).try_acquire_owned().ok()?),
    };
    // Open for the whole run, however it ends. Opened after the slot, so a
    // refused run does not flip the status.
    let busy = app.track_task();
    // The invocation is the agent run AgentCore Evaluations looks for: an
    // `invoke_agent` span (Rig adopts it as the run's span, so it makes none
    // of its own), with the prompt and the answer when content is recorded.
    let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
    let span = tracing::info_span!(
        "agentcore.invocation",
        otel.name = %format!("invoke_agent {agent_name}"),
        otel.kind = "server",
        agentcore.session_id = %session,
        gen_ai.operation.name = "invoke_agent",
        gen_ai.agent.name = %agent_name,
        gen_ai.task.input = tracing::field::Empty,
        gen_ai.task.output = tracing::field::Empty,
        agentcore.invocation.user_prompt = tracing::field::Empty,
        agentcore.invocation.agent_response = tracing::field::Empty,
    );
    if app.inner.record_content {
        span.record("gen_ai.task.input", prompt.as_str());
        span.record("agentcore.invocation.user_prompt", prompt.as_str());
    }
    // Without an OpenTelemetry layer there is nothing to continue: fine.
    let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(headers)));
    Some(Run {
        session,
        prompt,
        span,
        slot,
        busy,
    })
}

/// The session's conversation as a request sends it: the newest messages
/// the window keeps, after a summary when the history has grown past the
/// summarizing trigger.
async fn history_of(inner: &Inner, session: &str) -> Result<Vec<Message>, HistoryError> {
    let mut messages = inner.history.load(session).await?;
    if let Some(summarizing) = &inner.summarizing
        && messages.len() > summarizing.trigger_messages
        && let Some(summarized) = summarize(
            inner.history.as_ref(),
            summarizing,
            session,
            &messages,
            inner.record_content,
        )
        .await
    {
        messages = summarized;
    }
    // The summary, when the session has one, goes first; the window applies to
    // the messages after it, so a narrow window cannot drop it.
    let mut sent = Vec::new();
    let rest = match messages.split_first() {
        Some((first, rest)) if inner.summarizing.is_some() && is_summary(first) => {
            sent.push((**first).clone());
            rest
        }
        _ => messages.as_slice(),
    };
    sent.extend(
        view(rest, inner.window.as_ref())
            .iter()
            .map(|message| (**message).clone()),
    );
    Ok(sent)
}

async fn whole(
    app: AgentCoreApp,
    session: String,
    prompt: String,
    _slot: Option<OwnedSemaphorePermit>,
    _busy: BusyGuard,
) -> Response {
    let inner = &app.inner;
    let deadline = deadline_of(inner.max_run);
    let history = match within(deadline, history_of(inner, &session)).await {
        Ok(Ok(history)) => history,
        Ok(Err(failure)) => {
            tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
            return error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "the conversation could not be loaded",
            );
        }
        Err(_) => {
            tracing::warn!(max = ?inner.max_run, "agent run took too long");
            return timed_out(inner.max_run);
        }
    };
    let run = within(
        deadline,
        inner
            .agent
            .prompt(prompt)
            .history(history)
            .record_content_telemetry(inner.record_content)
            .run(),
    )
    .await;
    match run {
        // A stopped run is dropped before `save`, so its turn is not kept.
        Err(_) => {
            tracing::warn!(max = ?inner.max_run, "agent run took too long");
            timed_out(inner.max_run)
        }
        Ok(Ok(response)) => {
            save(inner, &session, response.messages.clone()).await;
            let answer = response.output();
            record_answer(inner.record_content, &answer);
            Json(json!({"response": answer, "status": "success"})).into_response()
        }
        Ok(Err(failure)) => {
            tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
            error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
        }
    }
}

/// The deadline for an invocation's run, from the start of the invocation.
fn deadline_of(max: Option<Duration>) -> Option<tokio::time::Instant> {
    max.map(|max| tokio::time::Instant::now() + max)
}

/// `future`, stopped at `deadline` when there is one.
async fn within<F: std::future::Future>(
    deadline: Option<tokio::time::Instant>,
    future: F,
) -> Result<F::Output, tokio::time::error::Elapsed> {
    match deadline {
        Some(deadline) => tokio::time::timeout_at(deadline, future).await,
        None => Ok(future.await),
    }
}

fn timeout_text(max: Option<Duration>) -> String {
    match max {
        Some(max) => format!("the agent run took longer than {max:?}"),
        None => "the agent run took too long".to_owned(),
    }
}

fn timed_out(max: Option<Duration>) -> Response {
    error(StatusCode::GATEWAY_TIMEOUT, &timeout_text(max))
}

/// Add a finished run to its session. A save that fails is logged, not
/// reported: the answer was already produced.
async fn save(inner: &Inner, session: &str, messages: Vec<Message>) {
    // With a summarizer, the window trims the session only down to its newest
    // 2 * trigger messages, so a summary (kept first) is not dropped while it
    // is still needed, and a failing summarizer cannot grow the session forever.
    let floor = inner.summarizing.as_ref().map_or(0, |summarizing| {
        summarizing.trigger_messages.saturating_mul(2)
    });
    let retained = Retained {
        window: inner.window.as_ref(),
        floor,
    };
    let window: &dyn Recent = match inner.summarizing {
        Some(_) => &retained,
        None => inner.window.as_ref(),
    };
    if let Err(failure) = inner.history.append(session, messages, window).await {
        tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not save the conversation");
    }
}

/// Stream the reply as server-sent events, one JSON object per event.
fn stream(app: AgentCoreApp, run: Run) -> Response {
    let body = futures::stream::unfold(events(app, run, false), |mut receiver| async move {
        let data = receiver.recv().await?;
        Some((
            Ok::<_, Infallible>(Event::default().data(data.to_string())),
            receiver,
        ))
    });
    Sse::new(body).into_response()
}

/// The run's events as JSON objects: `{"text": ...}` as the model writes, then
/// `{"response": ...}` with the whole answer, or `{"error": ...}`. The run goes
/// on in a spawned task; the receiver ends when it does.
fn events(
    app: AgentCoreApp,
    run: Run,
    cancel_on_disconnect: bool,
) -> mpsc::UnboundedReceiver<serde_json::Value> {
    let Run {
        session,
        prompt,
        span,
        slot,
        busy,
    } = run;
    let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
    tokio::spawn(
        async move {
            let _slot = slot;
            let _busy = busy;
            let inner = &app.inner;
            let deadline = deadline_of(inner.max_run);
            let history = match within(deadline, history_of(inner, &session)).await {
                Ok(Ok(history)) => history,
                Ok(Err(failure)) => {
                    tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
                    let _ = sender.send(json!({"error": "the conversation could not be loaded"}));
                    return;
                }
                Err(_) => {
                    tracing::warn!(max = ?inner.max_run, "agent run took too long");
                    let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
                    return;
                }
            };
            let mut run = inner
                .agent
                .prompt(prompt)
                .history(history)
                .record_content_telemetry(inner.record_content)
                .stream();
            loop {
                // Only the agent's run is cancelled when the client goes (and only
                // on /ws). Saving a finished answer is not, so it is always kept.
                let next = if cancel_on_disconnect {
                    tokio::select! {
                        () = sender.closed() => return,
                        next = within(deadline, run.next()) => next,
                    }
                } else {
                    within(deadline, run.next()).await
                };
                let item = match next {
                    Ok(Some(item)) => item,
                    Ok(None) => break,
                    Err(_) => {
                        tracing::warn!(max = ?inner.max_run, "agent run took too long");
                        let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
                        return;
                    }
                };
                match item {
                    Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
                        StreamEvent::Text { text, .. },
                    ))) => {
                        let _ = sender.send(json!({"text": text}));
                    }
                    Ok(MultiTurnStreamItem::FinalResponse(response)) => {
                        save(inner, &session, response.messages.clone()).await;
                        let answer = response.output();
                        record_answer(inner.record_content, &answer);
                        let _ = sender.send(json!({"response": answer}));
                        return;
                    }
                    Ok(_) => {}
                    Err(failure) => {
                        tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
                        let _ = sender.send(json!({"error": "the agent run failed"}));
                        return;
                    }
                }
            }
            let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
        }
        .instrument(span),
    );
    receiver
}

/// A text message on `/ws`: the `/invocations` body, with the session it
/// names when the upgrade request named none.
#[derive(Deserialize)]
struct WsRequest {
    prompt: String,
    session_id: Option<String>,
}

/// `GET /ws`: a WebSocket where each text message is one `/invocations` body
/// and the answer comes back as frames carrying the same events as the
/// server-sent ones, plus `session_id` and `message_type`. Each message is
/// limited to `max_request_bytes`.
async fn socket(
    State(app): State<AgentCoreApp>,
    headers: HeaderMap,
    upgrade: WebSocketUpgrade,
) -> Response {
    let limit = app.inner.max_request_bytes;
    let named = session_header(&headers);
    upgrade
        .max_message_size(limit)
        .max_frame_size(limit)
        .on_upgrade(move |socket| converse(app, headers, named, socket))
}

/// One connection. A run's frames go out as they come, while the socket is
/// still read, so pings are answered and a close is seen during a run. A
/// message that arrives during a run gets a busy error frame: a connection has
/// at most one run in flight. A message that cannot be used gets an error
/// frame, and the connection stays open. When the connection ends, its run is
/// cancelled.
async fn converse(
    app: AgentCoreApp,
    headers: HeaderMap,
    named: Option<String>,
    mut socket: WebSocket,
) {
    let limit = app.inner.max_request_bytes;
    // The session for messages that name none, when the upgrade named none.
    let fallback = local_id();
    let mut running: Option<Running> = None;
    loop {
        tokio::select! {
            incoming = socket.recv() => {
                let text = match incoming {
                    Some(Ok(WsMessage::Text(text))) => text,
                    Some(Ok(WsMessage::Close(_))) | None => break,
                    // Ping and pong are answered by the socket itself.
                    Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => continue,
                    Some(Ok(WsMessage::Binary(_))) => {
                        if !send(&mut socket, error_frame(BINARY)).await {
                            break;
                        }
                        continue;
                    }
                    // Over the message limit, or a broken frame: say why, then close.
                    Some(Err(_)) => {
                        let frame = error_frame(&format!(
                            "the message could not be read; a message is limited to {limit} bytes"
                        ));
                        let _ = send(&mut socket, frame).await;
                        break;
                    }
                };
                if running.is_some() {
                    if !send(&mut socket, error_frame(BUSY)).await {
                        break;
                    }
                    continue;
                }
                let request = match serde_json::from_str::<WsRequest>(text.as_str()) {
                    Ok(request) => request,
                    Err(_) => {
                        if !send(&mut socket, error_frame(BAD_MESSAGE)).await {
                            break;
                        }
                        continue;
                    }
                };
                let session = named
                    .clone()
                    .or_else(|| request.session_id.filter(|id| !id.is_empty()))
                    .unwrap_or_else(|| fallback.clone());
                match start_run(&app, &headers, session.clone(), request.prompt) {
                    Some(run) => {
                        running = Some(Running {
                            session,
                            events: events(app.clone(), run, true),
                            stashed: None,
                        });
                    }
                    None => {
                        if !send(&mut socket, error_frame(BUSY)).await {
                            break;
                        }
                    }
                }
            }
            next = next_event(&mut running), if running.is_some() => match next {
                Some(frame) => {
                    if !send(&mut socket, frame).await {
                        break;
                    }
                }
                None => running = None,
            },
        }
    }
}

/// The run in flight on a connection.
struct Running {
    session: String,
    events: mpsc::UnboundedReceiver<serde_json::Value>,
    /// An event read while text was gathered, sent on the next call.
    stashed: Option<serde_json::Value>,
}

const BINARY: &str = "binary messages are not supported; send a text message holding a JSON object";
const BAD_MESSAGE: &str = "the message must be a JSON object with a \"prompt\" string";

/// Send one JSON frame. False when the client has gone.
async fn send(socket: &mut WebSocket, frame: serde_json::Value) -> bool {
    socket
        .send(WsMessage::Text(frame.to_string().into()))
        .await
        .is_ok()
}

/// Text deltas that arrive within this window go out in one frame, so a model
/// that streams a token at a time sends at most 100 text frames a second. The
/// WebSocket frame rate limit is 250 frames a second per connection.
const TEXT_WINDOW: Duration = Duration::from_millis(10);

/// Text gathered into one frame stops at this many bytes, well under the
/// 64 KB frame limit.
const TEXT_FRAME_BYTES: usize = 16 * 1024;

/// The WebSocket frame size limit AgentCore Runtime enforces.
const MAX_FRAME_BYTES: usize = 64 * 1024;

/// The next frame of the run in flight, or `None` when that run has ended.
/// Waits forever when no run is in flight; the caller's condition rules that out.
async fn next_event(running: &mut Option<Running>) -> Option<serde_json::Value> {
    let Some(running) = running else {
        return std::future::pending().await;
    };
    let event = match running.stashed.take() {
        Some(event) => event,
        None => running.events.recv().await?,
    };
    let Some(mut text) = text_of(&event).map(str::to_owned) else {
        return Some(frame(&event, &running.session));
    };
    let window = tokio::time::sleep(TEXT_WINDOW);
    tokio::pin!(window);
    while text.len() < TEXT_FRAME_BYTES {
        tokio::select! {
            () = &mut window => break,
            next = running.events.recv() => match next {
                None => break,
                Some(next) => match text_of(&next) {
                    Some(more) => text.push_str(more),
                    None => {
                        running.stashed = Some(next);
                        break;
                    }
                },
            },
        }
    }
    Some(frame(&json!({"text": text}), &running.session))
}

fn text_of(event: &serde_json::Value) -> Option<&str> {
    event.get("text").and_then(serde_json::Value::as_str)
}

/// An event from [`events`] as a frame: the same object, with the session and
/// the kind of message it is. A frame over the 64 KB limit becomes an error
/// frame, since the connection would otherwise be closed.
fn frame(event: &serde_json::Value, session: &str) -> serde_json::Value {
    let kind = if event.get("error").is_some() {
        "error"
    } else if event.get("response").is_some() {
        "agent_response"
    } else {
        "agent_text"
    };
    let mut frame = event.clone();
    if let Some(object) = frame.as_object_mut() {
        object.insert("session_id".to_owned(), json!(session));
        object.insert("message_type".to_owned(), json!(kind));
    }
    if frame.to_string().len() > MAX_FRAME_BYTES {
        return error_frame(
            "the reply is larger than the 64 KB WebSocket frame limit; its text was streamed in agent_text frames, or use /invocations",
        );
    }
    frame
}

fn error_frame(message: &str) -> serde_json::Value {
    json!({"error": message, "status": "error", "message_type": "error"})
}

/// What a log line says about a failure. A provider's error text can echo the
/// prompt, so it is logged only with `record_content`; otherwise its kind is.
pub(crate) fn logged(
    record_content: bool,
    kind: &'static str,
    failure: &dyn std::fmt::Display,
) -> String {
    if record_content {
        failure.to_string()
    } else {
        kind.to_owned()
    }
}

/// Record the agent's answer on the invocation span, the current one.
fn record_answer(record_content: bool, answer: &str) {
    if record_content {
        let span = tracing::Span::current();
        span.record("gen_ai.task.output", answer);
        span.record("agentcore.invocation.agent_response", answer);
    }
}

fn error(status: StatusCode, message: &str) -> Response {
    (status, Json(json!({"error": message, "status": "error"}))).into_response()
}

/// The port `PORT` names, or [`DEFAULT_PORT`] when it is not set. A value
/// that is not a port number warns and also gets [`DEFAULT_PORT`].
fn port_from_env(value: Result<String, std::env::VarError>) -> u16 {
    let value = match value {
        Ok(value) => value,
        Err(std::env::VarError::NotPresent) => return DEFAULT_PORT,
        Err(std::env::VarError::NotUnicode(value)) => value.to_string_lossy().into_owned(),
    };
    value.parse().unwrap_or_else(|_| {
        tracing::warn!(
            port = %value,
            "PORT is not a port number from 0 to 65535; serving on {DEFAULT_PORT} instead"
        );
        DEFAULT_PORT
    })
}

/// Listen on every interface at `port`.
async fn listen(port: u16) -> Result<tokio::net::TcpListener, ServeError> {
    let address = SocketAddr::from(([0, 0, 0, 0], port));
    tokio::net::TcpListener::bind(address)
        .await
        .map_err(|source| ServeError::Bind { address, source })
}

#[cfg(test)]
mod tests {
    use std::env::VarError;

    use super::*;

    #[test]
    fn the_port_comes_from_env_or_the_default() {
        assert_eq!(port_from_env(Ok("3200".into())), 3200);
        assert_eq!(port_from_env(Err(VarError::NotPresent)), DEFAULT_PORT);
    }

    #[test]
    fn a_bad_port_falls_back_to_the_default() {
        for bad in ["", "abc", "70000", "-1", " 8080"] {
            assert_eq!(port_from_env(Ok(bad.into())), DEFAULT_PORT, "{bad:?}");
        }
    }

    #[tokio::test]
    async fn a_busy_port_is_an_error_that_names_the_address() {
        let held = listen(0).await.unwrap();
        let port = held.local_addr().unwrap().port();
        let message = listen(port)
            .await
            .err()
            .map(|e| e.to_string())
            .unwrap_or_default();
        assert!(
            message.starts_with(&format!("could not listen on 0.0.0.0:{port}: ")),
            "{message}"
        );
    }
}

#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_doctests {}