merry 0.1.3

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
//! High-level agent builder and session facade.

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,
};

/// Builder for a high-level semantic Merry agent.
///
/// The builder owns only application-facing composition. The resulting
/// [`Agent`] delegates execution and state to [`Runtime`]. A primary provider
/// must be configured before [`Self::build`] or [`Self::resume_from_store`].
pub struct AgentBuilder {
    runtime_builder: RuntimeBuilder,
    loop_config: AgentLoopConfig,
    generation_config: GenerationConfig,
    has_primary_provider: bool,
    profile: Option<Arc<dyn AgentProfile>>,
}

impl AgentBuilder {
    /// Creates a builder for a new or persisted session.
    ///
    /// When a [`FileSessionStore`] is configured, exclusive OS-level session
    /// locking is enabled by default so concurrent processes cannot double-write
    /// the same session. Call [`Self::session_lock`] with `false` to opt out.
    #[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,
        }
    }

    /// Installs a provider-neutral configured provider component.
    #[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
    }

    /// Installs a primary provider and model directly through Merry's provider trait.
    #[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
    }

    /// Installs a dedicated provider component for [`RuntimeModelRole::ContextCompaction`].
    #[must_use]
    pub fn compaction_provider(self, provider: ConfiguredModelProvider) -> Self {
        self.provider(provider.with_role(RuntimeModelRole::ContextCompaction))
    }

    /// Installs a dedicated compaction provider and model directly through Merry's provider trait.
    #[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
    }

    /// Applies a low-level provider-neutral runtime profile directly.
    ///
    /// This is the runtime escape hatch. Use [`Self::profile`] for an
    /// application-level profile that also owns the agent loop policy.
    pub fn runtime_profile(mut self, profile: RuntimeProfile) -> Result<Self, AgentBuildError> {
        self.runtime_builder = self.runtime_builder.with_profile(profile)?;
        Ok(self)
    }

    /// Applies an application-level agent profile and its loop policy.
    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)
    }

    /// Overrides the bounded model-turn policy used by normal runs.
    #[must_use]
    pub fn loop_config(mut self, config: AgentLoopConfig) -> Self {
        self.loop_config = config;
        self
    }

    /// Sets the number of model continuations allowed after a structured
    /// output decoder rejects the model's final-output call.
    #[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
    }

    /// Sets provider-neutral model generation controls.
    #[must_use]
    pub fn generation_config(mut self, config: GenerationConfig) -> Self {
        self.generation_config = config;
        self
    }

    /// Sets an explicit context-window size in tokens for this session.
    ///
    /// This takes precedence over provider-reported capabilities and fallback
    /// defaults when computing context budgets and automatic compaction triggers.
    #[must_use]
    pub fn context_window_tokens(mut self, tokens: NonZeroU64) -> Self {
        self.runtime_builder = self.runtime_builder.context_window_tokens(tokens);
        self
    }

    /// Configures automatic checkpoint compaction policy for this session.
    #[must_use]
    pub fn compaction(mut self, config: CompactionConfig) -> Self {
        self.runtime_builder = self.runtime_builder.automatic_compaction(config);
        self
    }

    /// Installs an in-process Rust hook registry for lifecycle interception.
    #[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
    }

    /// Installs a custom object-safe in-process Rust hook handler.
    #[must_use]
    pub fn hook_handler(mut self, handler: Arc<dyn merry_runtime::RuntimeHookHandler>) -> Self {
        self.runtime_builder = self.runtime_builder.hooks(handler);
        self
    }

    /// Declares host-bridged lifecycle hook subscriptions (used by foreign-language SDKs).
    ///
    /// Hook points not present in `subscriptions` are never emitted on the run stream.
    #[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
    }

    /// Sets the stable prompt composition for this session.
    #[must_use]
    pub fn prompt_profile(mut self, profile: merry_runtime::PromptProfile) -> Self {
        self.runtime_builder = self.runtime_builder.prompt_profile(profile);
        self
    }

    /// Controls whether the runtime asks the model to emit brief tool-progress commentary.
    #[must_use]
    pub fn progress_commentary(mut self, enabled: bool) -> Self {
        self.runtime_builder = self.runtime_builder.progress_commentary(enabled);
        self
    }

    /// Registers one typed application tool.
    #[must_use]
    pub fn tool(mut self, tool: Tool) -> Self {
        self.runtime_builder = self
            .runtime_builder
            .register_tool(tool.into_registered_tool());
        self
    }

    /// Registers discovered dynamic HTTP MCP meta-tools onto this agent.
    #[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)
    }

    /// Registers a tool whose invocation is handed to the embedding host.
    ///
    /// The facade owns bridge registration and explicit opt-in. Bindings and
    /// other foreign-language hosts only need to provide the provider-neutral
    /// name, description, and object input schema; runtime admission and
    /// result persistence remain in Rust.
    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)))
    }

    /// Registers an already validated bridge tool specification.
    #[doc(hidden)]
    #[must_use]
    pub fn bridge_tool_spec(self, spec: ToolSpec) -> Self {
        self.allow_bridge_tools()
            .register_tool(merry_runtime::RegisteredTool::bridge(spec))
    }

    /// Registers one low-level runtime or host integration tool.
    #[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
    }

    /// Registers low-level runtime or host integration tools in the supplied order.
    #[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
    }

    /// Enables explicit host-side bridge tool execution for this agent.
    #[doc(hidden)]
    #[must_use]
    pub fn allow_bridge_tools(mut self) -> Self {
        self.runtime_builder = self.runtime_builder.allow_bridge_tools();
        self
    }

    /// Sets the store used by explicit and automatic session savepoints.
    #[must_use]
    pub fn session_store(mut self, store: FileSessionStore) -> Self {
        self.runtime_builder = self.runtime_builder.session_store(store);
        self
    }

    /// Controls whether this agent acquires an exclusive OS-level session lock
    /// on its configured [`FileSessionStore`] (enabled by default).
    #[must_use]
    pub fn session_lock(mut self, enabled: bool) -> Self {
        self.runtime_builder = self.runtime_builder.session_lock(enabled);
        self
    }

    /// Configures how compacted session history is retained in memory and on disk.
    #[must_use]
    pub fn history_retention(mut self, retention: HistoryRetention) -> Self {
        self.runtime_builder = self.runtime_builder.history_retention(retention);
        self
    }

    /// Sets the bounded runtime event buffer capacity.
    #[must_use]
    pub fn event_buffer_size(mut self, size: NonZeroUsize) -> Self {
        self.runtime_builder = self.runtime_builder.event_buffer_size(size);
        self
    }

    /// Builds a new agent with the configured runtime state.
    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,
        })
    }

    /// Resumes this agent's session from an explicit file-backed store.
    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,
        })
    }
}

