use super::run::AgentRun;
use crate::{
errors::{AgentBuildError, AgentError},
interactive::InteractiveRun,
profile::{AgentProfile, AgentProfileContext},
providers::{ConfiguredModelProvider, RuntimeBuilderProviderExt},
run_result::RunResult,
stream::{
AgentEventStream, StructuredAgentEventStream, StructuredAgentRun, StructuredRunResult,
},
tools::{Tool, ToolBuildError},
};
use merry_core::{SessionId, ToolInputSchema, ToolName, ToolSpec};
use merry_llm::{GenerationConfig, ModelName, ModelProvider};
use merry_runtime::{
AgentLoopConfig, CitationCompactionPolicy, CompactionConfig, CompactionOutcome,
FileSessionStore, FinalOutputContract, HistoryRetention, Runtime, RuntimeBuilder,
RuntimeModelRole, RuntimeProfile, StepContext, StepInput, StructuredOutputRetryPolicy,
};
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use std::{
num::{NonZeroU64, NonZeroUsize},
sync::Arc,
};
pub struct AgentBuilder {
runtime_builder: RuntimeBuilder,
loop_config: AgentLoopConfig,
generation_config: GenerationConfig,
has_primary_provider: bool,
profile: Option<Arc<dyn AgentProfile>>,
}
impl AgentBuilder {
#[must_use]
pub fn new(session_id: SessionId) -> Self {
Self {
runtime_builder: Runtime::builder(session_id).session_lock(true),
loop_config: AgentLoopConfig::default(),
generation_config: GenerationConfig::default(),
has_primary_provider: false,
profile: None,
}
}
#[must_use]
pub fn provider(mut self, provider: ConfiguredModelProvider) -> Self {
self.has_primary_provider |= provider.role() == RuntimeModelRole::Primary;
self.runtime_builder = self.runtime_builder.with_provider(provider);
self
}
#[must_use]
pub fn model_provider(mut self, provider: Arc<dyn ModelProvider>, model: ModelName) -> Self {
self.runtime_builder = self.runtime_builder.model_provider(provider, model);
self.has_primary_provider = true;
self
}
#[must_use]
pub fn compaction_provider(self, provider: ConfiguredModelProvider) -> Self {
self.provider(provider.with_role(RuntimeModelRole::ContextCompaction))
}
#[must_use]
pub fn compaction_model_provider(
mut self,
provider: Arc<dyn ModelProvider>,
model: ModelName,
) -> Self {
self.runtime_builder = self.runtime_builder.model_provider_for_role(
RuntimeModelRole::ContextCompaction,
provider,
model,
);
self
}
pub fn runtime_profile(mut self, profile: RuntimeProfile) -> Result<Self, AgentBuildError> {
self.runtime_builder = self.runtime_builder.with_profile(profile)?;
Ok(self)
}
pub fn profile<P>(mut self, profile: P) -> Result<Self, AgentBuildError>
where
P: AgentProfile + 'static,
{
let mut context = AgentProfileContext::new(self.runtime_builder, self.loop_config);
profile.configure(&mut context)?;
let (runtime_builder, loop_config) = context.into_parts()?;
self.runtime_builder = runtime_builder;
self.loop_config = loop_config;
self.profile = Some(Arc::new(profile));
Ok(self)
}
#[must_use]
pub fn loop_config(mut self, config: AgentLoopConfig) -> Self {
self.loop_config = config;
self
}
#[must_use]
pub fn structured_output_retry_policy(mut self, policy: StructuredOutputRetryPolicy) -> Self {
self.loop_config = self
.loop_config
.clone()
.with_structured_output_retry_policy(policy);
self
}
#[must_use]
pub fn generation_config(mut self, config: GenerationConfig) -> Self {
self.generation_config = config;
self
}
#[must_use]
pub fn context_window_tokens(mut self, tokens: NonZeroU64) -> Self {
self.runtime_builder = self.runtime_builder.context_window_tokens(tokens);
self
}
#[must_use]
pub fn compaction(mut self, config: CompactionConfig) -> Self {
self.runtime_builder = self.runtime_builder.automatic_compaction(config);
self
}
#[must_use]
pub fn hooks(mut self, hooks: merry_runtime::HookRegistry) -> Self {
if !hooks.is_empty() {
self.runtime_builder = self.runtime_builder.hooks(Arc::new(hooks));
}
self
}
#[must_use]
pub fn hook_handler(mut self, handler: Arc<dyn merry_runtime::RuntimeHookHandler>) -> Self {
self.runtime_builder = self.runtime_builder.hooks(handler);
self
}
#[doc(hidden)]
#[must_use]
pub fn bridge_hook_subscriptions(
mut self,
subscriptions: merry_runtime::HookSubscriptions,
) -> Self {
self.runtime_builder = self
.runtime_builder
.bridge_hook_subscriptions(subscriptions);
self
}
#[must_use]
pub fn prompt_profile(mut self, profile: merry_runtime::PromptProfile) -> Self {
self.runtime_builder = self.runtime_builder.prompt_profile(profile);
self
}
#[must_use]
pub fn progress_commentary(mut self, enabled: bool) -> Self {
self.runtime_builder = self.runtime_builder.progress_commentary(enabled);
self
}
#[must_use]
pub fn tool(mut self, tool: Tool) -> Self {
self.runtime_builder = self
.runtime_builder
.register_tool(tool.into_registered_tool());
self
}
#[cfg(feature = "mcp")]
#[must_use]
pub fn mcp_toolset(self, toolset: crate::mcp::McpToolset) -> Self {
let (tools, _warnings) = toolset.into_parts();
self.register_tools(tools)
}
pub fn bridge_tool(
self,
name: ToolName,
description: &str,
input_schema: ToolInputSchema,
) -> Result<Self, AgentBuildError> {
let spec = ToolSpec::new(name, description, input_schema)
.map_err(ToolBuildError::from)
.map_err(|source| AgentBuildError::Tool { source })?;
Ok(self
.allow_bridge_tools()
.register_tool(merry_runtime::RegisteredTool::bridge(spec)))
}
#[doc(hidden)]
#[must_use]
pub fn bridge_tool_spec(self, spec: ToolSpec) -> Self {
self.allow_bridge_tools()
.register_tool(merry_runtime::RegisteredTool::bridge(spec))
}
#[doc(hidden)]
#[must_use]
pub fn register_tool(mut self, tool: merry_runtime::RegisteredTool) -> Self {
self.runtime_builder = self.runtime_builder.register_tool(tool);
self
}
#[doc(hidden)]
#[must_use]
pub fn register_tools<I>(mut self, tools: I) -> Self
where
I: IntoIterator<Item = merry_runtime::RegisteredTool>,
{
for tool in tools {
self = self.register_tool(tool);
}
self
}
#[doc(hidden)]
#[must_use]
pub fn allow_bridge_tools(mut self) -> Self {
self.runtime_builder = self.runtime_builder.allow_bridge_tools();
self
}
#[must_use]
pub fn session_store(mut self, store: FileSessionStore) -> Self {
self.runtime_builder = self.runtime_builder.session_store(store);
self
}
#[must_use]
pub fn session_lock(mut self, enabled: bool) -> Self {
self.runtime_builder = self.runtime_builder.session_lock(enabled);
self
}
#[must_use]
pub fn history_retention(mut self, retention: HistoryRetention) -> Self {
self.runtime_builder = self.runtime_builder.history_retention(retention);
self
}
#[must_use]
pub fn event_buffer_size(mut self, size: NonZeroUsize) -> Self {
self.runtime_builder = self.runtime_builder.event_buffer_size(size);
self
}
pub fn build(self) -> Result<Agent, AgentBuildError> {
if !self.has_primary_provider {
return Err(AgentBuildError::MissingPrimaryProvider);
}
let Self {
runtime_builder,
loop_config,
generation_config,
profile,
..
} = self;
let runtime = runtime_builder.build()?;
Ok(Agent {
runtime,
loop_config,
generation_config,
profile,
})
}
pub async fn resume_from_store(
self,
store: FileSessionStore,
) -> Result<Agent, AgentBuildError> {
if !self.has_primary_provider {
return Err(AgentBuildError::MissingPrimaryProvider);
}
let Self {
runtime_builder,
loop_config,
generation_config,
profile,
..
} = self;
let runtime = runtime_builder.resume_from_store(store).await?;
Ok(Agent {
runtime,
loop_config,
generation_config,
profile,
})
}
}
#[derive(Clone)]
pub struct Agent {
runtime: Runtime,
loop_config: AgentLoopConfig,
generation_config: GenerationConfig,
profile: Option<Arc<dyn AgentProfile>>,
}
impl Agent {
pub(crate) fn from_runtime_parts(
runtime: Runtime,
loop_config: AgentLoopConfig,
generation_config: GenerationConfig,
profile: Option<Arc<dyn AgentProfile>>,
) -> Self {
Self {
runtime,
loop_config,
generation_config,
profile,
}
}
pub(crate) fn runtime(&self) -> &Runtime {
&self.runtime
}
pub(crate) fn into_runtime(self) -> Runtime {
self.runtime
}
#[must_use]
pub fn session_handle(&self) -> crate::coding::CodingSessionHandle {
crate::coding::CodingSessionHandle::from_runtime(self.runtime.clone())
}
#[must_use]
pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
self.runtime.active_permission_grants()
}
pub fn revoke_session_grant(
&self,
id: crate::permissions::SessionGrantId,
) -> Result<bool, crate::process::ProcessRunnerError> {
self.runtime.revoke_session_grant(id)
}
pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
self.runtime.clear_session_grants()
}
#[must_use]
pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
self.runtime.revoke_review_guidance(id)
}
#[must_use]
pub fn session_id(&self) -> &SessionId {
self.runtime.session_id()
}
#[must_use]
pub fn loop_config(&self) -> &AgentLoopConfig {
&self.loop_config
}
#[must_use]
pub fn profile(&self) -> Option<&dyn AgentProfile> {
self.profile.as_deref()
}
pub async fn run(&self, task: &str) -> Result<RunResult, AgentError> {
self.run_with_config(task, self.loop_config.clone()).await
}
pub async fn run_structured<T>(&self, task: &str) -> Result<StructuredRunResult<T>, AgentError>
where
T: DeserializeOwned + JsonSchema,
{
let config = self.structured_loop_config::<T>()?;
let result = self.run_with_config(task, config).await?;
StructuredRunResult::from_run(result)
}
pub fn stream(&self, task: &str) -> Result<AgentEventStream, AgentError> {
let run = self.stream_with_config(task, self.loop_config.clone())?;
Ok(AgentEventStream::new(run))
}
#[doc(hidden)]
pub fn stream_with_tool_handoff(&self, task: &str) -> Result<AgentRun, AgentError> {
self.stream_with_config(task, self.loop_config.clone())
}
pub fn stream_with_owned_tool_handoff(
&self,
task: &str,
) -> Result<crate::binding::OwnedAgentRun, AgentError> {
self.stream_with_tool_handoff(task)
.map(crate::binding::OwnedAgentRun::from)
}
pub fn stream_with_owned_tool_handoff_and_schema(
&self,
task: &str,
schema: ToolInputSchema,
) -> Result<crate::binding::OwnedAgentRun, AgentError> {
let contract = FinalOutputContract::new(schema)
.map_err(|source| AgentError::FinalOutputContract { source })?;
let config = self
.loop_config
.clone()
.with_final_output_contract(contract);
self.stream_with_config(task, config)
.map(crate::binding::OwnedAgentRun::from)
}
pub fn stream_structured<T>(
&self,
task: &str,
) -> Result<StructuredAgentEventStream<T>, AgentError>
where
T: DeserializeOwned + JsonSchema,
{
let config = self.structured_loop_config::<T>()?;
Ok(StructuredAgentEventStream::new(AgentEventStream::new(
self.stream_with_config(task, config)?,
)))
}
#[doc(hidden)]
pub fn stream_structured_with_tool_handoff<T>(
&self,
task: &str,
) -> Result<StructuredAgentRun<T>, AgentError>
where
T: DeserializeOwned + JsonSchema,
{
let config = self.structured_loop_config::<T>()?;
Ok(StructuredAgentRun::new(
self.stream_with_config(task, config)?,
))
}
pub fn start_interactive(&self) -> Result<InteractiveRun, AgentError> {
self.runtime
.start_interactive_agent_run(self.step_context(), self.loop_config.clone())
.map(InteractiveRun::new)
.map_err(AgentError::from)
}
pub fn start_interactive_owned(
&self,
) -> Result<crate::binding::OwnedInteractiveRun, AgentError> {
self.start_interactive()
.map(crate::binding::OwnedInteractiveRun::new)
}
pub async fn compact(
&self,
focus: Option<String>,
policy: Option<CitationCompactionPolicy>,
) -> Result<Option<CompactionOutcome>, AgentError> {
self.runtime
.compact_context(policy, focus, StepContext::default())
.await
.map_err(AgentError::from)
}
pub async fn save_session(&self) -> Result<(), AgentError> {
self.runtime.save_session().await.map_err(AgentError::from)
}
pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), AgentError> {
self.runtime
.save_session_to(store)
.await
.map_err(AgentError::from)
}
#[must_use]
pub fn trajectory_handle(&self) -> crate::observability::TrajectoryHandle {
crate::observability::TrajectoryHandle::from_runtime(self.runtime.clone())
}
#[must_use]
pub fn is_closed(&self) -> bool {
self.runtime.is_closed()
}
pub async fn close(&self) -> Result<(), AgentError> {
self.runtime.close().await.map_err(AgentError::from)
}
async fn run_with_config(
&self,
task: &str,
config: AgentLoopConfig,
) -> Result<RunResult, AgentError> {
let input = StepInput::user_text(task).map_err(AgentError::from)?;
let result = self
.runtime
.run_agent_loop(input, self.step_context(), config)
.await
.map_err(AgentError::from)?;
RunResult::from_runtime(&self.runtime, result).await
}
fn stream_with_config(
&self,
task: &str,
config: AgentLoopConfig,
) -> Result<AgentRun, AgentError> {
let input = StepInput::user_text(task).map_err(AgentError::from)?;
let stream = self
.runtime
.run_agent_loop_stream(input, self.step_context(), config)
.map_err(AgentError::from)?;
Ok(AgentRun::new(self.runtime.clone(), stream))
}
fn step_context(&self) -> StepContext {
StepContext::default().with_generation_config(self.generation_config.clone())
}
fn structured_loop_config<T>(&self) -> Result<AgentLoopConfig, AgentError>
where
T: DeserializeOwned + JsonSchema,
{
let schema = ToolInputSchema::new(schemars::schema_for!(T)).map_err(|source| {
AgentError::FinalOutputContract {
source: merry_runtime::FinalOutputContractError::Core(source),
}
})?;
let contract = FinalOutputContract::new(schema)
.map_err(|source| AgentError::FinalOutputContract { source })?
.with_output_decoder::<T>();
Ok(self
.loop_config
.clone()
.with_final_output_contract(contract))
}
}