Skip to main content

bamboo_engine/runtime/execution/
agent_spawn.rs

1//! Core agent execution spawning logic.
2//!
3//! Provides [`spawn_session_execution`] which handles the full lifecycle of a
4//! background agent run: spawn task → execute → finalize runner → persist session.
5
6use std::collections::{BTreeSet, HashMap};
7use std::sync::Arc;
8
9use tokio::sync::{mpsc, RwLock};
10use tokio_util::sync::CancellationToken;
11use tracing::Instrument;
12
13use bamboo_agent_core::tools::ToolExecutor;
14use bamboo_agent_core::{AgentEvent, Session};
15use bamboo_domain::ReasoningEffort;
16use bamboo_infrastructure::LLMProvider;
17
18use crate::runtime::config::ImageFallbackConfig;
19use crate::runtime::execution::runner_lifecycle::finalize_runner;
20use crate::runtime::execution::runner_state::AgentRunner;
21use crate::runtime::Agent;
22use crate::runtime::ExecuteRequest;
23
24const SKILL_CONTEXT_START_MARKER: &str = "<!-- BAMBOO_SKILL_CONTEXT_START -->";
25const TOOL_GUIDE_START_MARKER: &str = "<!-- BAMBOO_TOOL_GUIDE_START -->";
26const EXTERNAL_MEMORY_START_MARKER: &str = "<!-- BAMBOO_EXTERNAL_MEMORY_START -->";
27const TASK_LIST_START_MARKER: &str = "<!-- BAMBOO_TASK_LIST_START -->";
28
29/// Arguments for spawning a background agent execution.
30///
31/// This is the crate-agnostic equivalent of the server's `SpawnAgentExecution`.
32/// It holds everything needed to run the agent loop and persist the result,
33/// without depending on HTTP types or `AppState`.
34pub struct SessionExecutionArgs {
35    // Core execution.
36    pub agent: Arc<Agent>,
37    pub session_id: String,
38    pub session: Session,
39
40    // Execution parameters.
41    pub tools_override: Option<Arc<dyn ToolExecutor>>,
42    pub provider_override: Option<Arc<dyn LLMProvider>>,
43    pub provider_name: Option<String>,
44    pub model: String,
45    pub fast_model: Option<String>,
46    /// Optional provider override for background/fast model calls.
47    pub background_model_provider: Option<Arc<dyn LLMProvider>>,
48    pub reasoning_effort: Option<ReasoningEffort>,
49    pub reasoning_effort_source: String,
50    pub disabled_tools: Option<BTreeSet<String>>,
51    pub disabled_skill_ids: Option<BTreeSet<String>>,
52    pub selected_skill_ids: Option<Vec<String>>,
53    pub selected_skill_mode: Option<String>,
54    pub cancel_token: CancellationToken,
55    pub mpsc_tx: mpsc::Sender<AgentEvent>,
56    pub image_fallback: Option<ImageFallbackConfig>,
57
58    // Post-execution resources.
59    pub runners: Arc<RwLock<HashMap<String, AgentRunner>>>,
60    pub sessions_cache: Arc<RwLock<HashMap<String, Session>>>,
61}
62
63/// Spawn a background agent execution task.
64///
65/// This function spawns a tokio task that:
66/// 1. Executes the agent loop via `agent.execute()`
67/// 2. Sends a terminal error event if the execution fails
68/// 3. Finalizes the runner status
69/// 4. Persists the session via merge-save (preserves concurrent UI title/pin edits)
70/// 5. Updates the in-memory session cache
71pub fn spawn_session_execution(args: SessionExecutionArgs) {
72    let span_session_id = args.session_id.clone();
73    let session_span = tracing::info_span!("agent_execution", session_id = %span_session_id);
74
75    tokio::spawn(
76        async move {
77            let SessionExecutionArgs {
78                agent,
79                session_id,
80                mut session,
81                tools_override,
82                provider_override,
83                provider_name,
84                model,
85                fast_model,
86                background_model_provider,
87                reasoning_effort,
88                reasoning_effort_source,
89                disabled_tools,
90                disabled_skill_ids,
91                selected_skill_ids,
92                selected_skill_mode,
93                cancel_token,
94                mpsc_tx,
95                image_fallback,
96                runners,
97                sessions_cache,
98            } = args;
99
100            let initial_message = initial_user_message_for_session(&session);
101            let selected_skill_ids =
102                selected_skill_ids.or_else(|| selected_skill_ids_for_session(&session));
103            let selected_skill_mode =
104                selected_skill_mode.or_else(|| selected_skill_mode_for_session(&session));
105
106            tracing::info!(
107                "[{}] Using resolved session model: {}, reasoning_effort={}, reasoning_source={}",
108                session_id,
109                model,
110                reasoning_effort
111                    .map(ReasoningEffort::as_str)
112                    .unwrap_or("none"),
113                reasoning_effort_source
114            );
115
116            session.model = model.clone();
117
118            let system_prompt = system_prompt_for_session(&session);
119            if let Some(prompt) = system_prompt.as_ref() {
120                log_base_system_prompt_snapshot(&session_id, prompt);
121            }
122
123            let result = agent
124                .execute(
125                    &mut session,
126                    ExecuteRequest {
127                        initial_message,
128                        event_tx: mpsc_tx.clone(),
129                        cancel_token,
130                        tools: tools_override,
131                        provider_override,
132                        model: Some(model),
133                        provider_name,
134                        background_model: fast_model,
135                        background_model_provider,
136                        reasoning_effort,
137                        disabled_tools,
138                        disabled_skill_ids,
139                        selected_skill_ids,
140                        selected_skill_mode,
141                        image_fallback,
142                    },
143                )
144                .await;
145
146            // Send terminal event for all error cases (including cancellation).
147            if let Some(error_event) = terminal_error_event_for_result(&result) {
148                let _ = mpsc_tx.send(error_event).await;
149            }
150
151            // Update runner status.
152            finalize_runner(&runners, &session_id, &result).await;
153
154            // Save session via merge-save so any concurrent UI edits to
155            // title / pinned / title_version are preserved (the runtime is not
156            // an authoritative title writer).
157            if let Err(error) =
158                agent.persistence().save_runtime_session(&mut session).await
159            {
160                tracing::warn!("[{}] Failed to save session: {}", session_id, error);
161            }
162
163            // Update memory cache.
164            {
165                let mut sessions = sessions_cache.write().await;
166                sessions.insert(session_id.clone(), session);
167            }
168
169            tracing::info!("[{}] Agent execution completed", session_id);
170        }
171        .instrument(session_span),
172    );
173}
174
175/// Log a snapshot of the base system prompt for debugging.
176pub fn log_base_system_prompt_snapshot(session_id: &str, prompt: &str) {
177    tracing::info!(
178        "[{}] Base system prompt snapshot: len={} chars, has_skill={}, has_tool_guide={}, has_external_memory={}, has_task_list={}",
179        session_id,
180        prompt.len(),
181        prompt.contains(SKILL_CONTEXT_START_MARKER),
182        prompt.contains(TOOL_GUIDE_START_MARKER),
183        prompt.contains(EXTERNAL_MEMORY_START_MARKER),
184        prompt.contains(TASK_LIST_START_MARKER),
185    );
186
187    tracing::debug!(
188        "[{}] ========== BASE SYSTEM PROMPT SNAPSHOT ==========",
189        session_id
190    );
191    tracing::debug!("[{}] Snapshot length: {} chars", session_id, prompt.len());
192    tracing::debug!("[{}] -----------------------------------", session_id);
193    tracing::debug!("[{}] {}", session_id, prompt);
194    tracing::debug!(
195        "[{}] ========== END BASE SYSTEM PROMPT SNAPSHOT ==========",
196        session_id
197    );
198}
199
200/// Map an execution result to a terminal error event.
201pub fn terminal_error_event_for_result<E>(result: &Result<(), E>) -> Option<AgentEvent>
202where
203    E: std::fmt::Display,
204{
205    match result {
206        Ok(_) => None,
207        Err(error) if is_cancelled_error(error) => Some(AgentEvent::Error {
208            message: "Agent execution cancelled by user".to_string(),
209        }),
210        Err(error) => Some(AgentEvent::Error {
211            message: error.to_string(),
212        }),
213    }
214}
215
216fn is_cancelled_error<E>(error: &E) -> bool
217where
218    E: std::fmt::Display,
219{
220    error.to_string().contains("cancelled")
221}
222
223// Session metadata helpers (pure functions, no server dependency).
224
225fn system_prompt_for_session(session: &Session) -> Option<String> {
226    session
227        .messages
228        .iter()
229        .find(|message| matches!(message.role, bamboo_agent_core::Role::System))
230        .map(|message| message.content.clone())
231}
232
233fn initial_user_message_for_session(session: &Session) -> String {
234    session
235        .messages
236        .last()
237        .filter(|message| matches!(message.role, bamboo_agent_core::Role::User))
238        .map(|message| message.content.clone())
239        .unwrap_or_default()
240}
241
242fn selected_skill_ids_for_session(session: &Session) -> Option<Vec<String>> {
243    session
244        .metadata
245        .get("selected_skill_ids")
246        .and_then(|raw| crate::skills::selection::parse_selected_skill_ids_metadata(raw))
247}
248
249fn selected_skill_mode_for_session(session: &Session) -> Option<String> {
250    let value = session
251        .metadata
252        .get("skill_mode")
253        .or_else(|| session.metadata.get("mode"))?;
254    let trimmed = value.trim();
255    if trimmed.is_empty() {
256        None
257    } else {
258        Some(trimmed.to_string())
259    }
260}