Skip to main content

rig_agentcore/
lib.rs

1//! Run a [Rig](https://github.com/0xPlaygrounds/rig) agent on AWS Bedrock
2//! AgentCore Runtime.
3//!
4//! AgentCore runs an agent as an ARM64 container that serves its HTTP
5//! protocol contract on port 8080: `POST /invocations` with a JSON body,
6//! answered with JSON or server-sent events, `GET /ping`, and the WebSocket
7//! `/ws`, where each text message is one JSON prompt. Each runtime
8//! session (the `X-Amzn-Bedrock-AgentCore-Runtime-Session-Id` header) is one
9//! conversation. [`AgentCoreApp`] serves that contract for a Rig agent:
10//!
11//! - the session's conversation is kept between invocations, in memory or in
12//!   any [`rig_memory`] store (see [`AgentCoreApp::history_store`]);
13//! - the reply streams as server-sent events when the caller asks for
14//!   `text/event-stream`, and is one JSON object otherwise;
15//! - each invocation runs in a span that continues the caller's trace and
16//!   carries the session as `session.id` (through [`rig_otel`]), which is what
17//!   AgentCore Observability and Evaluations group a session's traces by;
18//! - `/ping` answers `HealthyBusy` while an invocation or background work from
19//!   [`AgentCoreApp::spawn_task`] is open, so AgentCore Runtime keeps the
20//!   session running until that work ends.
21//!
22//! - prompts and replies go on the spans only with
23//!   [`AgentCoreApp::record_content`] (off by default, as in Rig). AgentCore
24//!   Evaluations needs them to judge a session. The app's setting overrides
25//!   the agent's own `record_content_telemetry`, so set it on the app.
26//!
27//! ```no_run
28//! async fn run(agent: rig_agent::Agent) -> Result<(), rig_agentcore::ServeError> {
29//!     rig_agentcore::AgentCoreApp::new(agent)
30//!         .record_content(true)
31//!         .serve()
32//!         .await
33//! }
34//! ```
35
36#![forbid(unsafe_code)]
37#![cfg_attr(docsrs, feature(doc_cfg))]
38#![cfg_attr(
39    test,
40    allow(
41        clippy::expect_used,
42        clippy::panic,
43        clippy::unwrap_used,
44        clippy::unreachable
45    )
46)]
47
48mod busy;
49mod history;
50
51use std::convert::Infallible;
52use std::future::Future;
53use std::net::SocketAddr;
54use std::sync::Arc;
55use std::time::Duration;
56
57use axum::Json;
58use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
59use axum::extract::{DefaultBodyLimit, State};
60use axum::http::{HeaderMap, StatusCode, header};
61use axum::response::sse::{Event, Sse};
62use axum::response::{IntoResponse, Response};
63use axum::routing::{get, post};
64use futures::StreamExt;
65use rig_agent::Agent;
66use rig_agent::agent::MultiTurnStreamItem;
67use rig_core::message::Message;
68use rig_core::streaming::{Item, StreamEvent};
69use rig_core::wasm_compat::{WasmCompatSend, WasmCompatSync};
70use rig_memory::AsyncStore;
71use rig_memory::recent::{Recent, TokenBudget, view};
72use serde::Deserialize;
73use serde_json::json;
74use tokio::sync::mpsc;
75use tokio::sync::{OwnedSemaphorePermit, Semaphore};
76use tracing::Instrument;
77
78use crate::busy::Busy;
79use crate::history::{
80    HistoryError, HistoryStore, InMemory, Persistent, Retained, Summarizing, is_summary, local_id,
81    summarize,
82};
83
84/// The header AgentCore Runtime names the session with.
85pub const SESSION_HEADER: &str = "x-amzn-bedrock-agentcore-runtime-session-id";
86
87/// The port AgentCore Runtime sends the HTTP protocol to.
88pub const DEFAULT_PORT: u16 = 8080;
89
90/// How many sessions an app keeps by default. AgentCore gives each session
91/// its own microVM, so one process usually sees one; this bounds the memory
92/// when the app runs elsewhere.
93pub const DEFAULT_MAX_SESSIONS: usize = 1000;
94
95/// How many tokens of history a session keeps by default.
96pub const DEFAULT_HISTORY_TOKENS: usize = 32_000;
97
98/// The largest `/invocations` body by default, in bytes: the limit Axum's JSON
99/// extractor already applied. A larger body gets 413.
100pub const DEFAULT_MAX_REQUEST_BYTES: usize = 2 * 1024 * 1024;
101
102pub use busy::BusyGuard;
103/// The session stores and history windows conversations are kept with.
104pub use rig_memory;
105
106/// Why the app stopped serving.
107#[derive(Debug, thiserror::Error)]
108#[non_exhaustive]
109pub enum ServeError {
110    /// The port could not be bound.
111    #[error("could not listen on {address}: {source}")]
112    Bind {
113        /// The address.
114        address: SocketAddr,
115        /// The error.
116        #[source]
117        source: std::io::Error,
118    },
119    /// Serving failed.
120    #[error("serving failed: {0}")]
121    Serve(#[source] std::io::Error),
122}
123
124/// A Rig agent served on AgentCore Runtime's HTTP protocol contract.
125#[derive(Clone)]
126pub struct AgentCoreApp {
127    inner: Arc<Inner>,
128}
129
130#[derive(Clone)]
131struct Inner {
132    agent: Agent,
133    history: Arc<dyn HistoryStore>,
134    window: Arc<dyn Recent>,
135    summarizing: Option<Summarizing>,
136    record_content: bool,
137    slots: Option<Arc<Semaphore>>,
138    max_run: Option<Duration>,
139    max_request_bytes: usize,
140    busy: Arc<Busy>,
141}
142
143impl AgentCoreApp {
144    /// Serve `agent`.
145    pub fn new(agent: Agent) -> Self {
146        Self {
147            inner: Arc::new(Inner {
148                agent,
149                history: Arc::new(InMemory::new(DEFAULT_MAX_SESSIONS)),
150                window: Arc::new(TokenBudget::new(DEFAULT_HISTORY_TOKENS)),
151                summarizing: None,
152                record_content: false,
153                slots: None,
154                max_run: None,
155                max_request_bytes: DEFAULT_MAX_REQUEST_BYTES,
156                busy: Busy::new(),
157            }),
158        }
159    }
160
161    /// Keep at most `max` sessions' conversations in memory, forgetting the
162    /// oldest. This is the default, with [`DEFAULT_MAX_SESSIONS`]. It replaces
163    /// a store set with [`history_store`](Self::history_store).
164    #[must_use]
165    pub fn max_sessions(self, max: usize) -> Self {
166        self.rebuild(|inner| inner.history = Arc::new(InMemory::new(max)))
167    }
168
169    /// Keep sessions in `store`, one session log per session id, so they
170    /// survive restarts and several apps can share them: any [`rig_memory`]
171    /// store, such as `rig_memory::DirStore` (feature `fs`) or the
172    /// `rig-sqlite` and `rig-postgres` stores. Any session id works: one that
173    /// is 1 to 128 ASCII letters, digits, `-` or `_` names its log as it is,
174    /// any other is hashed into a safe log name. Two apps, or concurrent
175    /// invocations of one session, saving at once do not lose either turn: a
176    /// save that loses a race rereads and retries up to 10 times with a short
177    /// jittered backoff. If a save still fails, the invocation's answer is
178    /// returned anyway, the failure is logged, and that run's turn is not
179    /// persisted, so later invocations do not see it. A load that fails is
180    /// reported to the caller as an error, before the agent runs. The store
181    /// keeps each session's whole conversation;
182    /// [`history_window`](Self::history_window) limits only what an invocation
183    /// sends. Replaces the in-memory store set by [`max_sessions`](Self::max_sessions).
184    #[must_use]
185    pub fn history_store<S>(self, store: S) -> Self
186    where
187        S: AsyncStore + WasmCompatSend + WasmCompatSync + 'static,
188    {
189        self.rebuild(|inner| inner.history = Arc::new(Persistent(store)))
190    }
191
192    /// Which newest messages of a session each invocation sends the model,
193    /// such as `rig_memory::recent::TokenBudget::new(8_000)` or
194    /// `LastMessages(20)`. Defaults to [`DEFAULT_HISTORY_TOKENS`] tokens. A
195    /// tool result is never sent without its call. An empty window
196    /// (`TokenBudget::new(0)`, `LastMessages(0)`) sends no history.
197    ///
198    /// With [`summarize_history`](Self::summarize_history), the summary is
199    /// sent first, and the window limits only the messages after it.
200    ///
201    /// What the window also does depends on the store. In memory, messages
202    /// beyond it are forgotten when a run is saved, so memory stays bounded.
203    /// With [`history_store`](Self::history_store), the store keeps the whole
204    /// conversation and the window only limits what is sent, so a later,
205    /// wider window sees older turns again.
206    #[must_use]
207    pub fn history_window(self, window: impl Recent + 'static) -> Self {
208        self.rebuild(|inner| inner.window = Arc::new(window))
209    }
210
211    /// Summarize a session's older history with `summarizer` once the session
212    /// holds more than `trigger_messages` messages. The messages before the
213    /// newest `keep_recent` are replaced by one summary, which becomes the
214    /// session's first message: a user message in rig-memory's compaction frame
215    /// ("The conversation history before this point was compacted into the
216    /// following summary: <summary>...</summary>"). The newest messages stay
217    /// verbatim, and the cut never separates a tool call from its result.
218    ///
219    /// The summary is always sent first, before the messages the window keeps,
220    /// even when the window is narrower than the summary and the kept messages.
221    /// In a session this option summarizes, a first message that opens with
222    /// rig-memory's summary frame text is treated as the summary, even if a
223    /// caller wrote it.
224    /// `summarizer` should be an agent without tools: a tool call in its reply
225    /// is not used. `trigger_messages` is raised to `keep_recent + 1` when it is
226    /// not larger, since a cut needs something older than the kept messages.
227    ///
228    /// Summarizing runs before the invocation answers. Two concurrent
229    /// invocations of one session may both summarize. A summary whose session
230    /// changed under it (a concurrent summary, or a refused save to the store)
231    /// is skipped and the history is kept, not lost.
232    ///
233    /// If a summary fails (the summarizer errors or returns no text, or the
234    /// store refuses the change), a warning is logged, the session keeps its
235    /// history, and the invocation answers as usual. The next invocation tries
236    /// again. Without a store, a session whose summaries keep failing keeps at
237    /// least its newest `2 * trigger_messages` messages, so memory stays
238    /// bounded; older messages are dropped. With
239    /// [`history_store`](Self::history_store), the store keeps the whole
240    /// conversation as it does without summaries.
241    ///
242    /// Without a store, the summary is kept in memory with the session. With
243    /// [`history_store`](Self::history_store), the summary is written to the
244    /// store's log in place of the messages it replaces, which the log keeps in
245    /// its history.
246    ///
247    /// Each attempt is traced as an `agentcore.summarize` span under the
248    /// invocation span. It records the messages summarized and kept, the
249    /// outcome (`summarized`, `skipped_changed`, `skipped_nothing_older` or
250    /// `failed`), and the summarizer's token usage when the provider reports
251    /// it. The prompt and the summary text are recorded only with
252    /// [`record_content`](Self::record_content), as the other GenAI content is.
253    #[must_use]
254    pub fn summarize_history(
255        self,
256        summarizer: Agent,
257        keep_recent: usize,
258        trigger_messages: usize,
259    ) -> Self {
260        let trigger_messages = trigger_messages.max(keep_recent.saturating_add(1));
261        self.rebuild(|inner| {
262            inner.summarizing = Some(Summarizing {
263                summarizer,
264                keep_recent,
265                trigger_messages,
266            });
267        })
268    }
269
270    /// Record prompts and replies on the GenAI spans. AgentCore Evaluations
271    /// needs them to judge a session; they are off by default, as in Rig,
272    /// because they put conversation content into your telemetry.
273    ///
274    /// This setting always overrides the agent's own
275    /// `AgentBuilder::record_content_telemetry`. The app passes its value to
276    /// every invocation, so the agent's setting is ignored when the agent is
277    /// served through `AgentCoreApp`. To record content, call
278    /// `.record_content(true)` on the app. The default here is `false`, so an
279    /// agent built with `record_content_telemetry(true)` still records nothing
280    /// unless the app sets it too. This is planned to change in 0.48 (PR #42),
281    /// so that an app setting left unset keeps the agent's.
282    #[must_use]
283    pub fn record_content(self, record: bool) -> Self {
284        self.rebuild(|inner| inner.record_content = record)
285    }
286
287    /// Run at most `max` invocations at once (at least one). An invocation
288    /// beyond that gets 429 Too Many Requests before the agent runs; 429 is the
289    /// conventional throttle status. Without this there is no cap, which is the
290    /// default: AgentCore Runtime gives each session its own microVM. Outside
291    /// AgentCore Runtime, a cap around 32 suits most single-process apps.
292    #[must_use]
293    pub fn max_concurrent_tasks(self, max: usize) -> Self {
294        self.rebuild(|inner| inner.slots = Some(Arc::new(Semaphore::new(max.max(1)))))
295    }
296
297    /// Stop an invocation that runs longer than `max`, counting the summarizing
298    /// step that can run before it. A stopped invocation answers 504 Gateway
299    /// Timeout (or an `{"error"}` event when streaming), and its turn is not
300    /// added to the session. Without this there is no limit, which is the
301    /// default. Outside AgentCore Runtime, ten minutes suits most agents.
302    #[must_use]
303    pub fn max_run_duration(self, max: Duration) -> Self {
304        self.rebuild(|inner| inner.max_run = Some(max))
305    }
306
307    /// Refuse an `/invocations` body larger than `bytes` with 413 Payload Too
308    /// Large, before it is parsed. Defaults to [`DEFAULT_MAX_REQUEST_BYTES`].
309    #[must_use]
310    pub fn max_request_bytes(self, bytes: usize) -> Self {
311        self.rebuild(|inner| inner.max_request_bytes = bytes)
312    }
313
314    /// Mark background work as open until the returned guard drops. While any
315    /// guard is alive, `/ping` answers `HealthyBusy`, so AgentCore Runtime keeps
316    /// the session running; once they are all dropped it answers `Healthy`
317    /// again. Use it for work that outlives an invocation, such as a task the
318    /// app starts on its own.
319    pub fn track_task(&self) -> BusyGuard {
320        Busy::open(&self.inner.busy)
321    }
322
323    /// Run `future` on the Tokio runtime as background work. `/ping` answers
324    /// `HealthyBusy` until it finishes, or until its task is aborted. Dropping
325    /// the returned handle does not stop the task. Call it on a running Tokio
326    /// runtime, as for [`tokio::spawn`].
327    ///
328    /// ```no_run
329    /// # async fn run(app: &rig_agentcore::AgentCoreApp) {
330    /// app.spawn_task(async {
331    ///     // Work that outlives the invocation that started it.
332    /// });
333    /// # }
334    /// ```
335    pub fn spawn_task<F>(&self, future: F) -> tokio::task::JoinHandle<F::Output>
336    where
337        F: Future + Send + 'static,
338        F::Output: Send + 'static,
339    {
340        let guard = self.track_task();
341        tokio::spawn(async move {
342            let _guard = guard;
343            future.await
344        })
345    }
346
347    fn rebuild(self, change: impl FnOnce(&mut Inner)) -> Self {
348        let mut inner = Arc::try_unwrap(self.inner).unwrap_or_else(|shared| (*shared).clone());
349        change(&mut inner);
350        Self {
351            inner: Arc::new(inner),
352        }
353    }
354
355    /// The contract's routes, `/invocations`, `/ping` and the WebSocket `/ws`,
356    /// as an Axum router.
357    pub fn router(self) -> axum::Router {
358        let limit = self.inner.max_request_bytes;
359        axum::Router::new()
360            .route(
361                "/invocations",
362                post(invoke).layer(DefaultBodyLimit::max(limit)),
363            )
364            .route("/ping", get(ping))
365            .route("/ws", get(socket))
366            .with_state(self)
367    }
368
369    /// Serve on `0.0.0.0` at `PORT` (default 8080, what AgentCore sends to)
370    /// until the process gets Ctrl-C or SIGTERM. A `PORT` that is set but is
371    /// not a port number logs a warning and serves on the default.
372    pub async fn serve(self) -> Result<(), ServeError> {
373        let listener = listen(port_from_env(std::env::var("PORT"))).await?;
374        axum::serve(listener, self.router())
375            .with_graceful_shutdown(shutdown())
376            .await
377            .map_err(ServeError::Serve)
378    }
379}
380
381/// Resolves when the process is asked to stop.
382async fn shutdown() {
383    let interrupt = async {
384        let _ = tokio::signal::ctrl_c().await;
385    };
386    #[cfg(unix)]
387    let terminate = async {
388        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
389            Ok(mut signal) => {
390                signal.recv().await;
391            }
392            Err(_) => std::future::pending::<()>().await,
393        }
394    };
395    #[cfg(not(unix))]
396    let terminate = std::future::pending::<()>();
397    tokio::select! {
398        () = interrupt => {}
399        () = terminate => {}
400    }
401}
402
403/// The `/invocations` body: AgentCore passes the caller's payload as is.
404#[derive(Deserialize)]
405struct Invocation {
406    prompt: String,
407}
408
409/// `Healthy`, or `HealthyBusy` while work is open, with the Unix time (in
410/// seconds) the status last changed. The time moves only on a change, as
411/// AgentCore's contract asks: a time that advanced on every ping would keep the
412/// idle timeout from firing.
413async fn ping(State(app): State<AgentCoreApp>) -> Json<serde_json::Value> {
414    let (busy, since) = app.inner.busy.status();
415    let status = if busy { "HealthyBusy" } else { "Healthy" };
416    Json(json!({"status": status, "time_of_last_update": since}))
417}
418
419async fn invoke(
420    State(app): State<AgentCoreApp>,
421    headers: HeaderMap,
422    body: Result<Json<Invocation>, axum::extract::rejection::JsonRejection>,
423) -> Response {
424    let invocation = match body {
425        Ok(Json(invocation)) => invocation,
426        Err(rejection) => {
427            if rejection.into_response().status() == StatusCode::PAYLOAD_TOO_LARGE {
428                return error(
429                    StatusCode::PAYLOAD_TOO_LARGE,
430                    &format!(
431                        "the request body is larger than {} bytes",
432                        app.inner.max_request_bytes
433                    ),
434                );
435            }
436            return error(
437                StatusCode::BAD_REQUEST,
438                "the body must be a JSON object with a \"prompt\" string",
439            );
440        }
441    };
442    let streams = headers
443        .get(header::ACCEPT)
444        .and_then(|value| value.to_str().ok())
445        .is_some_and(|accept| accept.contains("text/event-stream"));
446    let session = session_header(&headers).unwrap_or_else(local_id);
447    let Some(run) = start_run(&app, &headers, session, invocation.prompt) else {
448        return error(StatusCode::TOO_MANY_REQUESTS, BUSY);
449    };
450    if streams {
451        stream(app, run)
452    } else {
453        let span = run.span.clone();
454        whole(app, run.session, run.prompt, run.slot, run.busy)
455            .instrument(span)
456            .await
457    }
458}
459
460const BUSY: &str = "the agent is busy; try again shortly";
461
462/// The session the caller names in the session header, when it names one.
463fn session_header(headers: &HeaderMap) -> Option<String> {
464    headers
465        .get(SESSION_HEADER)
466        .and_then(|value| value.to_str().ok())
467        .filter(|value| !value.is_empty())
468        .map(str::to_owned)
469}
470
471/// A run the app has accepted: its session and prompt, its span, and the slot
472/// and busy guard that count it against the app's limits and `/ping`.
473struct Run {
474    session: String,
475    prompt: String,
476    span: tracing::Span,
477    slot: Option<OwnedSemaphorePermit>,
478    busy: BusyGuard,
479}
480
481/// Start a run, or `None` when the app is at its concurrency cap. Checked
482/// before the session is loaded, so a refused run never touches the agent or
483/// the history.
484fn start_run(
485    app: &AgentCoreApp,
486    headers: &HeaderMap,
487    session: String,
488    prompt: String,
489) -> Option<Run> {
490    // Held until the run ends, however it ends.
491    let slot = match &app.inner.slots {
492        None => None,
493        Some(slots) => Some(Arc::clone(slots).try_acquire_owned().ok()?),
494    };
495    // Open for the whole run, however it ends. Opened after the slot, so a
496    // refused run does not flip the status.
497    let busy = app.track_task();
498    // The invocation is the agent run AgentCore Evaluations looks for: an
499    // `invoke_agent` span (Rig adopts it as the run's span, so it makes none
500    // of its own), with the prompt and the answer when content is recorded.
501    let agent_name = app.inner.agent.name().unwrap_or("agent").to_owned();
502    let span = tracing::info_span!(
503        "agentcore.invocation",
504        otel.name = %format!("invoke_agent {agent_name}"),
505        otel.kind = "server",
506        agentcore.session_id = %session,
507        gen_ai.operation.name = "invoke_agent",
508        gen_ai.agent.name = %agent_name,
509        gen_ai.task.input = tracing::field::Empty,
510        gen_ai.task.output = tracing::field::Empty,
511        agentcore.invocation.user_prompt = tracing::field::Empty,
512        agentcore.invocation.agent_response = tracing::field::Empty,
513    );
514    if app.inner.record_content {
515        span.record("gen_ai.task.input", prompt.as_str());
516        span.record("agentcore.invocation.user_prompt", prompt.as_str());
517    }
518    // Without an OpenTelemetry layer there is nothing to continue: fine.
519    let _ = rig_otel::set_session(&span, session.clone(), Some(rig_otel::extract(headers)));
520    Some(Run {
521        session,
522        prompt,
523        span,
524        slot,
525        busy,
526    })
527}
528
529/// The session's conversation as a request sends it: the newest messages
530/// the window keeps, after a summary when the history has grown past the
531/// summarizing trigger.
532async fn history_of(inner: &Inner, session: &str) -> Result<Vec<Message>, HistoryError> {
533    let mut messages = inner.history.load(session).await?;
534    if let Some(summarizing) = &inner.summarizing
535        && messages.len() > summarizing.trigger_messages
536        && let Some(summarized) = summarize(
537            inner.history.as_ref(),
538            summarizing,
539            session,
540            &messages,
541            inner.record_content,
542        )
543        .await
544    {
545        messages = summarized;
546    }
547    // The summary, when the session has one, goes first; the window applies to
548    // the messages after it, so a narrow window cannot drop it.
549    let mut sent = Vec::new();
550    let rest = match messages.split_first() {
551        Some((first, rest)) if inner.summarizing.is_some() && is_summary(first) => {
552            sent.push((**first).clone());
553            rest
554        }
555        _ => messages.as_slice(),
556    };
557    sent.extend(
558        view(rest, inner.window.as_ref())
559            .iter()
560            .map(|message| (**message).clone()),
561    );
562    Ok(sent)
563}
564
565async fn whole(
566    app: AgentCoreApp,
567    session: String,
568    prompt: String,
569    _slot: Option<OwnedSemaphorePermit>,
570    _busy: BusyGuard,
571) -> Response {
572    let inner = &app.inner;
573    let deadline = deadline_of(inner.max_run);
574    let history = match within(deadline, history_of(inner, &session)).await {
575        Ok(Ok(history)) => history,
576        Ok(Err(failure)) => {
577            tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
578            return error(
579                StatusCode::INTERNAL_SERVER_ERROR,
580                "the conversation could not be loaded",
581            );
582        }
583        Err(_) => {
584            tracing::warn!(max = ?inner.max_run, "agent run took too long");
585            return timed_out(inner.max_run);
586        }
587    };
588    let run = within(
589        deadline,
590        inner
591            .agent
592            .prompt(prompt)
593            .history(history)
594            .record_content_telemetry(inner.record_content)
595            .run(),
596    )
597    .await;
598    match run {
599        // A stopped run is dropped before `save`, so its turn is not kept.
600        Err(_) => {
601            tracing::warn!(max = ?inner.max_run, "agent run took too long");
602            timed_out(inner.max_run)
603        }
604        Ok(Ok(response)) => {
605            save(inner, &session, response.messages.clone()).await;
606            let answer = response.output();
607            record_answer(inner.record_content, &answer);
608            Json(json!({"response": answer, "status": "success"})).into_response()
609        }
610        Ok(Err(failure)) => {
611            tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
612            error(StatusCode::INTERNAL_SERVER_ERROR, "the agent run failed")
613        }
614    }
615}
616
617/// The deadline for an invocation's run, from the start of the invocation.
618fn deadline_of(max: Option<Duration>) -> Option<tokio::time::Instant> {
619    max.map(|max| tokio::time::Instant::now() + max)
620}
621
622/// `future`, stopped at `deadline` when there is one.
623async fn within<F: std::future::Future>(
624    deadline: Option<tokio::time::Instant>,
625    future: F,
626) -> Result<F::Output, tokio::time::error::Elapsed> {
627    match deadline {
628        Some(deadline) => tokio::time::timeout_at(deadline, future).await,
629        None => Ok(future.await),
630    }
631}
632
633fn timeout_text(max: Option<Duration>) -> String {
634    match max {
635        Some(max) => format!("the agent run took longer than {max:?}"),
636        None => "the agent run took too long".to_owned(),
637    }
638}
639
640fn timed_out(max: Option<Duration>) -> Response {
641    error(StatusCode::GATEWAY_TIMEOUT, &timeout_text(max))
642}
643
644/// Add a finished run to its session. A save that fails is logged, not
645/// reported: the answer was already produced.
646async fn save(inner: &Inner, session: &str, messages: Vec<Message>) {
647    // With a summarizer, the window trims the session only down to its newest
648    // 2 * trigger messages, so a summary (kept first) is not dropped while it
649    // is still needed, and a failing summarizer cannot grow the session forever.
650    let floor = inner.summarizing.as_ref().map_or(0, |summarizing| {
651        summarizing.trigger_messages.saturating_mul(2)
652    });
653    let retained = Retained {
654        window: inner.window.as_ref(),
655        floor,
656    };
657    let window: &dyn Recent = match inner.summarizing {
658        Some(_) => &retained,
659        None => inner.window.as_ref(),
660    };
661    if let Err(failure) = inner.history.append(session, messages, window).await {
662        tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not save the conversation");
663    }
664}
665
666/// Stream the reply as server-sent events, one JSON object per event.
667fn stream(app: AgentCoreApp, run: Run) -> Response {
668    let body = futures::stream::unfold(events(app, run, false), |mut receiver| async move {
669        let data = receiver.recv().await?;
670        Some((
671            Ok::<_, Infallible>(Event::default().data(data.to_string())),
672            receiver,
673        ))
674    });
675    Sse::new(body).into_response()
676}
677
678/// The run's events as JSON objects: `{"text": ...}` as the model writes, then
679/// `{"response": ...}` with the whole answer, or `{"error": ...}`. The run goes
680/// on in a spawned task; the receiver ends when it does.
681fn events(
682    app: AgentCoreApp,
683    run: Run,
684    cancel_on_disconnect: bool,
685) -> mpsc::UnboundedReceiver<serde_json::Value> {
686    let Run {
687        session,
688        prompt,
689        span,
690        slot,
691        busy,
692    } = run;
693    let (sender, receiver) = mpsc::unbounded_channel::<serde_json::Value>();
694    tokio::spawn(
695        async move {
696            let _slot = slot;
697            let _busy = busy;
698            let inner = &app.inner;
699            let deadline = deadline_of(inner.max_run);
700            let history = match within(deadline, history_of(inner, &session)).await {
701                Ok(Ok(history)) => history,
702                Ok(Err(failure)) => {
703                    tracing::warn!(error = %logged(inner.record_content, "store_error", &failure), "could not load the conversation");
704                    let _ = sender.send(json!({"error": "the conversation could not be loaded"}));
705                    return;
706                }
707                Err(_) => {
708                    tracing::warn!(max = ?inner.max_run, "agent run took too long");
709                    let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
710                    return;
711                }
712            };
713            let mut run = inner
714                .agent
715                .prompt(prompt)
716                .history(history)
717                .record_content_telemetry(inner.record_content)
718                .stream();
719            loop {
720                // Only the agent's run is cancelled when the client goes (and only
721                // on /ws). Saving a finished answer is not, so it is always kept.
722                let next = if cancel_on_disconnect {
723                    tokio::select! {
724                        () = sender.closed() => return,
725                        next = within(deadline, run.next()) => next,
726                    }
727                } else {
728                    within(deadline, run.next()).await
729                };
730                let item = match next {
731                    Ok(Some(item)) => item,
732                    Ok(None) => break,
733                    Err(_) => {
734                        tracing::warn!(max = ?inner.max_run, "agent run took too long");
735                        let _ = sender.send(json!({"error": timeout_text(inner.max_run)}));
736                        return;
737                    }
738                };
739                match item {
740                    Ok(MultiTurnStreamItem::StreamAssistantItem(Item::Event(
741                        StreamEvent::Text { text, .. },
742                    ))) => {
743                        let _ = sender.send(json!({"text": text}));
744                    }
745                    Ok(MultiTurnStreamItem::FinalResponse(response)) => {
746                        save(inner, &session, response.messages.clone()).await;
747                        let answer = response.output();
748                        record_answer(inner.record_content, &answer);
749                        let _ = sender.send(json!({"response": answer}));
750                        return;
751                    }
752                    Ok(_) => {}
753                    Err(failure) => {
754                        tracing::warn!(error = %logged(inner.record_content, "run_failed", &failure), "agent run failed");
755                        let _ = sender.send(json!({"error": "the agent run failed"}));
756                        return;
757                    }
758                }
759            }
760            let _ = sender.send(json!({"error": "the agent run ended without an answer"}));
761        }
762        .instrument(span),
763    );
764    receiver
765}
766
767/// A text message on `/ws`: the `/invocations` body, with the session it
768/// names when the upgrade request named none.
769#[derive(Deserialize)]
770struct WsRequest {
771    prompt: String,
772    session_id: Option<String>,
773}
774
775/// `GET /ws`: a WebSocket where each text message is one `/invocations` body
776/// and the answer comes back as frames carrying the same events as the
777/// server-sent ones, plus `session_id` and `message_type`. Each message is
778/// limited to `max_request_bytes`.
779async fn socket(
780    State(app): State<AgentCoreApp>,
781    headers: HeaderMap,
782    upgrade: WebSocketUpgrade,
783) -> Response {
784    let limit = app.inner.max_request_bytes;
785    let named = session_header(&headers);
786    upgrade
787        .max_message_size(limit)
788        .max_frame_size(limit)
789        .on_upgrade(move |socket| converse(app, headers, named, socket))
790}
791
792/// One connection. A run's frames go out as they come, while the socket is
793/// still read, so pings are answered and a close is seen during a run. A
794/// message that arrives during a run gets a busy error frame: a connection has
795/// at most one run in flight. A message that cannot be used gets an error
796/// frame, and the connection stays open. When the connection ends, its run is
797/// cancelled.
798async fn converse(
799    app: AgentCoreApp,
800    headers: HeaderMap,
801    named: Option<String>,
802    mut socket: WebSocket,
803) {
804    let limit = app.inner.max_request_bytes;
805    // The session for messages that name none, when the upgrade named none.
806    let fallback = local_id();
807    let mut running: Option<Running> = None;
808    loop {
809        tokio::select! {
810            incoming = socket.recv() => {
811                let text = match incoming {
812                    Some(Ok(WsMessage::Text(text))) => text,
813                    Some(Ok(WsMessage::Close(_))) | None => break,
814                    // Ping and pong are answered by the socket itself.
815                    Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => continue,
816                    Some(Ok(WsMessage::Binary(_))) => {
817                        if !send(&mut socket, error_frame(BINARY)).await {
818                            break;
819                        }
820                        continue;
821                    }
822                    // Over the message limit, or a broken frame: say why, then close.
823                    Some(Err(_)) => {
824                        let frame = error_frame(&format!(
825                            "the message could not be read; a message is limited to {limit} bytes"
826                        ));
827                        let _ = send(&mut socket, frame).await;
828                        break;
829                    }
830                };
831                if running.is_some() {
832                    if !send(&mut socket, error_frame(BUSY)).await {
833                        break;
834                    }
835                    continue;
836                }
837                let request = match serde_json::from_str::<WsRequest>(text.as_str()) {
838                    Ok(request) => request,
839                    Err(_) => {
840                        if !send(&mut socket, error_frame(BAD_MESSAGE)).await {
841                            break;
842                        }
843                        continue;
844                    }
845                };
846                let session = named
847                    .clone()
848                    .or_else(|| request.session_id.filter(|id| !id.is_empty()))
849                    .unwrap_or_else(|| fallback.clone());
850                match start_run(&app, &headers, session.clone(), request.prompt) {
851                    Some(run) => {
852                        running = Some(Running {
853                            session,
854                            events: events(app.clone(), run, true),
855                            stashed: None,
856                        });
857                    }
858                    None => {
859                        if !send(&mut socket, error_frame(BUSY)).await {
860                            break;
861                        }
862                    }
863                }
864            }
865            next = next_event(&mut running), if running.is_some() => match next {
866                Some(frame) => {
867                    if !send(&mut socket, frame).await {
868                        break;
869                    }
870                }
871                None => running = None,
872            },
873        }
874    }
875}
876
877/// The run in flight on a connection.
878struct Running {
879    session: String,
880    events: mpsc::UnboundedReceiver<serde_json::Value>,
881    /// An event read while text was gathered, sent on the next call.
882    stashed: Option<serde_json::Value>,
883}
884
885const BINARY: &str = "binary messages are not supported; send a text message holding a JSON object";
886const BAD_MESSAGE: &str = "the message must be a JSON object with a \"prompt\" string";
887
888/// Send one JSON frame. False when the client has gone.
889async fn send(socket: &mut WebSocket, frame: serde_json::Value) -> bool {
890    socket
891        .send(WsMessage::Text(frame.to_string().into()))
892        .await
893        .is_ok()
894}
895
896/// Text deltas that arrive within this window go out in one frame, so a model
897/// that streams a token at a time sends at most 100 text frames a second. The
898/// WebSocket frame rate limit is 250 frames a second per connection.
899const TEXT_WINDOW: Duration = Duration::from_millis(10);
900
901/// Text gathered into one frame stops at this many bytes, well under the
902/// 64 KB frame limit.
903const TEXT_FRAME_BYTES: usize = 16 * 1024;
904
905/// The WebSocket frame size limit AgentCore Runtime enforces.
906const MAX_FRAME_BYTES: usize = 64 * 1024;
907
908/// The next frame of the run in flight, or `None` when that run has ended.
909/// Waits forever when no run is in flight; the caller's condition rules that out.
910async fn next_event(running: &mut Option<Running>) -> Option<serde_json::Value> {
911    let Some(running) = running else {
912        return std::future::pending().await;
913    };
914    let event = match running.stashed.take() {
915        Some(event) => event,
916        None => running.events.recv().await?,
917    };
918    let Some(mut text) = text_of(&event).map(str::to_owned) else {
919        return Some(frame(&event, &running.session));
920    };
921    let window = tokio::time::sleep(TEXT_WINDOW);
922    tokio::pin!(window);
923    while text.len() < TEXT_FRAME_BYTES {
924        tokio::select! {
925            () = &mut window => break,
926            next = running.events.recv() => match next {
927                None => break,
928                Some(next) => match text_of(&next) {
929                    Some(more) => text.push_str(more),
930                    None => {
931                        running.stashed = Some(next);
932                        break;
933                    }
934                },
935            },
936        }
937    }
938    Some(frame(&json!({"text": text}), &running.session))
939}
940
941fn text_of(event: &serde_json::Value) -> Option<&str> {
942    event.get("text").and_then(serde_json::Value::as_str)
943}
944
945/// An event from [`events`] as a frame: the same object, with the session and
946/// the kind of message it is. A frame over the 64 KB limit becomes an error
947/// frame, since the connection would otherwise be closed.
948fn frame(event: &serde_json::Value, session: &str) -> serde_json::Value {
949    let kind = if event.get("error").is_some() {
950        "error"
951    } else if event.get("response").is_some() {
952        "agent_response"
953    } else {
954        "agent_text"
955    };
956    let mut frame = event.clone();
957    if let Some(object) = frame.as_object_mut() {
958        object.insert("session_id".to_owned(), json!(session));
959        object.insert("message_type".to_owned(), json!(kind));
960    }
961    if frame.to_string().len() > MAX_FRAME_BYTES {
962        return error_frame(
963            "the reply is larger than the 64 KB WebSocket frame limit; its text was streamed in agent_text frames, or use /invocations",
964        );
965    }
966    frame
967}
968
969fn error_frame(message: &str) -> serde_json::Value {
970    json!({"error": message, "status": "error", "message_type": "error"})
971}
972
973/// What a log line says about a failure. A provider's error text can echo the
974/// prompt, so it is logged only with `record_content`; otherwise its kind is.
975pub(crate) fn logged(
976    record_content: bool,
977    kind: &'static str,
978    failure: &dyn std::fmt::Display,
979) -> String {
980    if record_content {
981        failure.to_string()
982    } else {
983        kind.to_owned()
984    }
985}
986
987/// Record the agent's answer on the invocation span, the current one.
988fn record_answer(record_content: bool, answer: &str) {
989    if record_content {
990        let span = tracing::Span::current();
991        span.record("gen_ai.task.output", answer);
992        span.record("agentcore.invocation.agent_response", answer);
993    }
994}
995
996fn error(status: StatusCode, message: &str) -> Response {
997    (status, Json(json!({"error": message, "status": "error"}))).into_response()
998}
999
1000/// The port `PORT` names, or [`DEFAULT_PORT`] when it is not set. A value
1001/// that is not a port number warns and also gets [`DEFAULT_PORT`].
1002fn port_from_env(value: Result<String, std::env::VarError>) -> u16 {
1003    let value = match value {
1004        Ok(value) => value,
1005        Err(std::env::VarError::NotPresent) => return DEFAULT_PORT,
1006        Err(std::env::VarError::NotUnicode(value)) => value.to_string_lossy().into_owned(),
1007    };
1008    value.parse().unwrap_or_else(|_| {
1009        tracing::warn!(
1010            port = %value,
1011            "PORT is not a port number from 0 to 65535; serving on {DEFAULT_PORT} instead"
1012        );
1013        DEFAULT_PORT
1014    })
1015}
1016
1017/// Listen on every interface at `port`.
1018async fn listen(port: u16) -> Result<tokio::net::TcpListener, ServeError> {
1019    let address = SocketAddr::from(([0, 0, 0, 0], port));
1020    tokio::net::TcpListener::bind(address)
1021        .await
1022        .map_err(|source| ServeError::Bind { address, source })
1023}
1024
1025#[cfg(test)]
1026mod tests {
1027    use std::env::VarError;
1028
1029    use super::*;
1030
1031    #[test]
1032    fn the_port_comes_from_env_or_the_default() {
1033        assert_eq!(port_from_env(Ok("3200".into())), 3200);
1034        assert_eq!(port_from_env(Err(VarError::NotPresent)), DEFAULT_PORT);
1035    }
1036
1037    #[test]
1038    fn a_bad_port_falls_back_to_the_default() {
1039        for bad in ["", "abc", "70000", "-1", " 8080"] {
1040            assert_eq!(port_from_env(Ok(bad.into())), DEFAULT_PORT, "{bad:?}");
1041        }
1042    }
1043
1044    #[tokio::test]
1045    async fn a_busy_port_is_an_error_that_names_the_address() {
1046        let held = listen(0).await.unwrap();
1047        let port = held.local_addr().unwrap().port();
1048        let message = listen(port)
1049            .await
1050            .err()
1051            .map(|e| e.to_string())
1052            .unwrap_or_default();
1053        assert!(
1054            message.starts_with(&format!("could not listen on 0.0.0.0:{port}: ")),
1055            "{message}"
1056        );
1057    }
1058}
1059
1060#[cfg(doctest)]
1061#[doc = include_str!("../README.md")]
1062mod readme_doctests {}