use crate::commands::config::SpriteConfig;
use crate::error::SpriteError;
use crate::utils::git;
use crate::utils::project;
use crate::utils::tmux;
use anyhow::{Context, Result};
pub fn execute(
session_name: Option<String>,
layout: String,
detach: bool,
force: bool,
) -> Result<()> {
project::execute_from_project_root(|| {
execute_from_project_root(session_name, layout, detach, force)
})
}
fn execute_from_project_root(
session_name: Option<String>,
layout: String,
detach: bool,
force: bool,
) -> Result<()> {
let session_name = session_name.unwrap_or_else(|| "sprite-session".to_string());
let config = SpriteConfig::load().context("Failed to load configuration")?;
if config.agents.is_empty() {
return Err(SpriteError::config(
"No agents configured. Use 'sprite init' to create agents first.",
)
.into());
}
println!("đ Starting Sprite multi-agent session...");
println!("đ Configuration loaded: {} agents", config.agents.len());
println!("đŽ Session name: {}", session_name);
println!("đŧī¸ Layout: {}", layout);
git::validate_git_repository().context("Git repository validation failed")?;
if tmux::session_exists(&session_name)? {
if force {
println!(
"đ Force mode: Killing existing session '{}'...",
session_name
);
tmux::kill_session_force(&session_name)?;
println!(" â
Old session killed");
} else if !detach {
return Err(SpriteError::session(
format!("Session '{}' already exists. Use 'sprite start --force' to replace it, 'sprite attach' to join, or 'sprite kill' to terminate.", session_name),
Some(session_name),
)
.into());
} else {
println!(
"âšī¸ Session '{}' already exists, detaching...",
session_name
);
return Ok(());
}
}
println!("đ Checking agent workspaces...");
if let Err(e) = config.validate_workspaces() {
println!("â ī¸ Workspace validation failed: {}", e);
println!("đ§ Attempting to provision missing workspaces...");
config
.provision_worktrees()
.context("Failed to provision workspaces")?;
config
.validate_workspaces()
.context("Workspace validation failed after provisioning")?;
}
let profile = determine_tmux_profile(&config.agents.len(), &layout)?;
println!("đ Using tmux profile: {}", profile);
create_tmux_session(&session_name, &config, &profile, detach)?;
std::thread::sleep(std::time::Duration::from_millis(300));
update_agent_status_to_active(&config)?;
if !detach {
println!("â
Session created successfully!");
println!("đĄ Use 'sprite attach' to rejoin the session");
println!("đĄ Use 'sprite kill' to terminate the session");
} else {
println!("â
Session created and detached!");
println!(
"đĄ Use 'sprite attach {}' to join the session",
session_name
);
}
Ok(())
}
fn determine_tmux_profile(agent_count: &usize, layout: &str) -> Result<String> {
let profile = match layout {
"tiled" => match agent_count {
1 => "profile3", 2..=3 => "profile0", 4..=6 => "profile2", _ => "profile5", },
"focus" => "profile3", "vertical" => "profile1", "horizontal" => "profile0", "dashboard" => "profile5", custom => {
if custom.starts_with("profile") && custom.len() == 8 {
custom
} else {
return Err(SpriteError::config(format!(
"Unknown layout or profile: '{}'. Available: tiled, focus, vertical, horizontal, dashboard, profile0-profile5",
custom
))
.into());
}
}
};
println!("đ {} agents detected â profile: {}", agent_count, profile);
Ok(profile.to_string())
}
fn create_tmux_session(
session_name: &str,
config: &SpriteConfig,
profile: &str,
#[allow(dead_code)] _detach: bool,
) -> Result<()> {
println!("đ§ Creating tmux session '{}'...", session_name);
let agents_dir = std::path::PathBuf::from("agents");
let profile_script = agents_dir.join("profiles").join(format!("{}.sh", profile));
tmux::execute_profile_script_with_agent_count(
session_name,
&profile_script,
config.agents.len() as u32,
)
.with_context(|| {
format!(
"Failed to execute profile script: {}",
profile_script.display()
)
})?;
setup_agent_panes(session_name, config)?;
send_supervisor_info(session_name, config)?;
println!("â
Tmux session '{}' created successfully", session_name);
Ok(())
}
fn setup_agent_panes(session_name: &str, config: &SpriteConfig) -> Result<()> {
println!("đ¤ Setting up agent panes...");
let panes = tmux::get_session_panes(session_name)
.context("Failed to get session panes for agent setup")?;
for (index, agent_config) in config.agents.iter().enumerate() {
let workspace_path = &agent_config.worktree_path;
let pane_target = if index < panes.len() {
panes[index].index.to_string()
} else {
"".to_string()
};
let cmd = format!("cd {}", workspace_path);
if let Err(e) = tmux::send_keys_with_delay(session_name, &pane_target, &cmd, 50) {
eprintln!(
"â ī¸ Warning: Failed to setup agent {} workspace: {}",
agent_config.id, e
);
}
let info_cmd = format!(
"echo 'đ¤ Agent {} - {}'",
agent_config.id, agent_config.description
);
if let Err(e) = tmux::send_keys_with_delay(session_name, &pane_target, &info_cmd, 50) {
eprintln!(
"â ī¸ Warning: Failed to display agent {} info: {}",
agent_config.id, e
);
}
let git_cmd = "git status --porcelain";
if let Err(e) = tmux::send_keys_with_delay(session_name, &pane_target, git_cmd, 50) {
eprintln!(
"â ī¸ Warning: Failed to show git status for agent {}: {}",
agent_config.id, e
);
}
}
Ok(())
}
fn send_supervisor_info(session_name: &str, config: &SpriteConfig) -> Result<()> {
println!("đŽ Configuring supervisor control pane...");
let supervisor_info = format!(
"đŽ Sprite Supervisor Control Panel\n\
đ Active Agents: {}\n\
đ Session: {}\n\
âī¸ Profile: {}\n\
\n\
Available Commands:\n\
âĸ sprite hey <agent> <command> - Send command to specific agent\n\
âĸ sprite send <command> - Broadcast to all agents\n\
âĸ sprite list - List all agents and their status\n\
âĸ sprite sync - Synchronize all workspaces\n\
âĸ sprite warp <agent> - Navigate to agent workspace\n\
âĸ sprite zoom <agent> - Focus on agent pane\n\
âĸ sprite kill - Terminate session\n\
âĸ sprite attach - Reattach to session",
config.agents.len(),
session_name,
"tiled"
);
if let Err(e) = tmux::send_keys_with_delay(session_name, "supervisor", &supervisor_info, 100) {
eprintln!(
"â ī¸ Warning: Failed to display supervisor information: {}",
e
);
}
let help_cmd = "echo 'Type \"sprite --help\" for command reference'";
if let Err(e) = tmux::send_keys_with_delay(session_name, "supervisor", help_cmd, 50) {
eprintln!("â ī¸ Warning: Failed to show help command: {}", e);
}
Ok(())
}
fn update_agent_status_to_active(_config: &crate::commands::config::SpriteConfig) -> Result<()> {
println!("đ Activating agents...");
let mut current_config = crate::commands::config::SpriteConfig::load()
.context("Failed to load configuration for status update")?;
let mut updated_count = 0;
for agent in &mut current_config.agents {
if agent.status.to_lowercase() == "inactive" {
agent.status = "Active".to_string();
updated_count += 1;
println!(" â
Agent {} is now Active", agent.id);
} else {
println!(
" âšī¸ Agent {} already has status: {}",
agent.id, agent.status
);
}
}
if updated_count > 0 {
current_config
.save()
.context("Failed to save updated configuration")?;
println!(
"đ Configuration updated: {} agents activated",
updated_count
);
} else {
println!("âšī¸ No agents needed activation");
}
Ok(())
}