Skip to main content

merry/agent/
core.rs

1//! High-level agent builder and session facade.
2
3use 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
29/// Builder for a high-level semantic Merry agent.
30///
31/// The builder owns only application-facing composition. The resulting
32/// [`Agent`] delegates execution and state to [`Runtime`]. A primary provider
33/// must be configured before [`Self::build`] or [`Self::resume_from_store`].
34pub 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    /// Creates a builder for a new or persisted session.
44    ///
45    /// When a [`FileSessionStore`] is configured, exclusive OS-level session
46    /// locking is enabled by default so concurrent processes cannot double-write
47    /// the same session. Call [`Self::session_lock`] with `false` to opt out.
48    #[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    /// Installs a provider-neutral configured provider component.
60    #[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    /// Installs a primary provider and model directly through Merry's provider trait.
68    #[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    /// Installs a dedicated provider component for [`RuntimeModelRole::ContextCompaction`].
76    #[must_use]
77    pub fn compaction_provider(self, provider: ConfiguredModelProvider) -> Self {
78        self.provider(provider.with_role(RuntimeModelRole::ContextCompaction))
79    }
80
81    /// Installs a dedicated compaction provider and model directly through Merry's provider trait.
82    #[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    /// Applies a low-level provider-neutral runtime profile directly.
97    ///
98    /// This is the runtime escape hatch. Use [`Self::profile`] for an
99    /// application-level profile that also owns the agent loop policy.
100    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    /// Applies an application-level agent profile and its loop policy.
106    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    /// Overrides the bounded model-turn policy used by normal runs.
120    #[must_use]
121    pub fn loop_config(mut self, config: AgentLoopConfig) -> Self {
122        self.loop_config = config;
123        self
124    }
125
126    /// Sets the number of model continuations allowed after a structured
127    /// output decoder rejects the model's final-output call.
128    #[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    /// Sets provider-neutral model generation controls.
138    #[must_use]
139    pub fn generation_config(mut self, config: GenerationConfig) -> Self {
140        self.generation_config = config;
141        self
142    }
143
144    /// Sets an explicit context-window size in tokens for this session.
145    ///
146    /// This takes precedence over provider-reported capabilities and fallback
147    /// defaults when computing context budgets and automatic compaction triggers.
148    #[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    /// Configures automatic checkpoint compaction policy for this session.
155    #[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    /// Installs an in-process Rust hook registry for lifecycle interception.
162    #[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    /// Installs a custom object-safe in-process Rust hook handler.
171    #[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    /// Declares host-bridged lifecycle hook subscriptions (used by foreign-language SDKs).
178    ///
179    /// Hook points not present in `subscriptions` are never emitted on the run stream.
180    #[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    /// Sets the stable prompt composition for this session.
193    #[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    /// Controls whether the runtime asks the model to emit brief tool-progress commentary.
200    #[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    /// Registers one typed application tool.
207    #[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    /// Registers discovered dynamic HTTP MCP meta-tools onto this agent.
216    #[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    /// Registers a tool whose invocation is handed to the embedding host.
224    ///
225    /// The facade owns bridge registration and explicit opt-in. Bindings and
226    /// other foreign-language hosts only need to provide the provider-neutral
227    /// name, description, and object input schema; runtime admission and
228    /// result persistence remain in Rust.
229    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    /// Registers an already validated bridge tool specification.
244    #[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    /// Registers one low-level runtime or host integration tool.
252    #[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    /// Registers low-level runtime or host integration tools in the supplied order.
260    #[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    /// Enables explicit host-side bridge tool execution for this agent.
273    #[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    /// Sets the store used by explicit and automatic session savepoints.
281    #[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    /// Controls whether this agent acquires an exclusive OS-level session lock
288    /// on its configured [`FileSessionStore`] (enabled by default).
289    #[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    /// Configures how compacted session history is retained in memory and on disk.
296    #[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    /// Sets the bounded runtime event buffer capacity.
303    #[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    /// Builds a new agent with the configured runtime state.
310    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    /// Resumes this agent's session from an explicit file-backed store.
331    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/// High-level semantic agent handle for one session.
356///
357/// Clones share the same runtime-owned session. The runtime admits one active
358/// run or direct mutation per session at a time.
359#[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    /// Returns a cloneable inspection and control handle for this agent's session.
391    #[must_use]
392    pub fn session_handle(&self) -> crate::coding::CodingSessionHandle {
393        crate::coding::CodingSessionHandle::from_runtime(self.runtime.clone())
394    }
395
396    /// Returns a point-in-time snapshot of active session-scoped permission
397    /// grants and user-authored review guidance notes.
398    #[must_use]
399    pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
400        self.runtime.active_permission_grants()
401    }
402
403    /// Revokes one active session-scoped permission grant by its stable ID.
404    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    /// Clears all active session-scoped permission grants immediately.
412    pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
413        self.runtime.clear_session_grants()
414    }
415
416    /// Revokes one session-scoped human review guidance note by its stable ID.
417    #[must_use]
418    pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
419        self.runtime.revoke_review_guidance(id)
420    }
421
422    /// Returns the session identity owned by this agent.
423    #[must_use]
424    pub fn session_id(&self) -> &SessionId {
425        self.runtime.session_id()
426    }
427
428    /// Returns the configured bounded loop policy.
429    #[must_use]
430    pub fn loop_config(&self) -> &AgentLoopConfig {
431        &self.loop_config
432    }
433
434    /// Returns the configured application-level profile when one was installed.
435    #[must_use]
436    pub fn profile(&self) -> Option<&dyn AgentProfile> {
437        self.profile.as_deref()
438    }
439
440    /// Runs one task to a terminal, blocked, failed, or cancelled result.
441    pub async fn run(&self, task: &str) -> Result<RunResult, AgentError> {
442        self.run_with_config(task, self.loop_config.clone()).await
443    }
444
445    /// Runs one task and decodes its runtime-recorded final output as `T`.
446    ///
447    /// `T` must produce an object-shaped JSON Schema. Merry validates that
448    /// contract before starting the model loop; scalar and array output types
449    /// return [`AgentError::FinalOutputContract`] immediately.
450    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    /// Starts an event-only stream for one non-interactive task.
460    ///
461    /// Registered Rust tools are executed by runtime and are therefore not
462    /// exposed as invocation messages. A host that deliberately owns tool
463    /// callables can use [`Self::stream_with_tool_handoff`] instead.
464    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    /// Starts the explicit host-tool handoff stream for one task.
470    ///
471    /// This is an adapter API for bindings or a Rust host that registered
472    /// low-level bridge tools. The caller must submit a complete invocation
473    /// batch before requesting the next message.
474    #[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    /// Starts an owned host-tool handoff stream for a foreign-language binding.
480    ///
481    /// The returned handle keeps the same message-first and batch-resolution
482    /// contract as [`Self::stream_with_tool_handoff`] without exposing Rust
483    /// borrow lifetimes to the binding layer.
484    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    /// Starts an owned host-tool handoff stream with a runtime-owned final
493    /// structured-output contract.
494    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    /// Starts a live stream whose terminal result is decoded as `T`.
510    ///
511    /// `T` must produce an object-shaped JSON Schema. The schema is compiled
512    /// before the provider is called, so an unsupported shape is reported at
513    /// stream construction time.
514    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    /// Starts a structured-output stream with explicit host-tool handoff.
528    #[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    /// Starts an interactive run with the same runtime event and loop contracts.
543    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    /// Starts an owned interactive run for foreign-language bindings.
551    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    /// Manually compacts session history outside an active run, optionally
559    /// emphasizing `focus` instructions and overriding the configured
560    /// [`CitationCompactionPolicy`] for this call.
561    ///
562    /// Returns `Ok(None)` when no compressible history exists before the
563    /// retained tail.
564    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    /// Saves the current resume-safe session state to its configured store.
576    pub async fn save_session(&self) -> Result<(), AgentError> {
577        self.runtime.save_session().await.map_err(AgentError::from)
578    }
579
580    /// Saves the current resume-safe session state to an explicit store.
581    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    /// Returns a read-only trajectory observability handle for this session.
589    #[must_use]
590    pub fn trajectory_handle(&self) -> crate::observability::TrajectoryHandle {
591        crate::observability::TrajectoryHandle::from_runtime(self.runtime.clone())
592    }
593
594    /// Returns whether [`Self::close`] has closed this agent session.
595    #[must_use]
596    pub fn is_closed(&self) -> bool {
597        self.runtime.is_closed()
598    }
599
600    /// Closes this agent session, releasing any held OS-level session lock and
601    /// removing an untouched empty session directory.
602    ///
603    /// Closing is idempotent once completed. Subsequent operations on the
604    /// closed agent fail with [`merry_runtime::RuntimeError::SessionClosed`].
605    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}