use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use anyhow::Result;
use async_trait::async_trait;
use crate::agent_loop::{AgentLoop, AgentLoopConfig, ToolEventSink};
use crate::agents::AgentConfig;
use crate::llm::LlmClientTrait;
use crate::mode::HarnessMode;
use crate::prompt::assemble_system_prompt_for_mode;
use crate::provider::{resolve_max_tokens, resolve_model};
use crate::runner::error::RunnerError;
use crate::tools::{AgentOutput, AgentRunner, RunContext, ToolRegistry};
#[async_trait]
pub trait RegistryFactory: Send + Sync {
async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry>;
}
#[async_trait]
impl<F, Fut> RegistryFactory for F
where
F: Fn(AgentConfig, RunContext) -> Fut + Send + Sync,
Fut: std::future::Future<Output = Arc<ToolRegistry>> + Send,
{
async fn build(&self, agent: &AgentConfig, ctx: &RunContext) -> Arc<ToolRegistry> {
self(agent.clone(), ctx.clone()).await
}
}
#[derive(Debug, Clone)]
pub struct InProcessRunnerConfig {
pub max_turns: u32,
pub timeout_secs: u64,
}
impl Default for InProcessRunnerConfig {
fn default() -> Self {
Self {
max_turns: 40,
timeout_secs: 120,
}
}
}
pub struct InProcessAgentRunner {
llm: Arc<dyn LlmClientTrait>,
registry_factory: Arc<dyn RegistryFactory>,
config_dir: PathBuf,
project_context: Option<String>,
config: InProcessRunnerConfig,
sink: Option<Arc<dyn ToolEventSink>>,
cancel: Option<Arc<AtomicBool>>,
mode: HarnessMode,
skills_catalog: Option<String>,
}
impl InProcessAgentRunner {
pub fn new(
llm: Arc<dyn LlmClientTrait>,
registry_factory: Arc<dyn RegistryFactory>,
config_dir: impl Into<PathBuf>,
) -> Self {
Self {
llm,
registry_factory,
config_dir: config_dir.into(),
project_context: None,
config: InProcessRunnerConfig::default(),
sink: None,
cancel: None,
mode: HarnessMode::default(),
skills_catalog: 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_mode(mut self, mode: HarnessMode) -> Self {
self.mode = mode;
self
}
pub fn with_project_context(mut self, context: impl Into<String>) -> Self {
self.project_context = Some(context.into());
self
}
pub fn with_skills_catalog(mut self, catalog: impl Into<String>) -> Self {
self.skills_catalog = Some(catalog.into());
self
}
pub fn with_config(mut self, config: InProcessRunnerConfig) -> Self {
self.config = config;
self
}
pub fn with_timeout_secs(mut self, timeout_secs: u64) -> Self {
self.config.timeout_secs = timeout_secs;
self
}
fn load_agent(&self, agent_name: &str) -> Result<AgentConfig, RunnerError> {
let path = self.config_dir.join(format!("{agent_name}.toml"));
if !path.exists() {
return Err(RunnerError::UnknownAgent {
name: agent_name.to_string(),
dir: self.config_dir.clone(),
});
}
AgentConfig::load(&path).map_err(|source| RunnerError::ConfigLoad {
name: agent_name.to_string(),
source,
})
}
async fn run_pipeline(
&self,
agent_name: &str,
task: &str,
ctx: &RunContext,
) -> Result<AgentOutput, RunnerError> {
let agent = self.load_agent(agent_name)?;
let full_registry = self.registry_factory.build(&agent, ctx).await;
let registry = gate_registry(&full_registry, &agent);
let model = resolve_model(&agent, Some(ctx));
let max_turns = ctx.max_turns_override.unwrap_or(self.config.max_turns);
let max_tokens = resolve_max_tokens(&agent);
let loop_config = AgentLoopConfig {
max_turns,
timeout_secs: self.config.timeout_secs,
model,
max_tokens,
mode: self.mode,
compaction: crate::agent_loop::CompactionConfig::default(),
};
let system = assemble_system_prompt_for_mode(
self.mode,
&agent,
self.project_context.as_deref(),
None,
self.skills_catalog.as_deref(),
);
let mut agent_loop = AgentLoop::new(loop_config, Arc::clone(&self.llm), registry);
if let Some(sink) = &self.sink {
agent_loop = agent_loop.with_tool_event_sink(Arc::clone(sink));
}
if let Some(cancel) = &self.cancel {
agent_loop = agent_loop.with_cancel_flag(Arc::clone(cancel));
}
agent_loop
.run(&system, task)
.await
.map_err(|source| RunnerError::Loop {
name: agent_name.to_string(),
source,
})
}
}
fn gate_registry(full: &Arc<ToolRegistry>, agent: &AgentConfig) -> Arc<ToolRegistry> {
match agent.tools.as_ref().and_then(|t| t.allowed.as_ref()) {
Some(allowed) => Arc::new(full.gated(allowed)),
None => Arc::clone(full),
}
}
#[async_trait]
impl AgentRunner for InProcessAgentRunner {
async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput> {
let ctx = RunContext::default();
Ok(self.run_pipeline(agent_name, task, &ctx).await?)
}
async fn run_with_context(
&self,
agent_name: &str,
task: &str,
ctx: &RunContext,
) -> Result<AgentOutput> {
Ok(self.run_pipeline(agent_name, task, ctx).await?)
}
}
pub fn agent_config_exists(dir: &Path, name: &str) -> bool {
dir.join(format!("{name}.toml")).exists()
}