mod cadence;
mod compaction;
#[path = "compaction_control.rs"]
mod compaction_control;
mod error;
mod goals;
mod sink;
mod streaming;
pub mod telemetry;
mod transcript;
#[cfg(test)]
mod cadence_env_helper;
#[cfg(test)]
pub(crate) use cadence_env_helper::with_cadence_env;
#[cfg(test)]
mod tests;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use serde_json::Value;
use crate::llm::{
CacheControl, ChatMessage, ChatRequest, ChatResponse, InferenceAdapter, 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 cadence::{CadenceConfig, resolve_cadence_config};
pub use compaction::CompactionConfig;
pub(crate) use compaction::estimate_tokens;
pub use error::AgentLoopError;
pub use goals::{GOAL_SLOT_COUNT, GoalSlot, GoalSlotError, GoalSlots, GoalSource};
pub use sink::{ContextBudgetSnapshot, ToolEventSink};
pub use transcript::Transcript;
pub type FinishGate = Arc<dyn Fn(&Transcript) -> Option<String> + Send + Sync>;
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,
pub cadence: Option<CadenceConfig>,
pub telemetry_data_dir: Option<PathBuf>,
}
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(),
cadence: None,
telemetry_data_dir: None,
}
}
}
pub struct AgentLoop {
config: AgentLoopConfig,
llm: Arc<dyn InferenceAdapter>,
registry: Arc<ToolRegistry>,
sink: Option<Arc<dyn ToolEventSink>>,
agent: Option<String>,
agent_id: Option<String>,
session_id: Option<String>,
cancel: Option<Arc<AtomicBool>>,
stop_signal: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
finish_gate: Option<FinishGate>,
suppress_redundant_reruns: bool,
}
impl AgentLoop {
pub fn new(
config: AgentLoopConfig,
llm: Arc<dyn InferenceAdapter>,
registry: Arc<ToolRegistry>,
) -> Self {
Self {
config,
llm,
registry,
sink: None,
agent: None,
agent_id: None,
session_id: None,
cancel: None,
stop_signal: None,
finish_gate: None,
suppress_redundant_reruns: false,
}
}
pub fn with_tool_event_sink(mut self, sink: Arc<dyn ToolEventSink>) -> Self {
self.sink = Some(sink);
self
}
pub fn with_agent(mut self, name: impl Into<String>) -> Self {
self.agent = Some(name.into());
self
}
fn agent_name(&self) -> &str {
self.agent
.as_deref()
.unwrap_or(crate::events::UNATTRIBUTED_AGENT)
}
pub fn with_agent_id(mut self, id: impl Into<String>) -> Self {
self.agent_id = Some(id.into());
self
}
fn agent_id_str(&self) -> &str {
self.agent_id
.as_deref()
.unwrap_or(crate::events::UNATTRIBUTED_AGENT_ID)
}
pub fn with_session_id(mut self, session_id: impl Into<String>) -> Self {
self.session_id = Some(session_id.into());
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 fn with_finish_gate(mut self, gate: FinishGate) -> Self {
self.finish_gate = Some(gate);
self
}
pub fn with_redundant_run_suppression(mut self) -> Self {
self.suppress_redundant_reruns = true;
self
}
pub async fn run(&self, system: &str, task: &str) -> Result<AgentOutput, AgentLoopError> {
let mut transcript = Transcript::seed(system, task);
self.run_with_transcript(&mut transcript, task).await
}
pub async fn run_with_transcript(
&self,
transcript: &mut Transcript,
task: &str,
) -> Result<AgentOutput, AgentLoopError> {
let mark = transcript.assistant_text_mark();
let mut perf = PerfCollector::new(0, PERF_WORKFLOW, task);
let timeout = Duration::from_secs(self.config.timeout_secs);
let inner = self.run_inner(transcript, &mut perf);
let mut result = 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)),
}),
};
match &mut result {
Ok(output) => scope_output_to_new_turns(output, transcript, mark),
Err(e) => {
if let Some(partial) = e.partial_output_mut() {
scope_output_to_new_turns(partial, transcript, mark);
}
}
}
result
}
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_cadence_compress(transcript).await;
self.maybe_compact_transcript(transcript);
let request = self.build_request(transcript, &schemas);
let turn_id = uuid::Uuid::new_v4().to_string();
let response = self.chat_turn(&request, &turn_id).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(
self.agent_name(),
self.agent_id_str(),
&call.id,
tool,
&args.to_string(),
)
.await;
}
let mut result = if self.suppress_redundant_reruns
&& crate::redundant_run::is_test_bash_call(call)
&& crate::redundant_run::is_redundant_test_rerun(&transcript.messages(), &call.id)
{
tracing::info!(
call_id = %call.id,
"agent_loop: suppressing redundant full-suite re-run (#2682) — an \
identical test command already passed and nothing has changed since"
);
ToolResult::ok(crate::redundant_run::REDUNDANT_RERUN_MESSAGE.to_string())
} else {
self.registry.dispatch_gated(tool, args.clone(), None).await
};
if tool == FINISH_TASK_TOOL_NAME
&& !result.is_error()
&& let Some(reason) = self.finish_gate.as_ref().and_then(|gate| gate(transcript))
{
tracing::warn!(
reason = %reason,
"agent_loop: verify-before-finish gate intercepted finish_task (#2279)"
);
result = ToolResult::err(reason);
}
if let Some(sink) = &self.sink {
notify_result(
sink.as_ref(),
self.agent_name(),
self.agent_id_str(),
&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 {
let agent = self.agent_name();
let agent_id = self.agent_id_str();
sink.tool_started(agent, agent_id, call_id, tool, "<invalid-arguments>")
.await;
sink.tool_error(agent, agent_id, call_id, tool, &message)
.await;
}
transcript.push_tool_result(call_id, tool, &message);
}
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,
stop: None,
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,
agent: &str,
agent_id: &str,
call_id: &str,
tool: &str,
result: &ToolResult,
) {
if result.is_fatal() {
sink.tool_error(agent, agent_id, call_id, tool, result.content())
.await;
} else {
sink.tool_finished(
agent,
agent_id,
call_id,
tool,
!result.is_error(),
result.content(),
)
.await;
}
if let Some(telemetry) = result.telemetry() {
sink.tool_telemetry(agent, agent_id, call_id, tool, telemetry)
.await;
}
}
fn accrue_usage(perf: &mut PerfCollector, model: &str, response: &ChatResponse) {
let usage = crate::llm::token_usage(response);
perf.record_phase(PERF_PHASE, 0, model, &usage);
}
fn scope_output_to_new_turns(output: &mut AgentOutput, transcript: &Transcript, mark: usize) {
if output.summary.is_none() {
output.content = transcript.assistant_text_since(mark);
}
}
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.finish_status = Some(parsed.status);
}
output
}