mod compaction;
mod error;
mod sink;
mod transcript;
#[cfg(test)]
mod tests;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use serde_json::Value;
use crate::llm::{
CacheControl, ChatMessage, ChatRequest, ChatResponse, LlmClientTrait, RequestUsageConfig,
ToolCall, ToolCallExtractError, ToolCallExtractor, ToolDefinition,
};
use crate::mode::HarnessMode;
use crate::perf::PerfCollector;
use crate::tools::{AgentOutput, FINISH_TASK_TOOL_NAME, FinishTaskArgs, ToolRegistry, ToolResult};
pub use compaction::CompactionConfig;
pub(crate) use compaction::estimate_tokens;
pub use error::AgentLoopError;
pub use sink::ToolEventSink;
pub use transcript::Transcript;
const PERF_PHASE: &str = "agent_loop";
const PERF_WORKFLOW: &str = "agent_loop";
#[derive(Debug, Clone)]
pub struct AgentLoopConfig {
pub max_turns: u32,
pub timeout_secs: u64,
pub model: String,
pub max_tokens: u32,
pub mode: HarnessMode,
pub compaction: CompactionConfig,
}
impl Default for AgentLoopConfig {
fn default() -> Self {
Self {
max_turns: 8,
timeout_secs: 120,
model: "openai/gpt-4o-mini".to_string(),
max_tokens: crate::provider::DEFAULT_MAX_TOKENS,
mode: HarnessMode::default(),
compaction: CompactionConfig::default(),
}
}
}
pub struct AgentLoop {
config: AgentLoopConfig,
llm: Arc<dyn LlmClientTrait>,
registry: Arc<ToolRegistry>,
sink: Option<Arc<dyn ToolEventSink>>,
cancel: Option<Arc<AtomicBool>>,
stop_signal: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
}
impl AgentLoop {
pub fn new(
config: AgentLoopConfig,
llm: Arc<dyn LlmClientTrait>,
registry: Arc<ToolRegistry>,
) -> Self {
Self {
config,
llm,
registry,
sink: None,
cancel: None,
stop_signal: None,
}
}
pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
self.sink = Some(sink);
self
}
pub fn with_cancel_flag(mut self, cancel: Arc<AtomicBool>) -> Self {
self.cancel = Some(cancel);
self
}
pub fn with_stop_signal(mut self, signal: Arc<dyn Fn() -> bool + Send + Sync>) -> Self {
self.stop_signal = Some(signal);
self
}
pub async fn run(&self, system: &str, task: &str) -> Result<AgentOutput, AgentLoopError> {
let mut transcript = Transcript::seed(system, task);
let mut perf = PerfCollector::new(0, PERF_WORKFLOW, task);
let timeout = Duration::from_secs(self.config.timeout_secs);
let inner = self.run_inner(&mut transcript, &mut perf);
match tokio::time::timeout(timeout, inner).await {
Ok(result) => result,
Err(_elapsed) => Err(AgentLoopError::Timeout {
timeout_secs: self.config.timeout_secs,
partial: Box::new(build_output(&transcript, &perf)),
}),
}
}
async fn run_inner(
&self,
transcript: &mut Transcript,
perf: &mut PerfCollector,
) -> Result<AgentOutput, AgentLoopError> {
let schemas = self.tool_definitions();
for _turn in 0..self.config.max_turns {
if let Some(cancel) = &self.cancel
&& cancel.load(Ordering::Relaxed)
{
return Err(AgentLoopError::Cancelled {
partial: Box::new(build_output(transcript, perf)),
});
}
if let Some(stop) = &self.stop_signal
&& stop()
{
return Err(AgentLoopError::StoppedBySignal {
partial: Box::new(build_output(transcript, perf)),
});
}
self.maybe_compact_transcript(transcript);
let request = self.build_request(transcript, &schemas);
let response = self.llm.chat(&request).await?;
accrue_usage(perf, &self.config.model, &response);
transcript.push_response(&response);
let tool_calls = response.first_tool_calls().to_vec();
if tool_calls.is_empty() {
return Ok(build_output(transcript, perf));
}
if let Some(finish_args) = self.dispatch_all(&tool_calls, transcript).await {
return Ok(build_finish_output(transcript, perf, &finish_args));
}
}
Err(AgentLoopError::TurnCapExceeded {
max_turns: self.config.max_turns,
partial: Box::new(build_output(transcript, perf)),
})
}
async fn dispatch_all(
&self,
tool_calls: &[ToolCall],
transcript: &mut Transcript,
) -> Option<Value> {
let extractor = ToolCallExtractor::new(|name| self.registry.schema_for(name));
let mut finish_args: Option<Value> = None;
for call in tool_calls {
let tool = call.function.name.as_str();
let args = match extractor.parse_and_validate(tool, &call.function.arguments) {
Ok(args) => args,
Err(error) => {
self.report_invalid_arguments(&call.id, tool, &error, transcript)
.await;
continue;
}
};
if let Some(sink) = &self.sink {
sink.tool_started(&call.id, tool, &args.to_string()).await;
}
let result = self.registry.dispatch_gated(tool, args.clone(), None).await;
if let Some(sink) = &self.sink {
notify_result(sink.as_ref(), &call.id, tool, &result).await;
}
transcript.push_tool_result(&call.id, tool, result.content());
if tool == FINISH_TASK_TOOL_NAME && !result.is_error() {
finish_args = Some(args);
}
}
finish_args
}
async fn report_invalid_arguments(
&self,
call_id: &str,
tool: &str,
error: &ToolCallExtractError,
transcript: &mut Transcript,
) {
let message = error.to_string();
if let Some(sink) = &self.sink {
sink.tool_started(call_id, tool, "<invalid-arguments>")
.await;
sink.tool_error(call_id, tool, &message).await;
}
transcript.push_tool_result(call_id, tool, &message);
}
fn maybe_compact_transcript(&self, transcript: &mut Transcript) {
if self.config.mode == HarnessMode::DailyDriver {
transcript.maybe_compact(&self.config.compaction);
}
}
fn build_request(&self, transcript: &Transcript, schemas: &[ToolDefinition]) -> ChatRequest {
let cache_prefix = self.prompt_cache_enabled();
let provider = crate::provider::provider_for(&self.config.model);
let tools = if schemas.is_empty() {
None
} else {
let mut schemas = schemas.to_vec();
if cache_prefix {
mark_cache_breakpoint_on_tools(&mut schemas);
}
Some(schemas)
};
let tool_choice = tools.as_ref().map(|_| Value::String("auto".to_string()));
let mut messages = transcript.to_messages();
if cache_prefix {
mark_cache_breakpoint_on_system(&mut messages);
mark_cache_breakpoint_on_history(&mut messages);
}
let usage = provider
.wants_detailed_usage()
.then(RequestUsageConfig::detailed);
ChatRequest {
model: self.config.model.clone(),
messages,
temperature: Some(0.0),
max_tokens: Some(self.config.max_tokens),
tools,
tool_choice,
usage,
}
}
fn prompt_cache_enabled(&self) -> bool {
self.config.mode == HarnessMode::DailyDriver
&& crate::provider::provider_for(&self.config.model).supports_prompt_caching()
}
fn tool_definitions(&self) -> Vec<ToolDefinition> {
let schemas = match self.config.mode {
HarnessMode::Parity => self.registry.schemas(),
HarnessMode::DailyDriver => self.registry.schemas(),
};
schemas
.into_iter()
.filter_map(
|v| match serde_json::from_value::<ToolDefinition>(v.clone()) {
Ok(def) => Some(def),
Err(e) => {
let name = schema_tool_name(&v);
tracing::warn!(
"dropping unparseable tool schema (tool={name}): {e}; raw schema: {v}"
);
None
}
},
)
.collect()
}
}
fn mark_cache_breakpoint_on_tools(schemas: &mut [ToolDefinition]) {
if let Some(last) = schemas.last_mut() {
last.function.cache_control = Some(CacheControl::ephemeral());
}
}
fn mark_cache_breakpoint_on_system(messages: &mut [ChatMessage]) {
if let Some(system) = messages.iter_mut().find(|m| m.role == "system") {
system.cache_control = Some(CacheControl::ephemeral());
}
}
fn mark_cache_breakpoint_on_history(messages: &mut [ChatMessage]) {
let idxs: Vec<usize> = messages
.iter()
.enumerate()
.filter(|(_, m)| m.role != "system")
.map(|(i, _)| i)
.collect();
for &i in idxs.iter().rev().take(2) {
messages[i].cache_control = Some(CacheControl::ephemeral());
}
}
fn schema_tool_name(schema: &Value) -> &str {
schema
.get("function")
.and_then(|f| f.get("name"))
.and_then(Value::as_str)
.unwrap_or("<unknown>")
}
async fn notify_result(sink: &dyn ToolEventSink, call_id: &str, tool: &str, result: &ToolResult) {
if result.is_fatal() {
sink.tool_error(call_id, tool, result.content()).await;
} else {
sink.tool_finished(call_id, tool, !result.is_error(), result.content())
.await;
}
}
fn accrue_usage(perf: &mut PerfCollector, model: &str, response: &ChatResponse) {
let usage = response.clone().token_usage();
perf.record_phase(PERF_PHASE, 0, model, &usage);
}
fn build_output(transcript: &Transcript, perf: &PerfCollector) -> AgentOutput {
let record = perf.build_record();
let totals = &record.totals;
let mut output = AgentOutput::from_content(transcript.assistant_text());
output.usage = crate::perf::TokenUsage::new(
totals.prompt_tokens,
totals.completion_tokens,
totals.cache_read_tokens,
totals.cache_creation_tokens,
);
output
}
fn build_finish_output(
transcript: &Transcript,
perf: &PerfCollector,
finish_args: &Value,
) -> AgentOutput {
let mut output = build_output(transcript, perf);
if let Ok(parsed) = serde_json::from_value::<FinishTaskArgs>(finish_args.clone()) {
output.summary = Some(parsed.summary.clone());
output.content = crate::tools::render_finish_summary(&parsed);
}
output
}