Skip to main content

bamboo_engine/runtime/runner/
loop_execution.rs

1use std::sync::Arc;
2
3use tokio::sync::mpsc;
4use tokio_util::sync::CancellationToken;
5use tracing::Instrument;
6
7use crate::runtime::config::AgentLoopConfig;
8use bamboo_agent_core::tools::ToolExecutor;
9use bamboo_agent_core::{AgentEvent, Session};
10use bamboo_infrastructure::LLMProvider;
11
12mod pipeline;
13mod startup;
14
15use pipeline::run_pipeline;
16use startup::{initialize_loop_state, LoopRunState};
17
18/// Runs the agent loop with a custom configuration.
19///
20/// This is the primary entry point for executing an agent conversation loop.
21/// It manages LLM streaming, tool execution, task list tracking, metrics collection,
22/// and event emission throughout the conversation lifecycle.
23///
24/// # Arguments
25///
26/// * `session` - The conversation session to operate on
27/// * `initial_message` - The user's initial message to process
28/// * `event_tx` - Channel sender for agent events
29/// * `llm` - The LLM provider to use for generation
30/// * `tools` - The tool executor for handling tool calls
31/// * `cancel_token` - Token for cancelling the operation
32/// * `config` - Configuration controlling loop behavior
33///
34/// # Returns
35///
36/// Returns `Ok(())` on successful completion, or an error if the loop fails.
37pub async fn run_agent_loop_with_config(
38    session: &mut Session,
39    initial_message: String,
40    event_tx: mpsc::Sender<AgentEvent>,
41    llm: Arc<dyn LLMProvider>,
42    tools: Arc<dyn ToolExecutor>,
43    cancel_token: CancellationToken,
44    config: AgentLoopConfig,
45) -> super::Result<()> {
46    let session_span = tracing::info_span!("agent_loop", session_id = %session.id);
47    async {
48        let mut state: LoopRunState =
49            initialize_loop_state(session, initial_message.as_str(), &config, tools.as_ref()).await;
50
51        let sent_complete = run_pipeline(
52            session,
53            &event_tx,
54            llm,
55            tools,
56            &cancel_token,
57            &config,
58            &mut state,
59        )
60        .await?;
61
62        super::session_finalize::finalize_session(
63            state.task_context,
64            session,
65            &event_tx,
66            &state.session_id,
67            &config,
68            state.metrics_collector.as_ref(),
69            sent_complete,
70            &mut state.runtime_state,
71        )
72        .await;
73
74        Ok(())
75    }
76    .instrument(session_span)
77    .await
78}