use std::collections::{HashMap, HashSet};
use std::num::NonZeroU32;
use std::sync::Arc;
use crate::event::{Event, EventSink};
use crate::message::{Content, Message, Role};
use crate::output::{ModelOutput, Step, StopReason};
use crate::provider::{ModelProvider, ProviderError};
use crate::request::{ChatParams, ModelRequest};
use crate::session::Session;
use crate::tool::{
ReplaySafety, ToolCall, ToolContext, ToolProgress, ToolResolver, ToolResult, ToolStatus,
};
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
pub enum AgentError {
#[error("agent built without a model provider")]
MissingProvider,
#[error(transparent)]
Provider(#[from] ProviderError),
#[error(transparent)]
Commit(#[from] CommitError),
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("commit failed: {0}")]
pub struct CommitError(
pub String,
);
impl AgentError {
pub fn is_retryable(&self) -> bool {
matches!(self, AgentError::Provider(err) if err.is_retryable())
}
}
struct ForwardingSink<'a> {
inner: &'a mut dyn EventSink,
announced: HashSet<String>,
}
impl EventSink for ForwardingSink<'_> {
fn emit(&mut self, event: Event<'_>) {
if let Event::ToolCallStart { id, .. } = event {
self.announced.insert(id.to_owned());
}
self.inner.emit(event);
}
}
struct CallProgress<'sink, 'a> {
id: String,
events: &'sink mut ForwardingSink<'a>,
}
impl ToolProgress for CallProgress<'_, '_> {
fn output(&mut self, chunk: &str) {
self.events.emit(Event::ToolOutputDelta {
id: &self.id,
chunk,
});
}
fn status(&mut self, status: ToolStatus) {
self.events.emit(Event::ToolStatus {
id: &self.id,
status: &status,
});
}
}
pub type CommitHook = Box<dyn Fn(&Session) -> Result<(), CommitError> + Send + Sync>;
pub struct Agent {
provider: Arc<dyn ModelProvider>,
resolver: Option<Arc<dyn ToolResolver>>,
system: Option<String>,
params: ChatParams,
commit: Option<CommitHook>,
steps: u32,
}
impl std::fmt::Debug for Agent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Agent")
.field("provider", &"<dyn ModelProvider>")
.field(
"resolver",
&self.resolver.as_ref().map(|_| "<dyn ToolResolver>"),
)
.field("system", &self.system)
.field("params", &self.params)
.field("commit", &self.commit.as_ref().map(|_| "<commit hook>"))
.field("steps", &self.steps)
.finish()
}
}
impl Agent {
pub fn builder() -> AgentBuilder {
AgentBuilder::default()
}
pub async fn step(
&mut self,
session: &mut Session,
sink: &mut dyn EventSink,
ctx: &ToolContext,
) -> Result<Step, AgentError> {
let iteration = self.steps;
self.steps += 1;
close_orphaned_calls(&mut session.history);
let mut events = ForwardingSink {
inner: sink,
announced: HashSet::new(),
};
events.emit(Event::StepStart { iteration });
if let Some(commit) = &self.commit {
commit(session).map_err(AgentError::Commit)?;
}
let req = ModelRequest {
system: self.system.clone(),
messages: session.history.clone(),
tools: self
.resolver
.as_ref()
.map(|r| r.specs())
.unwrap_or_default(),
params: self.params.clone(),
}
.normalized();
let out = self.provider.complete(req, &mut events).await?;
let call_indices: Vec<usize> = out
.message
.content
.iter()
.enumerate()
.filter_map(|(i, c)| matches!(c, Content::ToolCall(_)).then_some(i))
.collect();
session.history.push(out.message.clone());
if out.stop_reason == StopReason::ToolUse {
if let Some(commit) = &self.commit {
commit(session).map_err(AgentError::Commit)?;
}
for i in call_indices {
let Some(Content::ToolCall(call)) = out.message.content.get(i) else {
continue;
};
if !events.announced.contains(&call.id) {
events.emit(Event::ToolCallStart {
id: &call.id,
name: &call.name,
});
}
let result = {
let mut progress = CallProgress {
id: call.id.clone(),
events: &mut events,
};
match &self.resolver {
Some(resolver) => {
resolver
.resolve_streaming(call.clone(), ctx, &mut progress)
.await
}
None => ToolResult::failure(&call.id, "no tool resolver is configured"),
}
};
events.emit(Event::ToolResult {
id: &result.id,
content: &result.content,
is_error: result.is_error,
code: result.code,
});
session.history.push(Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(result)],
});
}
}
if let Some(commit) = &self.commit {
commit(session).map_err(AgentError::Commit)?;
}
events.emit(Event::StepEnd {
usage: out.usage,
stop_reason: &out.stop_reason,
});
Ok(Step { output: out })
}
pub const DEFAULT_TURN_STEPS: NonZeroU32 = NonZeroU32::new(32).unwrap();
pub async fn turn(
&mut self,
input: impl Into<Message>,
session: &mut Session,
sink: &mut dyn EventSink,
ctx: &ToolContext,
) -> Result<ModelOutput, AgentError> {
self.turn_with_limit(input, session, sink, ctx, Self::DEFAULT_TURN_STEPS)
.await
}
pub async fn turn_with_limit(
&mut self,
input: impl Into<Message>,
session: &mut Session,
sink: &mut dyn EventSink,
ctx: &ToolContext,
max_iterations: NonZeroU32,
) -> Result<ModelOutput, AgentError> {
run_turn(self, session, input.into(), sink, ctx, max_iterations).await
}
pub async fn resume_turn(
&mut self,
session: &mut Session,
sink: &mut dyn EventSink,
ctx: &ToolContext,
) -> Result<ModelOutput, AgentError> {
self.resume_turn_with_limit(session, sink, ctx, Self::DEFAULT_TURN_STEPS)
.await
}
pub async fn resume_turn_with_limit(
&mut self,
session: &mut Session,
sink: &mut dyn EventSink,
ctx: &ToolContext,
max_iterations: NonZeroU32,
) -> Result<ModelOutput, AgentError> {
let mut step = self.step(session, sink, ctx).await?;
let mut remaining = max_iterations.get() - 1;
while step.output.stop_reason == StopReason::ToolUse && remaining > 0 {
step = self.step(session, sink, ctx).await?;
remaining -= 1;
}
Ok(step.output)
}
pub fn system(&self) -> Option<&str> {
self.system.as_deref()
}
pub fn set_commit_hook(&mut self, hook: Option<CommitHook>) {
self.commit = hook;
}
}
#[derive(Default)]
pub struct AgentBuilder {
provider: Option<Arc<dyn ModelProvider>>,
resolver: Option<Arc<dyn ToolResolver>>,
system: Option<String>,
model: Option<String>,
params: Option<ChatParams>,
commit: Option<CommitHook>,
}
impl std::fmt::Debug for AgentBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AgentBuilder")
.field(
"provider",
&self.provider.as_ref().map(|_| "<dyn ModelProvider>"),
)
.field(
"resolver",
&self.resolver.as_ref().map(|_| "<dyn ToolResolver>"),
)
.field("system", &self.system)
.field("model", &self.model)
.field("params", &self.params)
.field("commit", &self.commit.as_ref().map(|_| "<commit hook>"))
.finish()
}
}
impl AgentBuilder {
pub fn provider(mut self, provider: impl ModelProvider + 'static) -> Self {
self.provider = Some(Arc::new(provider));
self
}
pub fn resolver(mut self, resolver: impl ToolResolver + 'static) -> Self {
self.resolver = Some(Arc::new(resolver));
self
}
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
pub fn system(mut self, system: impl Into<String>) -> Self {
self.system = Some(system.into());
self
}
pub fn params(mut self, params: ChatParams) -> Self {
self.params = Some(params);
self
}
pub fn commit_hook(mut self, hook: CommitHook) -> Self {
self.commit = Some(hook);
self
}
pub fn build(self) -> Result<Agent, AgentError> {
let mut params = self.params.unwrap_or_default();
if let Some(model) = self.model {
params.model = model;
}
Ok(Agent {
provider: self.provider.ok_or(AgentError::MissingProvider)?,
resolver: self.resolver,
system: self.system,
params,
commit: self.commit,
steps: 0,
})
}
}
pub fn close_orphaned_calls(history: &mut Vec<Message>) -> Vec<String> {
let results = dangling_calls(history).into_iter().map(|call| {
ToolResult::failure(
&call.id,
"the turn was interrupted before this call ran; nothing happened",
)
});
insert_missing(history, results)
}
fn dangling_calls(history: &[Message]) -> Vec<ToolCall> {
let mut found = Vec::new();
let mut index = 0;
while index < history.len() {
if history[index].role != Role::Assistant {
index += 1;
continue;
}
let mut calls = Vec::new();
let mut seen = HashSet::new();
for content in &history[index].content {
if let Content::ToolCall(call) = content
&& seen.insert(call.id.clone())
{
calls.push(call.clone());
}
}
if calls.is_empty() {
index += 1;
continue;
}
let mut block_end = index + 1;
while block_end < history.len() && history[block_end].role == Role::Tool {
block_end += 1;
}
let answered: HashSet<&str> = history[index + 1..block_end]
.iter()
.flat_map(|message| message.content.iter())
.filter_map(|content| match content {
Content::ToolResult(result) => Some(result.id.as_str()),
_ => None,
})
.collect();
found.extend(
calls
.into_iter()
.filter(|call| !answered.contains(call.id.as_str())),
);
index = block_end;
}
found
}
fn insert_missing(
history: &mut Vec<Message>,
mut results: impl Iterator<Item = ToolResult>,
) -> Vec<String> {
let mut repaired = Vec::new();
let mut index = 0;
while index < history.len() {
if history[index].role != Role::Assistant {
index += 1;
continue;
}
let mut calls = Vec::new();
let mut seen = HashSet::new();
for content in &history[index].content {
if let Content::ToolCall(call) = content
&& seen.insert(call.id.clone())
{
calls.push(call.id.clone());
}
}
if calls.is_empty() {
index += 1;
continue;
}
let mut block_end = index + 1;
while block_end < history.len() && history[block_end].role == Role::Tool {
block_end += 1;
}
let answered: HashSet<&str> = history[index + 1..block_end]
.iter()
.flat_map(|message| message.content.iter())
.filter_map(|content| match content {
Content::ToolResult(result) => Some(result.id.as_str()),
_ => None,
})
.collect();
let missing: Vec<&String> = calls
.iter()
.filter(|id| !answered.contains(id.as_str()))
.collect();
if missing.is_empty() {
index += 1;
continue;
}
let rank: HashMap<&str, usize> = calls
.iter()
.enumerate()
.map(|(position, id)| (id.as_str(), position))
.collect();
for id in missing {
let result = results
.next()
.expect("one result per dangling call, in call order");
let call_rank = rank[id.as_str()];
let mut insert_at = index + 1;
for (offset, message) in history[index + 1..block_end].iter().enumerate() {
let position = index + 1 + offset;
let mut earlier = false;
let mut later = false;
for content in &message.content {
if let Content::ToolResult(result) = content
&& let Some(other) = rank.get(result.id.as_str())
{
earlier |= *other < call_rank;
later |= *other > call_rank;
}
}
if earlier {
insert_at = position + 1;
}
if later {
break;
}
}
history.insert(
insert_at,
Message {
role: Role::Tool,
content: vec![Content::ToolResult(result)],
annotations: Default::default(),
},
);
block_end += 1;
repaired.push(id.clone());
}
index = block_end;
}
repaired
}
pub async fn revive_dangling_calls(
session: &mut Session,
resolver: &dyn ToolResolver,
ctx: &ToolContext,
) {
let dangling = dangling_calls(&session.history);
if dangling.is_empty() {
return;
}
let mut results = Vec::with_capacity(dangling.len());
for call in dangling {
results.push(match resolver.replay_safety(&call.name) {
ReplaySafety::Safe => resolver.resolve(call, ctx).await,
ReplaySafety::Unsafe => ToolResult::failure(
&call.id,
"interrupted: the call was committed but its result never \
landed; its effect may have partially applied, verify \
state before retrying",
),
});
}
insert_missing(&mut session.history, results.into_iter());
}
pub async fn run_turn(
agent: &mut Agent,
session: &mut Session,
input: Message,
sink: &mut dyn EventSink,
ctx: &ToolContext,
max_iterations: NonZeroU32,
) -> Result<ModelOutput, AgentError> {
session.history.push(input);
let mut step = agent.step(session, sink, ctx).await?;
let mut remaining = max_iterations.get() - 1;
while step.output.stop_reason == StopReason::ToolUse && remaining > 0 {
step = agent.step(session, sink, ctx).await?;
remaining -= 1;
}
Ok(step.output)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tool::ToolCall;
#[test]
fn a_dangling_call_is_answered_with_one_synthetic_failure() {
let mut history = vec![
Message::text(Role::User, "run it"),
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(ToolCall {
id: "call-1".into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})],
},
];
let answered = close_orphaned_calls(&mut history);
assert_eq!(answered, ["call-1"]);
assert_eq!(history.len(), 3);
let Some(Content::ToolResult(result)) = history[2].content.first() else {
panic!("the tail is the synthetic result");
};
assert_eq!(result.id, "call-1");
assert!(result.is_error, "an interrupted call reads as a failure");
}
#[test]
fn a_reused_call_id_is_answered_per_turn() {
let assistant = |id: &str| Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(ToolCall {
id: id.into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})],
};
let mut history = vec![
Message::text(Role::User, "first"),
assistant("call_0"),
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult::failure(
"call_0",
"already answered",
))],
},
Message::text(Role::User, "second"),
assistant("call_0"),
];
let answered = close_orphaned_calls(&mut history);
assert_eq!(answered, ["call_0"]);
assert_eq!(history.len(), 6, "one synthetic result, no duplicates");
let Some(Content::ToolResult(result)) = history[5].content.first() else {
panic!("the tail answers the second call");
};
assert_eq!(result.id, "call_0");
assert!(result.is_error);
}
#[test]
fn an_answered_history_is_left_alone() {
let mut history = vec![
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::ToolCall(ToolCall {
id: "call-1".into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})],
},
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult::failure(
"call-1",
"already answered",
))],
},
];
let before = history.clone();
assert!(close_orphaned_calls(&mut history).is_empty());
assert_eq!(history.len(), before.len());
}
#[test]
fn only_the_unanswered_calls_are_repaired() {
let call = |id: &str| {
Content::ToolCall(ToolCall {
id: id.into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})
};
let mut history = vec![
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![call("answered"), call("dangling"), call("duplicated")],
},
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult::failure(
"answered",
"the one that ran",
))],
},
Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult::failure(
"duplicated",
"the twin that ran",
))],
},
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![Content::Text("done".into())],
},
];
let answered = close_orphaned_calls(&mut history);
assert_eq!(answered, ["dangling"]);
assert_eq!(history.len(), 5);
}
#[test]
fn a_non_tail_orphan_is_answered_before_later_messages() {
let call = |id: &str| {
Content::ToolCall(ToolCall {
id: id.into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})
};
let mut history = vec![
Message::text(Role::User, "run it"),
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![call("dangling")],
},
Message::text(Role::User, "later"),
Message::text(Role::Assistant, "done"),
];
let answered = close_orphaned_calls(&mut history);
assert_eq!(answered, ["dangling"]);
assert_eq!(history.len(), 5);
let Some(Content::ToolResult(result)) = history[2].content.first() else {
panic!("the result sits directly after its assistant message");
};
assert_eq!(result.id, "dangling");
assert_eq!(
history[3].role,
Role::User,
"later messages keep their order"
);
assert_eq!(history[4].role, Role::Assistant);
}
#[test]
fn a_missing_call_keeps_its_place_in_the_result_block() {
let call = |id: &str| {
Content::ToolCall(ToolCall {
id: id.into(),
name: "bash".into(),
args: serde_json::json!({"command": "echo hi"}),
provider_data: serde_json::Value::Null,
})
};
let result = |id: &str| Message {
annotations: Default::default(),
role: Role::Tool,
content: vec![Content::ToolResult(ToolResult::failure(id, "ran"))],
};
let mut missing_first = vec![
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![call("missing"), call("answered")],
},
result("answered"),
Message::text(Role::Assistant, "done"),
];
assert_eq!(close_orphaned_calls(&mut missing_first), ["missing"]);
assert_eq!(missing_first.len(), 4);
let Some(Content::ToolResult(first)) = missing_first[1].content.first() else {
panic!("the missing call goes before the later result");
};
assert_eq!(first.id, "missing");
let Some(Content::ToolResult(second)) = missing_first[2].content.first() else {
panic!("the answered call keeps its result");
};
assert_eq!(second.id, "answered");
let mut missing_last = vec![
Message {
annotations: Default::default(),
role: Role::Assistant,
content: vec![call("answered"), call("missing")],
},
result("answered"),
Message::text(Role::Assistant, "done"),
];
assert_eq!(close_orphaned_calls(&mut missing_last), ["missing"]);
assert_eq!(missing_last.len(), 4);
let Some(Content::ToolResult(second)) = missing_last[2].content.first() else {
panic!("the missing call goes after the earlier result");
};
assert_eq!(second.id, "missing");
}
#[test]
fn a_retryable_provider_failure_reads_retryable() {
assert!(AgentError::Provider(ProviderError::Network("dead link".into())).is_retryable());
assert!(AgentError::Provider(ProviderError::Timeout).is_retryable());
assert!(
AgentError::Provider(ProviderError::Api {
message: "server error (HTTP 502)".into(),
status: Some(502),
})
.is_retryable()
);
}
#[test]
fn everything_else_reads_permanent() {
assert_eq!(AgentError::MissingProvider, AgentError::MissingProvider);
assert!(!AgentError::MissingProvider.is_retryable());
assert!(
!AgentError::Provider(ProviderError::Api {
message: "rate limit".into(),
status: Some(429),
})
.is_retryable()
);
assert!(!AgentError::Commit(CommitError("disk full".into())).is_retryable());
assert!(!AgentError::MissingProvider.is_retryable());
}
}
#[cfg(test)]
mod revive_tests {
use super::*;
use crate::request::ToolSpec;
use serde_json::json;
struct Mixed;
#[async_trait::async_trait]
impl ToolResolver for Mixed {
fn specs(&self) -> Vec<ToolSpec> {
vec![
ToolSpec::new("safe_tool", "safe to re-run", json!({})),
ToolSpec::new("unsafe_tool", "must not re-run", json!({})),
]
}
async fn resolve(&self, call: ToolCall, _ctx: &ToolContext) -> ToolResult {
ToolResult::success(call.id, "re-ran")
}
fn replay_safety(&self, name: &str) -> ReplaySafety {
match name {
"safe_tool" => ReplaySafety::Safe,
_ => ReplaySafety::Unsafe,
}
}
}
fn call(id: &str, name: &str) -> ToolCall {
ToolCall {
id: id.into(),
name: name.into(),
args: json!({}),
provider_data: serde_json::Value::Null,
}
}
fn session_with_dangling() -> Session {
let mut session = Session::default();
session.history.push(Message::text(Role::User, "go"));
session.history.push(Message {
role: Role::Assistant,
content: vec![
Content::ToolCall(call("safe_1", "safe_tool")),
Content::ToolCall(call("unsafe_1", "unsafe_tool")),
],
annotations: Default::default(),
});
session
}
#[tokio::test]
async fn revive_reexecutes_safe_calls_and_reports_unsafe_ones() {
let mut session = session_with_dangling();
revive_dangling_calls(&mut session, &Mixed, &ToolContext::default()).await;
assert_eq!(session.history.len(), 4);
let results: Vec<&ToolResult> = session.history[2..]
.iter()
.flat_map(|message| message.content.iter())
.filter_map(|content| match content {
Content::ToolResult(result) => Some(result),
_ => None,
})
.collect();
assert_eq!(results[0].id, "safe_1");
assert!(!results[0].is_error);
assert_eq!(results[0].content, "re-ran");
assert_eq!(results[1].id, "unsafe_1");
assert!(results[1].is_error);
assert!(results[1].content.contains("interrupted"));
revive_dangling_calls(&mut session, &Mixed, &ToolContext::default()).await;
assert_eq!(session.history.len(), 4);
}
#[tokio::test]
async fn revive_leaves_a_clean_history_alone() {
let mut session = Session::default();
session.history.push(Message::text(Role::User, "go"));
session.history.push(Message::text(Role::Assistant, "done"));
revive_dangling_calls(&mut session, &Mixed, &ToolContext::default()).await;
assert_eq!(session.history.len(), 2);
}
}