|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::io::Write; |
| 3 | +use std::path::PathBuf; |
| 4 | + |
| 5 | +use eyre::Result; |
| 6 | +use serde::{ |
| 7 | + Deserialize, |
| 8 | + Serialize, |
| 9 | +}; |
| 10 | + |
| 11 | +use crate::cli::DEFAULT_AGENT_NAME; |
| 12 | +use crate::cli::chat::tools::delegate::agent::subagents_dir; |
| 13 | +use crate::cli::chat::tools::delegate::{ |
| 14 | + AgentExecution, |
| 15 | + AgentStatus, |
| 16 | + launch_agent, |
| 17 | +}; |
| 18 | +use crate::cli::chat::{ |
| 19 | + ChatError, |
| 20 | + ChatSession, |
| 21 | + ChatState, |
| 22 | +}; |
| 23 | +use crate::database::settings::Setting; |
| 24 | +use crate::os::Os; |
| 25 | + |
| 26 | +#[derive(Debug, Default, Serialize, Deserialize, Clone)] |
| 27 | +pub struct SubagentHeader { |
| 28 | + pub launched_at: String, |
| 29 | + pub agent: Option<String>, |
| 30 | + pub prompt: String, |
| 31 | + pub status: String, // "active", "completed", "failed" |
| 32 | + pub pid: u32, |
| 33 | + pub completed_at: Option<String>, |
| 34 | +} |
| 35 | + |
| 36 | +#[derive(Debug, Default, Serialize, Deserialize, Clone)] |
| 37 | +pub struct SubagentContent { |
| 38 | + pub output: String, |
| 39 | + pub exit_code: Option<i32>, |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Debug, Default, Serialize, Deserialize, Clone)] |
| 43 | +pub struct StatusFile { |
| 44 | + pub subagents: HashMap<String, SubagentHeader>, |
| 45 | + pub last_updated: String, |
| 46 | +} |
| 47 | + |
| 48 | +#[derive(Debug, PartialEq, clap::Subcommand)] |
| 49 | +pub enum DelegateArgs { |
| 50 | + /// Show status of tasks |
| 51 | + Status { |
| 52 | + /// Specific task agent name (optional) |
| 53 | + agent_name: Option<String>, |
| 54 | + }, |
| 55 | + /// Read output from a task |
| 56 | + Read { |
| 57 | + /// Task agent name |
| 58 | + agent_name: String, |
| 59 | + }, |
| 60 | + /// Delete a task and its files |
| 61 | + Delete { |
| 62 | + /// Task agent name |
| 63 | + agent_name: String, |
| 64 | + }, |
| 65 | + /// Launch a new task |
| 66 | + Launch { |
| 67 | + /// Agent to use for the task |
| 68 | + #[arg(long)] |
| 69 | + agent: Option<String>, |
| 70 | + /// Task description |
| 71 | + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] |
| 72 | + prompt: Vec<String>, |
| 73 | + }, |
| 74 | +} |
| 75 | + |
| 76 | +impl DelegateArgs { |
| 77 | + pub async fn execute(self, os: &mut Os, session: &mut ChatSession) -> Result<ChatState, ChatError> { |
| 78 | + if !is_enabled(os) { |
| 79 | + return Err(ChatError::Custom( |
| 80 | + "Delegate feature is not enabled. Enable it with /experiment command.".into(), |
| 81 | + )); |
| 82 | + } |
| 83 | + |
| 84 | + let executions = gather_executions(os) |
| 85 | + .await |
| 86 | + .map_err(|e| ChatError::Custom(e.to_string().into()))?; |
| 87 | + |
| 88 | + let result = match self { |
| 89 | + DelegateArgs::Status { agent_name } => { |
| 90 | + show_status( |
| 91 | + agent_name.as_deref(), |
| 92 | + &executions.iter().map(|(e, _)| e).collect::<Vec<_>>(), |
| 93 | + ) |
| 94 | + .await |
| 95 | + }, |
| 96 | + DelegateArgs::Read { agent_name } => { |
| 97 | + let (execution, path) = executions |
| 98 | + .iter() |
| 99 | + .find(|(e, _)| e.agent.as_str() == agent_name) |
| 100 | + .ok_or(ChatError::Custom("No task found".into()))?; |
| 101 | + |
| 102 | + let execution_as_str = |
| 103 | + serde_json::to_string(&execution).map_err(|e| ChatError::Custom(e.to_string().into()))?; |
| 104 | + |
| 105 | + _ = os.fs.remove_file(path).await; |
| 106 | + |
| 107 | + return Ok(ChatState::HandleInput { |
| 108 | + input: format!( |
| 109 | + "Delegate task with agent {} has concluded with the following content: {}", |
| 110 | + &execution.agent, execution_as_str, |
| 111 | + ), |
| 112 | + }); |
| 113 | + }, |
| 114 | + DelegateArgs::Delete { agent_name } => { |
| 115 | + let (_, path) = executions |
| 116 | + .iter() |
| 117 | + .find(|(e, _)| e.agent.as_str() == agent_name) |
| 118 | + .ok_or(ChatError::Custom("No task found".into()))?; |
| 119 | + os.fs.remove_file(path).await?; |
| 120 | + |
| 121 | + Ok(format!("Task with agent {agent_name} has been deleted")) |
| 122 | + }, |
| 123 | + DelegateArgs::Launch { agent, prompt } => { |
| 124 | + let prompt_str = prompt.join(" "); |
| 125 | + if prompt_str.trim().is_empty() { |
| 126 | + return Err(ChatError::Custom("Please provide a prompt for the task".into())); |
| 127 | + } |
| 128 | + |
| 129 | + launch_agent( |
| 130 | + os, |
| 131 | + agent.as_deref().unwrap_or(DEFAULT_AGENT_NAME), |
| 132 | + &session.conversation.agents, |
| 133 | + &prompt_str, |
| 134 | + ) |
| 135 | + .await |
| 136 | + }, |
| 137 | + }; |
| 138 | + |
| 139 | + match result { |
| 140 | + Ok(output) => { |
| 141 | + crossterm::queue!(session.stderr, crossterm::style::Print(format!("{}\n", output)))?; |
| 142 | + }, |
| 143 | + Err(e) => { |
| 144 | + crossterm::queue!(session.stderr, crossterm::style::Print(format!("Error: {}\n", e)))?; |
| 145 | + }, |
| 146 | + } |
| 147 | + |
| 148 | + session.stderr.flush()?; |
| 149 | + |
| 150 | + Ok(ChatState::PromptUser { |
| 151 | + skip_printing_tools: false, |
| 152 | + }) |
| 153 | + } |
| 154 | +} |
| 155 | + |
| 156 | +fn is_enabled(os: &Os) -> bool { |
| 157 | + os.database.settings.get_bool(Setting::EnabledDelegate).unwrap_or(false) |
| 158 | +} |
| 159 | + |
| 160 | +async fn gather_executions(os: &Os) -> Result<Vec<(AgentExecution, PathBuf)>> { |
| 161 | + let mut dir_walker = os.fs.read_dir(subagents_dir(os).await?).await?; |
| 162 | + let mut executions = Vec::<(AgentExecution, PathBuf)>::new(); |
| 163 | + |
| 164 | + while let Ok(Some(file)) = dir_walker.next_entry().await { |
| 165 | + let bytes = os.fs.read(file.path()).await?; |
| 166 | + let execution = serde_json::from_slice::<AgentExecution>(&bytes)?; |
| 167 | + |
| 168 | + executions.push((execution, file.path())); |
| 169 | + } |
| 170 | + |
| 171 | + Ok(executions) |
| 172 | +} |
| 173 | + |
| 174 | +async fn show_status(agent_name: Option<&str>, executions: &[&AgentExecution]) -> Result<String> { |
| 175 | + if let Some(agent_name) = agent_name { |
| 176 | + let execution = executions |
| 177 | + .iter() |
| 178 | + .find(|e| e.agent.as_str() == agent_name) |
| 179 | + .ok_or(eyre::eyre!("Execution not found"))?; |
| 180 | + |
| 181 | + Ok(format!( |
| 182 | + "📦 Subagent Status: {}\n🤖 agent: {}\n📋 Task: {}\n⏰ Launched: {}", |
| 183 | + execution.status, execution.agent, execution.task, execution.launched_at |
| 184 | + )) |
| 185 | + } else { |
| 186 | + let mut active_count = 0; |
| 187 | + let mut completed_count = 0; |
| 188 | + let mut failed_count = 0; |
| 189 | + |
| 190 | + for execution in executions { |
| 191 | + match execution.status { |
| 192 | + AgentStatus::Running => active_count += 1, |
| 193 | + AgentStatus::Completed => completed_count += 1, |
| 194 | + AgentStatus::Failed => failed_count += 1, |
| 195 | + } |
| 196 | + } |
| 197 | + |
| 198 | + Ok(format!( |
| 199 | + "📊 Subagent Summary:\n🟢 Active: {}\n✅ Completed: {}\n❌ Failed: {}\n📈 Total: {}", |
| 200 | + active_count, |
| 201 | + completed_count, |
| 202 | + failed_count, |
| 203 | + executions.len() |
| 204 | + )) |
| 205 | + } |
| 206 | +} |
0 commit comments