1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//! Agent trait — decides what to do next given conversation history and tools.
use crate::types::{SgrError, ToolCall};
/// Agent's decision: what to do next.
#[derive(Debug, Clone)]
pub struct Decision {
/// Agent's assessment of the current situation.
pub situation: String,
/// Task breakdown (reasoning steps).
pub task: Vec<String>,
/// Tool calls to execute.
pub tool_calls: Vec<ToolCall>,
/// If true, the agent considers the task done.
pub completed: bool,
}
/// Errors from agent operations.
#[derive(Debug, thiserror::Error)]
pub enum AgentError {
#[error("LLM error: {0}")]
Llm(#[from] SgrError),
#[error("tool error: {0}")]
Tool(String),
#[error("loop detected after {0} iterations")]
LoopDetected(usize),
#[error("max steps reached: {0}")]
MaxSteps(usize),
#[error("cancelled")]
Cancelled,
}
/// An agent that decides what tools to call given conversation history.
///
/// Lifecycle hooks (all have default no-op implementations):
/// - `prepare_context` — called before each step to modify context
/// - `prepare_tools` — called before each step to filter/modify tool set
/// - `after_action` — called after tool execution with results
#[async_trait::async_trait]
pub trait Agent: Send + Sync {
/// Given messages and available tools, decide what to do next.
async fn decide(
&self,
messages: &[crate::types::Message],
tools: &crate::registry::ToolRegistry,
) -> Result<Decision, AgentError>;
/// Stateful decide — returns response_id for multi-turn chaining.
///
/// The agent loop tracks `response_id` across steps and passes it here.
/// Agents that support stateful sessions (e.g., HybridAgent with
/// `tools_call_stateful`) can use it for delta-only requests.
///
/// Default: delegates to stateless `decide()`, returns `None`.
async fn decide_stateful(
&self,
messages: &[crate::types::Message],
tools: &crate::registry::ToolRegistry,
_previous_response_id: Option<&str>,
) -> Result<(Decision, Option<String>), AgentError> {
let d = self.decide(messages, tools).await?;
Ok((d, None))
}
/// Hook: modify context before each step. Default: no-op.
fn prepare_context(
&self,
_ctx: &mut crate::context::AgentContext,
_messages: &[crate::types::Message],
) {
}
/// Hook: filter or reorder tools before each step.
/// Returns tool names to include. Default: all tools.
fn prepare_tools(
&self,
_ctx: &crate::context::AgentContext,
tools: &crate::registry::ToolRegistry,
) -> Vec<String> {
tools.list().iter().map(|t| t.name().to_string()).collect()
}
/// Hook: called after tool execution with the tool name and output.
/// Can modify context or messages. Default: no-op.
fn after_action(
&self,
_ctx: &mut crate::context::AgentContext,
_tool_name: &str,
_output: &str,
) {
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decision_completed() {
let d = Decision {
situation: "done".into(),
task: vec![],
tool_calls: vec![],
completed: true,
};
assert!(d.completed);
}
#[test]
fn agent_error_display() {
let err = AgentError::LoopDetected(5);
assert_eq!(err.to_string(), "loop detected after 5 iterations");
let err = AgentError::MaxSteps(50);
assert_eq!(err.to_string(), "max steps reached: 50");
}
}