1use super::run::AgentRun;
4use crate::{
5 errors::{AgentBuildError, AgentError},
6 interactive::InteractiveRun,
7 profile::{AgentProfile, AgentProfileContext},
8 providers::{ConfiguredModelProvider, RuntimeBuilderProviderExt},
9 run_result::RunResult,
10 stream::{
11 AgentEventStream, StructuredAgentEventStream, StructuredAgentRun, StructuredRunResult,
12 },
13 tools::{Tool, ToolBuildError},
14};
15use merry_core::{SessionId, ToolInputSchema, ToolName, ToolSpec};
16use merry_llm::{GenerationConfig, ModelName, ModelProvider};
17use merry_runtime::{
18 AgentLoopConfig, CitationCompactionPolicy, CompactionConfig, CompactionOutcome,
19 FileSessionStore, FinalOutputContract, HistoryRetention, Runtime, RuntimeBuilder,
20 RuntimeModelRole, RuntimeProfile, StepContext, StepInput, StructuredOutputRetryPolicy,
21};
22use schemars::JsonSchema;
23use serde::de::DeserializeOwned;
24use std::{
25 num::{NonZeroU64, NonZeroUsize},
26 sync::Arc,
27};
28
29pub struct AgentBuilder {
35 runtime_builder: RuntimeBuilder,
36 loop_config: AgentLoopConfig,
37 generation_config: GenerationConfig,
38 has_primary_provider: bool,
39 profile: Option<Arc<dyn AgentProfile>>,
40}
41
42impl AgentBuilder {
43 #[must_use]
49 pub fn new(session_id: SessionId) -> Self {
50 Self {
51 runtime_builder: Runtime::builder(session_id).session_lock(true),
52 loop_config: AgentLoopConfig::default(),
53 generation_config: GenerationConfig::default(),
54 has_primary_provider: false,
55 profile: None,
56 }
57 }
58
59 #[must_use]
61 pub fn provider(mut self, provider: ConfiguredModelProvider) -> Self {
62 self.has_primary_provider |= provider.role() == RuntimeModelRole::Primary;
63 self.runtime_builder = self.runtime_builder.with_provider(provider);
64 self
65 }
66
67 #[must_use]
69 pub fn model_provider(mut self, provider: Arc<dyn ModelProvider>, model: ModelName) -> Self {
70 self.runtime_builder = self.runtime_builder.model_provider(provider, model);
71 self.has_primary_provider = true;
72 self
73 }
74
75 #[must_use]
77 pub fn compaction_provider(self, provider: ConfiguredModelProvider) -> Self {
78 self.provider(provider.with_role(RuntimeModelRole::ContextCompaction))
79 }
80
81 #[must_use]
83 pub fn compaction_model_provider(
84 mut self,
85 provider: Arc<dyn ModelProvider>,
86 model: ModelName,
87 ) -> Self {
88 self.runtime_builder = self.runtime_builder.model_provider_for_role(
89 RuntimeModelRole::ContextCompaction,
90 provider,
91 model,
92 );
93 self
94 }
95
96 pub fn runtime_profile(mut self, profile: RuntimeProfile) -> Result<Self, AgentBuildError> {
101 self.runtime_builder = self.runtime_builder.with_profile(profile)?;
102 Ok(self)
103 }
104
105 pub fn profile<P>(mut self, profile: P) -> Result<Self, AgentBuildError>
107 where
108 P: AgentProfile + 'static,
109 {
110 let mut context = AgentProfileContext::new(self.runtime_builder, self.loop_config);
111 profile.configure(&mut context)?;
112 let (runtime_builder, loop_config) = context.into_parts()?;
113 self.runtime_builder = runtime_builder;
114 self.loop_config = loop_config;
115 self.profile = Some(Arc::new(profile));
116 Ok(self)
117 }
118
119 #[must_use]
121 pub fn loop_config(mut self, config: AgentLoopConfig) -> Self {
122 self.loop_config = config;
123 self
124 }
125
126 #[must_use]
129 pub fn structured_output_retry_policy(mut self, policy: StructuredOutputRetryPolicy) -> Self {
130 self.loop_config = self
131 .loop_config
132 .clone()
133 .with_structured_output_retry_policy(policy);
134 self
135 }
136
137 #[must_use]
139 pub fn generation_config(mut self, config: GenerationConfig) -> Self {
140 self.generation_config = config;
141 self
142 }
143
144 #[must_use]
149 pub fn context_window_tokens(mut self, tokens: NonZeroU64) -> Self {
150 self.runtime_builder = self.runtime_builder.context_window_tokens(tokens);
151 self
152 }
153
154 #[must_use]
156 pub fn compaction(mut self, config: CompactionConfig) -> Self {
157 self.runtime_builder = self.runtime_builder.automatic_compaction(config);
158 self
159 }
160
161 #[must_use]
163 pub fn hooks(mut self, hooks: merry_runtime::HookRegistry) -> Self {
164 if !hooks.is_empty() {
165 self.runtime_builder = self.runtime_builder.hooks(Arc::new(hooks));
166 }
167 self
168 }
169
170 #[must_use]
172 pub fn hook_handler(mut self, handler: Arc<dyn merry_runtime::RuntimeHookHandler>) -> Self {
173 self.runtime_builder = self.runtime_builder.hooks(handler);
174 self
175 }
176
177 #[doc(hidden)]
181 #[must_use]
182 pub fn bridge_hook_subscriptions(
183 mut self,
184 subscriptions: merry_runtime::HookSubscriptions,
185 ) -> Self {
186 self.runtime_builder = self
187 .runtime_builder
188 .bridge_hook_subscriptions(subscriptions);
189 self
190 }
191
192 #[must_use]
194 pub fn prompt_profile(mut self, profile: merry_runtime::PromptProfile) -> Self {
195 self.runtime_builder = self.runtime_builder.prompt_profile(profile);
196 self
197 }
198
199 #[must_use]
201 pub fn progress_commentary(mut self, enabled: bool) -> Self {
202 self.runtime_builder = self.runtime_builder.progress_commentary(enabled);
203 self
204 }
205
206 #[must_use]
208 pub fn tool(mut self, tool: Tool) -> Self {
209 self.runtime_builder = self
210 .runtime_builder
211 .register_tool(tool.into_registered_tool());
212 self
213 }
214
215 #[cfg(feature = "mcp")]
217 #[must_use]
218 pub fn mcp_toolset(self, toolset: crate::mcp::McpToolset) -> Self {
219 let (tools, _warnings) = toolset.into_parts();
220 self.register_tools(tools)
221 }
222
223 pub fn bridge_tool(
230 self,
231 name: ToolName,
232 description: &str,
233 input_schema: ToolInputSchema,
234 ) -> Result<Self, AgentBuildError> {
235 let spec = ToolSpec::new(name, description, input_schema)
236 .map_err(ToolBuildError::from)
237 .map_err(|source| AgentBuildError::Tool { source })?;
238 Ok(self
239 .allow_bridge_tools()
240 .register_tool(merry_runtime::RegisteredTool::bridge(spec)))
241 }
242
243 #[doc(hidden)]
245 #[must_use]
246 pub fn bridge_tool_spec(self, spec: ToolSpec) -> Self {
247 self.allow_bridge_tools()
248 .register_tool(merry_runtime::RegisteredTool::bridge(spec))
249 }
250
251 #[doc(hidden)]
253 #[must_use]
254 pub fn register_tool(mut self, tool: merry_runtime::RegisteredTool) -> Self {
255 self.runtime_builder = self.runtime_builder.register_tool(tool);
256 self
257 }
258
259 #[doc(hidden)]
261 #[must_use]
262 pub fn register_tools<I>(mut self, tools: I) -> Self
263 where
264 I: IntoIterator<Item = merry_runtime::RegisteredTool>,
265 {
266 for tool in tools {
267 self = self.register_tool(tool);
268 }
269 self
270 }
271
272 #[doc(hidden)]
274 #[must_use]
275 pub fn allow_bridge_tools(mut self) -> Self {
276 self.runtime_builder = self.runtime_builder.allow_bridge_tools();
277 self
278 }
279
280 #[must_use]
282 pub fn session_store(mut self, store: FileSessionStore) -> Self {
283 self.runtime_builder = self.runtime_builder.session_store(store);
284 self
285 }
286
287 #[must_use]
290 pub fn session_lock(mut self, enabled: bool) -> Self {
291 self.runtime_builder = self.runtime_builder.session_lock(enabled);
292 self
293 }
294
295 #[must_use]
297 pub fn history_retention(mut self, retention: HistoryRetention) -> Self {
298 self.runtime_builder = self.runtime_builder.history_retention(retention);
299 self
300 }
301
302 #[must_use]
304 pub fn event_buffer_size(mut self, size: NonZeroUsize) -> Self {
305 self.runtime_builder = self.runtime_builder.event_buffer_size(size);
306 self
307 }
308
309 pub fn build(self) -> Result<Agent, AgentBuildError> {
311 if !self.has_primary_provider {
312 return Err(AgentBuildError::MissingPrimaryProvider);
313 }
314 let Self {
315 runtime_builder,
316 loop_config,
317 generation_config,
318 profile,
319 ..
320 } = self;
321 let runtime = runtime_builder.build()?;
322 Ok(Agent {
323 runtime,
324 loop_config,
325 generation_config,
326 profile,
327 })
328 }
329
330 pub async fn resume_from_store(
332 self,
333 store: FileSessionStore,
334 ) -> Result<Agent, AgentBuildError> {
335 if !self.has_primary_provider {
336 return Err(AgentBuildError::MissingPrimaryProvider);
337 }
338 let Self {
339 runtime_builder,
340 loop_config,
341 generation_config,
342 profile,
343 ..
344 } = self;
345 let runtime = runtime_builder.resume_from_store(store).await?;
346 Ok(Agent {
347 runtime,
348 loop_config,
349 generation_config,
350 profile,
351 })
352 }
353}
354
355#[derive(Clone)]
360pub struct Agent {
361 runtime: Runtime,
362 loop_config: AgentLoopConfig,
363 generation_config: GenerationConfig,
364 profile: Option<Arc<dyn AgentProfile>>,
365}
366
367impl Agent {
368 pub(crate) fn from_runtime_parts(
369 runtime: Runtime,
370 loop_config: AgentLoopConfig,
371 generation_config: GenerationConfig,
372 profile: Option<Arc<dyn AgentProfile>>,
373 ) -> Self {
374 Self {
375 runtime,
376 loop_config,
377 generation_config,
378 profile,
379 }
380 }
381
382 pub(crate) fn runtime(&self) -> &Runtime {
383 &self.runtime
384 }
385
386 pub(crate) fn into_runtime(self) -> Runtime {
387 self.runtime
388 }
389
390 #[must_use]
392 pub fn session_handle(&self) -> crate::coding::CodingSessionHandle {
393 crate::coding::CodingSessionHandle::from_runtime(self.runtime.clone())
394 }
395
396 #[must_use]
399 pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
400 self.runtime.active_permission_grants()
401 }
402
403 pub fn revoke_session_grant(
405 &self,
406 id: crate::permissions::SessionGrantId,
407 ) -> Result<bool, crate::process::ProcessRunnerError> {
408 self.runtime.revoke_session_grant(id)
409 }
410
411 pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
413 self.runtime.clear_session_grants()
414 }
415
416 #[must_use]
418 pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
419 self.runtime.revoke_review_guidance(id)
420 }
421
422 #[must_use]
424 pub fn session_id(&self) -> &SessionId {
425 self.runtime.session_id()
426 }
427
428 #[must_use]
430 pub fn loop_config(&self) -> &AgentLoopConfig {
431 &self.loop_config
432 }
433
434 #[must_use]
436 pub fn profile(&self) -> Option<&dyn AgentProfile> {
437 self.profile.as_deref()
438 }
439
440 pub async fn run(&self, task: &str) -> Result<RunResult, AgentError> {
442 self.run_with_config(task, self.loop_config.clone()).await
443 }
444
445 pub async fn run_structured<T>(&self, task: &str) -> Result<StructuredRunResult<T>, AgentError>
451 where
452 T: DeserializeOwned + JsonSchema,
453 {
454 let config = self.structured_loop_config::<T>()?;
455 let result = self.run_with_config(task, config).await?;
456 StructuredRunResult::from_run(result)
457 }
458
459 pub fn stream(&self, task: &str) -> Result<AgentEventStream, AgentError> {
465 let run = self.stream_with_config(task, self.loop_config.clone())?;
466 Ok(AgentEventStream::new(run))
467 }
468
469 #[doc(hidden)]
475 pub fn stream_with_tool_handoff(&self, task: &str) -> Result<AgentRun, AgentError> {
476 self.stream_with_config(task, self.loop_config.clone())
477 }
478
479 pub fn stream_with_owned_tool_handoff(
485 &self,
486 task: &str,
487 ) -> Result<crate::binding::OwnedAgentRun, AgentError> {
488 self.stream_with_tool_handoff(task)
489 .map(crate::binding::OwnedAgentRun::from)
490 }
491
492 pub fn stream_with_owned_tool_handoff_and_schema(
495 &self,
496 task: &str,
497 schema: ToolInputSchema,
498 ) -> Result<crate::binding::OwnedAgentRun, AgentError> {
499 let contract = FinalOutputContract::new(schema)
500 .map_err(|source| AgentError::FinalOutputContract { source })?;
501 let config = self
502 .loop_config
503 .clone()
504 .with_final_output_contract(contract);
505 self.stream_with_config(task, config)
506 .map(crate::binding::OwnedAgentRun::from)
507 }
508
509 pub fn stream_structured<T>(
515 &self,
516 task: &str,
517 ) -> Result<StructuredAgentEventStream<T>, AgentError>
518 where
519 T: DeserializeOwned + JsonSchema,
520 {
521 let config = self.structured_loop_config::<T>()?;
522 Ok(StructuredAgentEventStream::new(AgentEventStream::new(
523 self.stream_with_config(task, config)?,
524 )))
525 }
526
527 #[doc(hidden)]
529 pub fn stream_structured_with_tool_handoff<T>(
530 &self,
531 task: &str,
532 ) -> Result<StructuredAgentRun<T>, AgentError>
533 where
534 T: DeserializeOwned + JsonSchema,
535 {
536 let config = self.structured_loop_config::<T>()?;
537 Ok(StructuredAgentRun::new(
538 self.stream_with_config(task, config)?,
539 ))
540 }
541
542 pub fn start_interactive(&self) -> Result<InteractiveRun, AgentError> {
544 self.runtime
545 .start_interactive_agent_run(self.step_context(), self.loop_config.clone())
546 .map(InteractiveRun::new)
547 .map_err(AgentError::from)
548 }
549
550 pub fn start_interactive_owned(
552 &self,
553 ) -> Result<crate::binding::OwnedInteractiveRun, AgentError> {
554 self.start_interactive()
555 .map(crate::binding::OwnedInteractiveRun::new)
556 }
557
558 pub async fn compact(
565 &self,
566 focus: Option<String>,
567 policy: Option<CitationCompactionPolicy>,
568 ) -> Result<Option<CompactionOutcome>, AgentError> {
569 self.runtime
570 .compact_context(policy, focus, StepContext::default())
571 .await
572 .map_err(AgentError::from)
573 }
574
575 pub async fn save_session(&self) -> Result<(), AgentError> {
577 self.runtime.save_session().await.map_err(AgentError::from)
578 }
579
580 pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), AgentError> {
582 self.runtime
583 .save_session_to(store)
584 .await
585 .map_err(AgentError::from)
586 }
587
588 #[must_use]
590 pub fn trajectory_handle(&self) -> crate::observability::TrajectoryHandle {
591 crate::observability::TrajectoryHandle::from_runtime(self.runtime.clone())
592 }
593
594 #[must_use]
596 pub fn is_closed(&self) -> bool {
597 self.runtime.is_closed()
598 }
599
600 pub async fn close(&self) -> Result<(), AgentError> {
606 self.runtime.close().await.map_err(AgentError::from)
607 }
608
609 async fn run_with_config(
610 &self,
611 task: &str,
612 config: AgentLoopConfig,
613 ) -> Result<RunResult, AgentError> {
614 let input = StepInput::user_text(task).map_err(AgentError::from)?;
615 let result = self
616 .runtime
617 .run_agent_loop(input, self.step_context(), config)
618 .await
619 .map_err(AgentError::from)?;
620 RunResult::from_runtime(&self.runtime, result).await
621 }
622
623 fn stream_with_config(
624 &self,
625 task: &str,
626 config: AgentLoopConfig,
627 ) -> Result<AgentRun, AgentError> {
628 let input = StepInput::user_text(task).map_err(AgentError::from)?;
629 let stream = self
630 .runtime
631 .run_agent_loop_stream(input, self.step_context(), config)
632 .map_err(AgentError::from)?;
633 Ok(AgentRun::new(self.runtime.clone(), stream))
634 }
635
636 fn step_context(&self) -> StepContext {
637 StepContext::default().with_generation_config(self.generation_config.clone())
638 }
639
640 fn structured_loop_config<T>(&self) -> Result<AgentLoopConfig, AgentError>
641 where
642 T: DeserializeOwned + JsonSchema,
643 {
644 let schema = ToolInputSchema::new(schemars::schema_for!(T)).map_err(|source| {
645 AgentError::FinalOutputContract {
646 source: merry_runtime::FinalOutputContractError::Core(source),
647 }
648 })?;
649 let contract = FinalOutputContract::new(schema)
650 .map_err(|source| AgentError::FinalOutputContract { source })?
651 .with_output_decoder::<T>();
652 Ok(self
653 .loop_config
654 .clone()
655 .with_final_output_contract(contract))
656 }
657}