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