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