use codive_prompts::PromptStore;
use crate::config::AgentConfig;
use crate::event::{Event, EventBus};
use crate::message::{ContentPart, Message, ToolCall, ToolResult};
use crate::provider::{CompletionRequest, Provider, ProviderError, StopReason, StreamEvent};
use crate::session::Session;
use crate::tool::{ToolInfo, ToolRegistry};
use std::sync::Arc;
use tokio_stream::StreamExt;
use tracing::{debug, info, instrument, warn};
pub use tokio_util::sync::CancellationToken;
#[derive(Debug, thiserror::Error)]
pub enum AgentRunError {
#[error("Provider error: {0}")]
Provider(#[from] ProviderError),
#[error("Tool error: {message}")]
Tool { message: String },
#[error("Maximum steps exceeded ({max_steps})")]
MaxStepsExceeded { max_steps: u32 },
#[error("Session error: {message}")]
Session { message: String },
#[error("Operation cancelled")]
Cancelled,
}
impl AgentRunError {
pub fn tool(message: impl Into<String>) -> Self {
Self::Tool {
message: message.into(),
}
}
pub fn session(message: impl Into<String>) -> Self {
Self::Session {
message: message.into(),
}
}
pub fn is_cancelled(&self) -> bool {
matches!(self, Self::Cancelled)
}
}
#[derive(Debug, Clone)]
pub struct TurnResult {
pub text: String,
pub tool_calls: Vec<ToolCall>,
pub stop_reason: StopReason,
pub steps: u32,
}
impl TurnResult {
pub fn new(text: String, tool_calls: Vec<ToolCall>, stop_reason: StopReason, steps: u32) -> Self {
Self {
text,
tool_calls,
stop_reason,
steps,
}
}
}
pub struct Agent {
provider: Arc<dyn Provider>,
tools: ToolRegistry,
config: AgentConfig,
prompt_store: Arc<PromptStore>,
session: Session,
event_bus: EventBus,
}
impl Agent {
pub fn new(
provider: Arc<dyn Provider>,
config: AgentConfig,
prompt_store: Arc<PromptStore>,
) -> Self {
let session = Session::new();
Self {
provider,
tools: ToolRegistry::new(),
config,
prompt_store,
session,
event_bus: EventBus::new(),
}
}
pub fn with_session(
provider: Arc<dyn Provider>,
config: AgentConfig,
prompt_store: Arc<PromptStore>,
session: Session,
) -> Self {
Self {
provider,
tools: ToolRegistry::new(),
config,
prompt_store,
session,
event_bus: EventBus::new(),
}
}
pub fn tools_mut(&mut self) -> &mut ToolRegistry {
&mut self.tools
}
pub fn tools(&self) -> &ToolRegistry {
&self.tools
}
pub fn session(&self) -> &Session {
&self.session
}
pub fn session_mut(&mut self) -> &mut Session {
&mut self.session
}
pub fn event_bus(&self) -> &EventBus {
&self.event_bus
}
pub fn config(&self) -> &AgentConfig {
&self.config
}
#[instrument(skip(self, user_message), fields(session_id = %self.session.id))]
pub async fn run(&mut self, user_message: impl Into<String>) -> Result<TurnResult, AgentRunError> {
self.run_with_cancellation(user_message, None).await
}
#[instrument(skip(self, user_message, cancel_token), fields(session_id = %self.session.id))]
pub async fn run_with_cancellation(
&mut self,
user_message: impl Into<String>,
cancel_token: Option<CancellationToken>,
) -> Result<TurnResult, AgentRunError> {
let user_message = user_message.into();
info!(message = %user_message, "Starting agent turn");
if let Some(ref token) = cancel_token {
if token.is_cancelled() {
return Err(AgentRunError::Cancelled);
}
}
self.session.add_message(Message::user(&user_message));
self.event_bus.publish(Event::MessageCreated {
session_id: self.session.id.clone(),
message_id: format!("msg_{}", self.session.message_count()),
role: "user".to_string(),
});
self.run_loop_internal(cancel_token).await
}
pub async fn continue_turn(&mut self) -> Result<TurnResult, AgentRunError> {
self.run_loop_internal(None).await
}
pub async fn continue_turn_with_cancellation(
&mut self,
cancel_token: Option<CancellationToken>,
) -> Result<TurnResult, AgentRunError> {
self.run_loop_internal(cancel_token).await
}
async fn run_loop_internal(
&mut self,
cancel_token: Option<CancellationToken>,
) -> Result<TurnResult, AgentRunError> {
let mut steps = 0u32;
let mut accumulated_text = String::new();
let mut all_tool_calls = Vec::new();
let mut final_stop_reason: StopReason;
loop {
steps += 1;
if let Some(ref token) = cancel_token {
if token.is_cancelled() {
info!(steps, "Agent run cancelled");
return Err(AgentRunError::Cancelled);
}
}
if steps > self.config.max_steps {
warn!(steps, max = self.config.max_steps, "Maximum steps exceeded");
return Err(AgentRunError::MaxStepsExceeded {
max_steps: self.config.max_steps,
});
}
debug!(step = steps, "Running agent step");
let request = self.build_request();
let stream_result = if let Some(ref token) = cancel_token {
tokio::select! {
_ = token.cancelled() => {
info!(steps, "Agent run cancelled during provider call");
return Err(AgentRunError::Cancelled);
}
result = self.provider.complete(request) => result
}
} else {
self.provider.complete(request).await
};
let mut stream = stream_result?;
let (text, tool_calls, stop_reason) = self.process_stream(&mut stream).await?;
accumulated_text.push_str(&text);
all_tool_calls.extend(tool_calls.clone());
final_stop_reason = stop_reason;
let mut content_parts = Vec::new();
if !text.is_empty() {
content_parts.push(ContentPart::text(&text));
}
for call in &tool_calls {
content_parts.push(ContentPart::ToolCall(call.clone()));
}
if !content_parts.is_empty() {
self.session.add_message(Message::assistant(content_parts));
}
if !text.is_empty() {
self.event_bus.publish(Event::MessageComplete {
session_id: self.session.id.clone(),
message_id: format!("msg_{}", self.session.message_count()),
});
}
if !tool_calls.is_empty() {
if let Some(ref token) = cancel_token {
if token.is_cancelled() {
info!(steps, "Agent run cancelled before tool execution");
return Err(AgentRunError::Cancelled);
}
}
let results = self.execute_tools(&tool_calls).await;
self.session.add_message(Message::tool_results(results));
continue;
}
break;
}
info!(
steps,
text_len = accumulated_text.len(),
tool_calls = all_tool_calls.len(),
"Agent turn complete"
);
Ok(TurnResult::new(
accumulated_text,
all_tool_calls,
final_stop_reason,
steps,
))
}
fn build_request(&self) -> CompletionRequest {
let system_prompt = self.config.build_system_prompt(&self.prompt_store);
let mut request = CompletionRequest::new(system_prompt)
.with_messages(self.session.messages.iter().cloned());
let tool_infos: Vec<ToolInfo> = self.tools.tool_infos_with_store(&self.prompt_store);
if !tool_infos.is_empty() {
request = request.with_tools(tool_infos);
}
request
}
async fn process_stream(
&self,
stream: &mut crate::provider::CompletionStream,
) -> Result<(String, Vec<ToolCall>, StopReason), AgentRunError> {
let mut text = String::new();
let mut tool_calls: Vec<ToolCallBuilder> = Vec::new();
let mut stop_reason = StopReason::EndTurn;
while let Some(event) = stream.next().await {
match event {
StreamEvent::MessageStart { message_id } => {
debug!(message_id, "Stream started");
}
StreamEvent::TextDelta { text: delta } => {
text.push_str(&delta);
self.event_bus.publish(Event::MessageDelta {
session_id: self.session.id.clone(),
message_id: "streaming".to_string(),
delta,
});
}
StreamEvent::ToolCallStart { index, id, name } => {
while tool_calls.len() <= index {
tool_calls.push(ToolCallBuilder::default());
}
tool_calls[index].id = id;
tool_calls[index].name = name;
}
StreamEvent::ToolCallDelta {
index,
arguments_delta,
} => {
if index < tool_calls.len() {
tool_calls[index].arguments.push_str(&arguments_delta);
}
}
StreamEvent::ToolCallEnd { index: _ } => {
}
StreamEvent::MessageEnd {
stop_reason: reason,
usage: _,
} => {
stop_reason = reason;
}
StreamEvent::Error { message, code } => {
warn!(message, ?code, "Stream error");
return Err(AgentRunError::Provider(ProviderError::ProviderError {
message,
}));
}
}
}
let completed_tool_calls: Vec<ToolCall> = tool_calls
.into_iter()
.filter(|b| !b.id.is_empty() && !b.name.is_empty())
.map(|b| {
let arguments = serde_json::from_str(&b.arguments).unwrap_or(serde_json::json!({}));
ToolCall::new(b.id, b.name, arguments)
})
.collect();
Ok((text, completed_tool_calls, stop_reason))
}
async fn execute_tools(&self, tool_calls: &[ToolCall]) -> Vec<ToolResult> {
let mut results = Vec::with_capacity(tool_calls.len());
for call in tool_calls {
debug!(tool = %call.name, id = %call.id, "Executing tool");
self.event_bus.publish(Event::ToolCallStarted {
session_id: self.session.id.clone(),
tool_name: call.name.clone(),
tool_call_id: call.id.clone(),
arguments: Some(call.arguments.clone()),
});
let (result, file_change) = if let Some(tool) = self.tools.get(&call.name) {
let output = tool.execute(call.arguments.clone()).await;
let file_change = output.file_change.clone();
let result = if output.is_error {
ToolResult::failure(&call.id, &output.content)
} else {
ToolResult::success(&call.id, &output.content)
};
(result, file_change)
} else {
warn!(tool = %call.name, "Tool not found");
(ToolResult::failure(&call.id, format!("Tool '{}' not found", call.name)), None)
};
self.event_bus.publish(Event::ToolCallCompleted {
session_id: self.session.id.clone(),
tool_call_id: call.id.clone(),
success: result.is_success(),
file_change,
});
results.push(result);
}
results
}
}
#[derive(Default)]
struct ToolCallBuilder {
id: String,
name: String,
arguments: String,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tool::{Tool, ToolOutput};
use async_trait::async_trait;
fn test_prompt_store() -> Arc<PromptStore> {
Arc::new(PromptStore::default())
}
struct MockProvider {
responses: Vec<Vec<StreamEvent>>,
call_count: std::sync::atomic::AtomicUsize,
}
impl MockProvider {
fn new(responses: Vec<Vec<StreamEvent>>) -> Self {
Self {
responses,
call_count: std::sync::atomic::AtomicUsize::new(0),
}
}
fn single_response(text: &str) -> Self {
Self::new(vec![vec![
StreamEvent::message_start("msg_1"),
StreamEvent::text_delta(text),
StreamEvent::message_end(StopReason::EndTurn),
]])
}
}
#[async_trait]
impl Provider for MockProvider {
fn name(&self) -> &str {
"mock"
}
fn model(&self) -> &str {
"mock-model"
}
async fn complete(
&self,
_request: CompletionRequest,
) -> Result<crate::provider::CompletionStream, ProviderError> {
let idx = self
.call_count
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let events = self.responses.get(idx).cloned().unwrap_or_default();
Ok(Box::pin(tokio_stream::iter(events)))
}
}
struct EchoTool;
#[async_trait]
impl Tool for EchoTool {
fn name(&self) -> &str {
"echo"
}
fn description(&self) -> &str {
"Echoes back the input"
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"message": { "type": "string" }
},
"required": ["message"]
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let message = params["message"].as_str().unwrap_or("no message");
ToolOutput::success(format!("Echo: {}", message))
}
}
#[test]
fn test_agent_creation() {
let provider = Arc::new(MockProvider::single_response("Hello"));
let config = AgentConfig::default();
let agent = Agent::new(provider, config, test_prompt_store());
assert!(agent.tools().is_empty());
assert!(agent.session().messages.is_empty());
}
#[test]
fn test_agent_with_session() {
let provider = Arc::new(MockProvider::single_response("Hello"));
let config = AgentConfig::default();
let mut session = Session::new();
session.add_message(Message::user("Previous message"));
let agent = Agent::with_session(provider, config, test_prompt_store(), session);
assert_eq!(agent.session().messages.len(), 1);
}
#[test]
fn test_register_tool() {
let provider = Arc::new(MockProvider::single_response("Hello"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
agent.tools_mut().register(Arc::new(EchoTool));
assert!(agent.tools().get("echo").is_some());
}
#[tokio::test]
async fn test_simple_run() {
let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
let result = agent.run("Hello!").await.unwrap();
assert_eq!(result.text, "Hello, I'm Claude!");
assert!(result.tool_calls.is_empty());
assert_eq!(result.stop_reason, StopReason::EndTurn);
assert_eq!(result.steps, 1);
}
#[tokio::test]
async fn test_run_updates_session() {
let provider = Arc::new(MockProvider::single_response("Response"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
agent.run("User input").await.unwrap();
let messages = &agent.session().messages;
assert_eq!(messages.len(), 2);
assert!(messages[0].is_user());
assert!(messages[1].is_assistant());
}
#[tokio::test]
async fn test_max_steps_exceeded() {
let responses = (0..100)
.map(|_| {
vec![
StreamEvent::message_start("msg"),
StreamEvent::ToolCallStart {
index: 0,
id: "call_1".to_string(),
name: "echo".to_string(),
},
StreamEvent::ToolCallDelta {
index: 0,
arguments_delta: r#"{"message":"test"}"#.to_string(),
},
StreamEvent::ToolCallEnd { index: 0 },
StreamEvent::MessageEnd {
stop_reason: StopReason::ToolUse,
usage: None,
},
]
})
.collect();
let provider = Arc::new(MockProvider::new(responses));
let config = AgentConfig::default().with_max_steps(3);
let mut agent = Agent::new(provider, config, test_prompt_store());
agent.tools_mut().register(Arc::new(EchoTool));
let result = agent.run("Hello").await;
assert!(matches!(result, Err(AgentRunError::MaxStepsExceeded { max_steps: 3 })));
}
#[tokio::test]
async fn test_tool_execution() {
let responses = vec![
vec![
StreamEvent::message_start("msg_1"),
StreamEvent::text_delta("Let me echo that."),
StreamEvent::ToolCallStart {
index: 0,
id: "call_1".to_string(),
name: "echo".to_string(),
},
StreamEvent::ToolCallDelta {
index: 0,
arguments_delta: r#"{"message":"hello"}"#.to_string(),
},
StreamEvent::ToolCallEnd { index: 0 },
StreamEvent::MessageEnd {
stop_reason: StopReason::ToolUse,
usage: None,
},
],
vec![
StreamEvent::message_start("msg_2"),
StreamEvent::text_delta("The echo returned: Echo: hello"),
StreamEvent::MessageEnd {
stop_reason: StopReason::EndTurn,
usage: None,
},
],
];
let provider = Arc::new(MockProvider::new(responses));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
agent.tools_mut().register(Arc::new(EchoTool));
let result = agent.run("Echo hello").await.unwrap();
assert!(result.text.contains("echo"));
assert_eq!(result.tool_calls.len(), 1);
assert_eq!(result.tool_calls[0].name, "echo");
assert_eq!(result.steps, 2);
}
#[tokio::test]
async fn test_tool_not_found() {
let responses = vec![
vec![
StreamEvent::message_start("msg_1"),
StreamEvent::ToolCallStart {
index: 0,
id: "call_1".to_string(),
name: "nonexistent_tool".to_string(),
},
StreamEvent::ToolCallDelta {
index: 0,
arguments_delta: "{}".to_string(),
},
StreamEvent::ToolCallEnd { index: 0 },
StreamEvent::MessageEnd {
stop_reason: StopReason::ToolUse,
usage: None,
},
],
vec![
StreamEvent::message_start("msg_2"),
StreamEvent::text_delta("Tool not found"),
StreamEvent::MessageEnd {
stop_reason: StopReason::EndTurn,
usage: None,
},
],
];
let provider = Arc::new(MockProvider::new(responses));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
let _result = agent.run("Use unknown tool").await.unwrap();
let messages = &agent.session().messages;
assert_eq!(messages.len(), 4);
}
#[test]
fn test_turn_result() {
let result = TurnResult::new(
"Hello".to_string(),
vec![],
StopReason::EndTurn,
1,
);
assert_eq!(result.text, "Hello");
assert!(result.tool_calls.is_empty());
assert_eq!(result.stop_reason, StopReason::EndTurn);
assert_eq!(result.steps, 1);
}
#[test]
fn test_agent_run_error_display() {
let err = AgentRunError::tool("Tool failed");
assert!(err.to_string().contains("Tool failed"));
let err = AgentRunError::MaxStepsExceeded { max_steps: 10 };
assert!(err.to_string().contains("10"));
}
#[test]
fn test_cancellation_error() {
let err = AgentRunError::Cancelled;
assert!(err.is_cancelled());
assert!(err.to_string().contains("cancelled"));
let err = AgentRunError::tool("some error");
assert!(!err.is_cancelled());
}
#[tokio::test]
async fn test_run_with_already_cancelled_token() {
let provider = Arc::new(MockProvider::single_response("Hello"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
let token = CancellationToken::new();
token.cancel();
let result = agent.run_with_cancellation("Hello", Some(token)).await;
assert!(matches!(result, Err(AgentRunError::Cancelled)));
}
#[tokio::test]
async fn test_run_with_no_cancellation() {
let provider = Arc::new(MockProvider::single_response("Hello, I'm Claude!"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
let token = CancellationToken::new();
let result = agent.run_with_cancellation("Hello!", Some(token)).await.unwrap();
assert_eq!(result.text, "Hello, I'm Claude!");
}
#[tokio::test]
async fn test_run_without_token_works() {
let provider = Arc::new(MockProvider::single_response("Response"));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
let result = agent.run_with_cancellation("Hello", None).await.unwrap();
assert_eq!(result.text, "Response");
}
#[tokio::test]
async fn test_cancellation_during_tool_loop() {
let responses = vec![
vec![
StreamEvent::message_start("msg_1"),
StreamEvent::ToolCallStart {
index: 0,
id: "call_1".to_string(),
name: "echo".to_string(),
},
StreamEvent::ToolCallDelta {
index: 0,
arguments_delta: r#"{"message":"test"}"#.to_string(),
},
StreamEvent::ToolCallEnd { index: 0 },
StreamEvent::MessageEnd {
stop_reason: StopReason::ToolUse,
usage: None,
},
],
];
let provider = Arc::new(MockProvider::new(responses));
let config = AgentConfig::default();
let mut agent = Agent::new(provider, config, test_prompt_store());
agent.tools_mut().register(Arc::new(EchoTool));
let token = CancellationToken::new();
let cancel_token = token.clone();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
cancel_token.cancel();
});
tokio::time::sleep(std::time::Duration::from_millis(5)).await;
let result = agent.run_with_cancellation("Use tool", Some(token)).await;
assert!(result.is_ok() || matches!(result, Err(AgentRunError::Cancelled)));
}
}