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    pub app_data_dir: Option<std::path::PathBuf>,
58
59    // Post-execution resources.
60    pub runners: Arc<RwLock<HashMap<String, AgentRunner>>>,
61    pub sessions_cache: Arc<RwLock<HashMap<String, Session>>>,
62}
63
64/// Spawn a background agent execution task.
65///
66/// This function spawns a tokio task that:
67/// 1. Executes the agent loop via `agent.execute()`
68/// 2. Sends a terminal error event if the execution fails
69/// 3. Finalizes the runner status
70/// 4. Persists the session via merge-save (preserves concurrent UI title/pin edits)
71/// 5. Updates the in-memory session cache
72pub fn spawn_session_execution(args: SessionExecutionArgs) {
73    let span_session_id = args.session_id.clone();
74    let session_span = tracing::info_span!("agent_execution", session_id = %span_session_id);
75
76    tokio::spawn(
77        async move {
78            let SessionExecutionArgs {
79                agent,
80                session_id,
81                mut session,
82                tools_override,
83                provider_override,
84                provider_name,
85                model,
86                fast_model,
87                background_model_provider,
88                reasoning_effort,
89                reasoning_effort_source,
90                disabled_tools,
91                disabled_skill_ids,
92                selected_skill_ids,
93                selected_skill_mode,
94                cancel_token,
95                mpsc_tx,
96                image_fallback,
97                app_data_dir,
98                runners,
99                sessions_cache,
100            } = args;
101
102            let initial_message = initial_user_message_for_session(&session);
103            let selected_skill_ids =
104                selected_skill_ids.or_else(|| selected_skill_ids_for_session(&session));
105            let selected_skill_mode =
106                selected_skill_mode.or_else(|| selected_skill_mode_for_session(&session));
107
108            tracing::info!(
109                "[{}] Using resolved session model: {}, reasoning_effort={}, reasoning_source={}",
110                session_id,
111                model,
112                reasoning_effort
113                    .map(ReasoningEffort::as_str)
114                    .unwrap_or("none"),
115                reasoning_effort_source
116            );
117
118            session.model = model.clone();
119
120            let system_prompt = system_prompt_for_session(&session);
121            if let Some(prompt) = system_prompt.as_ref() {
122                log_base_system_prompt_snapshot(&session_id, prompt);
123            }
124
125            let result = agent
126                .execute(
127                    &mut session,
128                    ExecuteRequest {
129                        initial_message,
130                        event_tx: mpsc_tx.clone(),
131                        cancel_token,
132                        tools: tools_override,
133                        provider_override,
134                        model: Some(model),
135                        provider_name,
136                        background_model: fast_model,
137                        background_model_provider,
138                        reasoning_effort,
139                        disabled_tools,
140                        disabled_skill_ids,
141                        selected_skill_ids,
142                        selected_skill_mode,
143                        image_fallback,
144                        app_data_dir,
145                    },
146                )
147                .await;
148
149            // Send terminal event for all error cases (including cancellation).
150            if let Some(error_event) = terminal_error_event_for_result(&result) {
151                let _ = mpsc_tx.send(error_event).await;
152            }
153
154            // Update runner status.
155            finalize_runner(&runners, &session_id, &result).await;
156
157            // Save session via merge-save so any concurrent UI edits to
158            // title / pinned / title_version are preserved (the runtime is not
159            // an authoritative title writer).
160            if let Err(error) = agent.persistence().save_runtime_session(&mut session).await {
161                tracing::warn!("[{}] Failed to save session: {}", session_id, error);
162            }
163
164            // Update memory cache.
165            {
166                let mut sessions = sessions_cache.write().await;
167                sessions.insert(session_id.clone(), session);
168            }
169
170            tracing::info!("[{}] Agent execution completed", session_id);
171        }
172        .instrument(session_span),
173    );
174}
175
176/// Log a snapshot of the base system prompt for debugging.
177pub fn log_base_system_prompt_snapshot(session_id: &str, prompt: &str) {
178    tracing::info!(
179        "[{}] Base system prompt snapshot: len={} chars, has_skill={}, has_tool_guide={}, has_external_memory={}, has_task_list={}",
180        session_id,
181        prompt.len(),
182        prompt.contains(SKILL_CONTEXT_START_MARKER),
183        prompt.contains(TOOL_GUIDE_START_MARKER),
184        prompt.contains(EXTERNAL_MEMORY_START_MARKER),
185        prompt.contains(TASK_LIST_START_MARKER),
186    );
187
188    tracing::debug!(
189        "[{}] ========== BASE SYSTEM PROMPT SNAPSHOT ==========",
190        session_id
191    );
192    tracing::debug!("[{}] Snapshot length: {} chars", session_id, prompt.len());
193    tracing::debug!("[{}] -----------------------------------", session_id);
194    tracing::debug!("[{}] {}", session_id, prompt);
195    tracing::debug!(
196        "[{}] ========== END BASE SYSTEM PROMPT SNAPSHOT ==========",
197        session_id
198    );
199}
200
201/// Map an execution result to a terminal error event.
202pub fn terminal_error_event_for_result<E>(result: &Result<(), E>) -> Option<AgentEvent>
203where
204    E: std::fmt::Display,
205{
206    match result {
207        Ok(_) => None,
208        Err(error) if is_cancelled_error(error) => Some(AgentEvent::Error {
209            message: "Agent execution cancelled by user".to_string(),
210        }),
211        Err(error) => Some(AgentEvent::Error {
212            message: error.to_string(),
213        }),
214    }
215}
216
217fn is_cancelled_error<E>(error: &E) -> bool
218where
219    E: std::fmt::Display,
220{
221    error.to_string().contains("cancelled")
222}
223
224// Session metadata helpers (pure functions, no server dependency).
225
226fn system_prompt_for_session(session: &Session) -> Option<String> {
227    session
228        .messages
229        .iter()
230        .find(|message| matches!(message.role, bamboo_agent_core::Role::System))
231        .map(|message| message.content.clone())
232}
233
234fn initial_user_message_for_session(session: &Session) -> String {
235    session
236        .messages
237        .last()
238        .filter(|message| matches!(message.role, bamboo_agent_core::Role::User))
239        .map(|message| message.content.clone())
240        .unwrap_or_default()
241}
242
243fn selected_skill_ids_for_session(session: &Session) -> Option<Vec<String>> {
244    session
245        .metadata
246        .get("selected_skill_ids")
247        .and_then(|raw| crate::skills::selection::parse_selected_skill_ids_metadata(raw))
248}
249
250fn selected_skill_mode_for_session(session: &Session) -> Option<String> {
251    let value = session
252        .metadata
253        .get("skill_mode")
254        .or_else(|| session.metadata.get("mode"))?;
255    let trimmed = value.trim();
256    if trimmed.is_empty() {
257        None
258    } else {
259        Some(trimmed.to_string())
260    }
261}