Skip to main content

bamboo_engine/runtime/
runner.rs

1//! Agent loop runner implementation.
2//!
3//! This module provides the core agent execution loop that orchestrates LLM interactions,
4//! tool execution, and event streaming for conversational AI agents.
5
6use bamboo_agent_core::TokenUsage;
7use bamboo_agent_core::{AgentError, Session};
8
9pub(crate) mod auxiliary_budget;
10pub mod image_fallback;
11mod logging;
12mod loop_execution;
13mod metrics_lifecycle;
14pub(crate) mod prompt_context;
15pub(crate) mod round_frame;
16pub(crate) mod round_lifecycle;
17pub(crate) mod round_prelude;
18pub(crate) mod session_finalize;
19pub(crate) mod session_setup;
20pub(crate) mod state_bridge;
21mod task_lifecycle;
22pub(crate) mod tool_execution;
23mod workspace_context;
24
25pub use bamboo_agent_core::PromptSnapshot;
26pub(crate) use loop_execution::run_agent_loop_with_config;
27pub use state_bridge::{refresh_turn_boundary_with_inbox, TurnBoundaryRefresh};
28
29pub fn read_prompt_snapshot(session: &Session) -> Option<PromptSnapshot> {
30    session_setup::read_prompt_snapshot(session)
31}
32
33pub fn refresh_prompt_snapshot(session: &mut Session) {
34    session_setup::refresh_prompt_snapshot(session)
35}
36
37pub(super) fn to_event_token_usage(prompt_tokens: u64, completion_tokens: u64) -> TokenUsage {
38    let mut usage = TokenUsage {
39        prompt_tokens,
40        completion_tokens,
41        total_tokens: 0,
42    };
43    usage.recompute_total();
44    usage
45}
46
47/// Result type for agent loop operations.
48pub type Result<T> = std::result::Result<T, AgentError>;
49
50#[cfg(test)]
51mod tests;
52
53/// Stable, content-free outcome categories shared by loop and provider spans.
54fn telemetry_outcome<T>(
55    result: &std::result::Result<T, AgentError>,
56) -> bamboo_infrastructure::telemetry::Outcome {
57    match result {
58        Ok(_) => bamboo_infrastructure::telemetry::Outcome::Success,
59        Err(error) => telemetry_error_outcome(error),
60    }
61}
62
63fn telemetry_error_outcome(error: &AgentError) -> bamboo_infrastructure::telemetry::Outcome {
64    use bamboo_infrastructure::telemetry::Outcome;
65    match error {
66        AgentError::Cancelled => Outcome::Cancelled,
67        AgentError::StreamTimeout(_) => Outcome::Timeout,
68        AgentError::LLMOverflow(_) => Outcome::ContextOverflow,
69        AgentError::EmptyAssistantResponse { .. } => Outcome::EmptyResponse,
70        AgentError::LLM(_) => Outcome::ProviderError,
71        _ => Outcome::ExecutionError,
72    }
73}