/// High-level semantic agent handle for one session.
///
/// Clones share the same runtime-owned session. The runtime admits one active
/// run or direct mutation per session at a time.
#[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
    }

    /// Returns a cloneable inspection and control handle for this agent's session.
    #[must_use]
    pub fn session_handle(&self) -> crate::coding::CodingSessionHandle {
        crate::coding::CodingSessionHandle::from_runtime(self.runtime.clone())
    }

    /// Returns a point-in-time snapshot of active session-scoped permission
    /// grants and user-authored review guidance notes.
    #[must_use]
    pub fn active_permission_grants(&self) -> crate::permissions::ActivePermissionGrants {
        self.runtime.active_permission_grants()
    }

    /// Revokes one active session-scoped permission grant by its stable ID.
    pub fn revoke_session_grant(
        &self,
        id: crate::permissions::SessionGrantId,
    ) -> Result<bool, crate::process::ProcessRunnerError> {
        self.runtime.revoke_session_grant(id)
    }

    /// Clears all active session-scoped permission grants immediately.
    pub fn clear_session_grants(&self) -> Result<(), crate::process::ProcessRunnerError> {
        self.runtime.clear_session_grants()
    }

    /// Revokes one session-scoped human review guidance note by its stable ID.
    #[must_use]
    pub fn revoke_review_guidance(&self, id: crate::permissions::ReviewGuidanceId) -> bool {
        self.runtime.revoke_review_guidance(id)
    }

    /// Returns the session identity owned by this agent.
    #[must_use]
    pub fn session_id(&self) -> &SessionId {
        self.runtime.session_id()
    }

    /// Returns the configured bounded loop policy.
    #[must_use]
    pub fn loop_config(&self) -> &AgentLoopConfig {
        &self.loop_config
    }

    /// Returns the configured application-level profile when one was installed.
    #[must_use]
    pub fn profile(&self) -> Option<&dyn AgentProfile> {
        self.profile.as_deref()
    }

    /// Runs one task to a terminal, blocked, failed, or cancelled result.
    pub async fn run(&self, task: &str) -> Result<RunResult, AgentError> {
        self.run_with_config(task, self.loop_config.clone()).await
    }

    /// Runs one task and decodes its runtime-recorded final output as `T`.
    ///
    /// `T` must produce an object-shaped JSON Schema. Merry validates that
    /// contract before starting the model loop; scalar and array output types
    /// return [`AgentError::FinalOutputContract`] immediately.
    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)
    }

    /// Starts an event-only stream for one non-interactive task.
    ///
    /// Registered Rust tools are executed by runtime and are therefore not
    /// exposed as invocation messages. A host that deliberately owns tool
    /// callables can use [`Self::stream_with_tool_handoff`] instead.
    pub fn stream(&self, task: &str) -> Result<AgentEventStream, AgentError> {
        let run = self.stream_with_config(task, self.loop_config.clone())?;
        Ok(AgentEventStream::new(run))
    }

    /// Starts the explicit host-tool handoff stream for one task.
    ///
    /// This is an adapter API for bindings or a Rust host that registered
    /// low-level bridge tools. The caller must submit a complete invocation
    /// batch before requesting the next message.
    #[doc(hidden)]
    pub fn stream_with_tool_handoff(&self, task: &str) -> Result<AgentRun, AgentError> {
        self.stream_with_config(task, self.loop_config.clone())
    }

    /// Starts an owned host-tool handoff stream for a foreign-language binding.
    ///
    /// The returned handle keeps the same message-first and batch-resolution
    /// contract as [`Self::stream_with_tool_handoff`] without exposing Rust
    /// borrow lifetimes to the binding layer.
    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)
    }

    /// Starts an owned host-tool handoff stream with a runtime-owned final
    /// structured-output contract.
    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)
    }

    /// Starts a live stream whose terminal result is decoded as `T`.
    ///
    /// `T` must produce an object-shaped JSON Schema. The schema is compiled
    /// before the provider is called, so an unsupported shape is reported at
    /// stream construction time.
    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)?,
        )))
    }

    /// Starts a structured-output stream with explicit host-tool handoff.
    #[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)?,
        ))
    }

    /// Starts an interactive run with the same runtime event and loop contracts.
    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)
    }

    /// Starts an owned interactive run for foreign-language bindings.
    pub fn start_interactive_owned(
        &self,
    ) -> Result<crate::binding::OwnedInteractiveRun, AgentError> {
        self.start_interactive()
            .map(crate::binding::OwnedInteractiveRun::new)
    }

    /// Manually compacts session history outside an active run, optionally
    /// emphasizing `focus` instructions and overriding the configured
    /// [`CitationCompactionPolicy`] for this call.
    ///
    /// Returns `Ok(None)` when no compressible history exists before the
    /// retained tail.
    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)
    }

    /// Saves the current resume-safe session state to its configured store.
    pub async fn save_session(&self) -> Result<(), AgentError> {
        self.runtime.save_session().await.map_err(AgentError::from)
    }

    /// Saves the current resume-safe session state to an explicit store.
    pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), AgentError> {
        self.runtime
            .save_session_to(store)
            .await
            .map_err(AgentError::from)
    }

    /// Returns a read-only trajectory observability handle for this session.
    #[must_use]
    pub fn trajectory_handle(&self) -> crate::observability::TrajectoryHandle {
        crate::observability::TrajectoryHandle::from_runtime(self.runtime.clone())
    }

    /// Returns whether [`Self::close`] has closed this agent session.
    #[must_use]
    pub fn is_closed(&self) -> bool {
        self.runtime.is_closed()
    }

    /// Closes this agent session, releasing any held OS-level session lock and
    /// removing an untouched empty session directory.
    ///
    /// Closing is idempotent once completed. Subsequent operations on the
    /// closed agent fail with [`merry_runtime::RuntimeError::SessionClosed`].
    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))
    }
}