use async_trait::async_trait;
use bamboo_agent_core::AgentEvent;
use bamboo_domain::Session;
use tokio::sync::broadcast;
use super::execute::{consume_pending_clarification_resume, has_pending_user_message};
use super::types::{ResumeConfigSnapshot, ResumeOutcome};
use crate::execution::{SessionExecutionReservation, SessionExecutionReserveOutcome};
#[async_trait]
pub trait ResumeExecutionPort: Send + Sync {
async fn load_session(&self, session_id: &str) -> Option<Session>;
async fn save_and_cache_session(&self, session: &mut Session);
async fn reserve_session_execution(
&self,
session_id: &str,
event_sender: &broadcast::Sender<AgentEvent>,
) -> SessionExecutionReserveOutcome;
async fn get_or_create_event_sender(&self, session_id: &str) -> broadcast::Sender<AgentEvent>;
async fn spawn_resume_execution(&self, request: ResumeSpawnRequest);
}
pub struct ResumeSpawnRequest {
pub session_id: String,
pub session: Session,
pub execution_reservation: SessionExecutionReservation,
pub event_sender: broadcast::Sender<AgentEvent>,
pub config: ResumeConfigSnapshot,
}
pub async fn resume_session_execution(
port: &dyn ResumeExecutionPort,
session_id: &str,
config: ResumeConfigSnapshot,
) -> ResumeOutcome {
let Some(mut session) = port.load_session(session_id).await else {
return ResumeOutcome::NotFound;
};
if !has_pending_user_message(&session) {
return ResumeOutcome::Completed;
}
let event_sender = port.get_or_create_event_sender(session_id).await;
let reservation = match port
.reserve_session_execution(session_id, &event_sender)
.await
{
SessionExecutionReserveOutcome::Reserved(reservation) => reservation,
SessionExecutionReserveOutcome::AlreadyRunning { run_id } => {
return ResumeOutcome::AlreadyRunning { run_id };
}
};
let run_id = reservation.run_id().to_string();
consume_pending_clarification_resume(&mut session);
port.save_and_cache_session(&mut session).await;
port.spawn_resume_execution(ResumeSpawnRequest {
session_id: session_id.to_string(),
session,
execution_reservation: reservation,
event_sender,
config,
})
.await;
ResumeOutcome::Started { run_id }
}