Skip to main content

merry_runtime/
runtime.rs

1//! Runtime builder and step execution skeleton.
2//!
3//! [`Runtime`] is the MVP facade for session-owned state. Step execution and
4//! direct mutation APIs admit one active operation at a time, record durable
5//! session state before returning observable events where applicable, and keep
6//! provider wire details behind the `merry-llm` provider boundary.
7
8use crate::{
9    CitationCompactionInput, CitationCompactionPolicy, CompactedCheckpointSummary, CompactionError,
10    CompactionOutcome, FileSessionStore, RuntimeCapabilities, RuntimeError,
11    events::{
12        ActiveStepPermit, RuntimeEventProjector, RuntimeEventStream, RuntimeJournalEventStream,
13    },
14    model_config::ModelProviderConfig,
15    step::{StepContext, StepInput},
16    subagent::{SubagentActivityReceiver, SubagentManager},
17    tool::ToolExecutionContext,
18};
19use merry_core::{
20    PendingToolCall, QueuedInputView, RuntimeEvent, RuntimeJournalEvent, SessionId, ToolCallId,
21};
22use merry_llm::{ModelName, ModelProvider, ModelRetryPolicy};
23use std::{
24    num::NonZeroU64,
25    sync::{Arc, atomic::Ordering},
26};
27use tokio::sync::Notify;
28use tokio_util::sync::CancellationToken;
29
30mod admission;
31mod auto_compaction;
32mod builder;
33mod config;
34mod diagnostics;
35mod journal_emission;
36mod journal_persistence;
37mod memory_activation;
38mod memory_maintenance;
39mod model_output;
40mod model_turn_lifecycle;
41mod output_rate;
42mod permission_execution;
43mod plan_tool_execution;
44mod process_execution;
45mod provider_request;
46mod provider_step;
47mod provider_stream;
48mod session_access;
49mod session_topic;
50pub(crate) use self::session_topic::TopicTask;
51mod state;
52mod step;
53mod tool_batch;
54mod tool_execution;
55
56use self::auto_compaction::{
57    compact_context_once_inner, compaction_input_for_policy,
58    install_summary_compaction_transactionally,
59};
60pub use self::builder::RuntimeBuilder;
61pub use self::config::{ArchiveConfig, CompactionConfig, HistoryRetention};
62use self::diagnostics::{
63    DIAGNOSTIC_TOOL_ACTION_POLICY_DENIED, DIAGNOSTIC_TOOL_CALL_RESULT_REQUIRED,
64    DIAGNOSTIC_TOOL_NOT_REGISTERED, TOOL_ACTION_POLICY_DENIED_MESSAGE, diagnostic_from_text,
65    runtime_error_message,
66};
67#[cfg(test)]
68use self::journal_emission::send_cancelled_event;
69#[cfg(test)]
70use self::memory_activation::memory_activation_seed_from_step_input;
71#[cfg(test)]
72use self::provider_request::{request_context_budget, step_usage_context_snapshot};
73use self::state::RuntimeInner;
74#[cfg(test)]
75use self::tool_execution::admit_action_to_generic_executor;
76
77/// Merry runtime handle for one session.
78///
79/// A cloned handle points at the same session-owned state. [`Runtime::step`]
80/// and direct mutation APIs such as [`Runtime::record_artifact`],
81/// [`Runtime::record_context_entry`], [`Runtime::submit_tool_result`], and
82/// [`Runtime::execute_tool_call`] acquire the active-step permit.
83#[derive(Clone)]
84pub struct Runtime {
85    inner: Arc<RuntimeInner>,
86}
87
88impl Runtime {
89    /// Creates a runtime builder for the provided session.
90    ///
91    /// The session id defines the ownership boundary for transcript state,
92    /// context, pending tool calls, and emitted runtime events.
93    #[must_use]
94    pub fn builder(session_id: SessionId) -> RuntimeBuilder {
95        RuntimeBuilder::new(session_id)
96    }
97
98    /// Subscribes to the latest UI-only activity snapshots for managed subagents.
99    #[must_use]
100    pub fn subscribe_subagent_activity(&self) -> SubagentActivityReceiver {
101        self.inner.subagents.activity_hub.subscribe()
102    }
103
104    /// Resumes a session from the default XDG state store.
105    pub async fn resume(session_id: SessionId) -> Result<Self, RuntimeError> {
106        let store = FileSessionStore::default_store()?;
107        Self::builder(session_id).resume_from_store(store).await
108    }
109
110    /// Starts a runtime step and returns its event stream.
111    ///
112    /// Only one step or direct mutation may own the runtime at a time. The
113    /// step producer owns the initial active-step permit. Dropping the returned
114    /// [`RuntimeJournalEventStream`] cancels and aborts the producer; the runtime
115    /// becomes available after the producer and any in-flight persistence
116    /// transaction have dropped their permit handles.
117    ///
118    /// All events emitted by the step are provider-neutral [`RuntimeJournalEvent`]
119    /// values. The runtime records session transcript and pending-tool state
120    /// before the corresponding event becomes observable.
121    ///
122    /// Cancellation records a cancelled event when the producer reaches a
123    /// cancellation checkpoint. Pending tool calls remain pending unless a
124    /// durable result has already been recorded. If compaction persistence is
125    /// already in flight, its transaction keeps the active-step permit until
126    /// the staged state is discarded or durably installed.
127    pub fn step(
128        &self,
129        input: StepInput,
130        context: StepContext,
131    ) -> Result<RuntimeJournalEventStream, RuntimeError> {
132        let active_permit = self.acquire_active_step_permit()?;
133
134        self.step_with_active_permit(input, context, active_permit)
135    }
136
137    /// Starts a runtime step and returns the raw ordered journal stream.
138    ///
139    /// This is the explicit low-level alias for [`Runtime::step`]. Runtime
140    /// internals, debugging tools, and replay inspection should use this API
141    /// when they need exact journal payloads rather than SDK-facing projection.
142    pub fn journal_stream(
143        &self,
144        input: StepInput,
145        context: StepContext,
146    ) -> Result<RuntimeJournalEventStream, RuntimeError> {
147        self.step(input, context)
148    }
149
150    /// Starts a runtime step and returns SDK-facing public events.
151    ///
152    /// Public events are projected from the internal journal after the
153    /// corresponding session state is recorded. They expose assistant text and
154    /// tool activity directly while omitting internal bridge handoff details.
155    pub fn stream(
156        &self,
157        input: StepInput,
158        context: StepContext,
159    ) -> Result<RuntimeEventStream, RuntimeError> {
160        let journal_stream = self.step(input, context)?;
161        Ok(RuntimeEventStream::new(
162            journal_stream,
163            self.clone(),
164            self.inner.event_buffer_size.get(),
165        ))
166    }
167
168    /// Projects raw ordered journal events into SDK-facing public events.
169    ///
170    /// This helper is read-only and is intended for SDK bindings that need to
171    /// return public events for a completed run while preserving raw journal
172    /// evidence inside Rust runtime results.
173    pub async fn project_journal_events(
174        &self,
175        events: &[RuntimeJournalEvent],
176    ) -> Result<Vec<RuntimeEvent>, RuntimeError> {
177        let mut projector = RuntimeEventProjector::new();
178        let mut projected = Vec::new();
179        for event in events {
180            if let Some(event) = projector.project(event.clone(), self).await? {
181                projected.push(event);
182            }
183        }
184        Ok(projected)
185    }
186
187    /// Returns the latest authoritative session usage snapshot.
188    pub async fn usage(&self) -> Option<merry_core::SessionUsage> {
189        let session = self.inner.session.lock().await;
190        session.usage()
191    }
192
193    pub(crate) fn acquire_active_step_permit(&self) -> Result<ActiveStepPermit, RuntimeError> {
194        if self.inner.closed.load(Ordering::Acquire) {
195            return Err(RuntimeError::SessionClosed {
196                session_id: self.inner.session_id.clone(),
197            });
198        }
199        let permit =
200            ActiveStepPermit::acquire(Arc::clone(&self.inner.active_step)).ok_or_else(|| {
201                RuntimeError::StepAlreadyActive {
202                    session_id: self.inner.session_id.clone(),
203                }
204            })?;
205        // Re-check after acquiring the permit to close any race with `Runtime::close`.
206        if self.inner.closed.load(Ordering::Acquire) {
207            return Err(RuntimeError::SessionClosed {
208                session_id: self.inner.session_id.clone(),
209            });
210        }
211        Ok(permit)
212    }
213
214    pub fn session_id(&self) -> &SessionId {
215        &self.inner.session_id
216    }
217
218    /// Returns the model-written session topic, waiting briefly for the
219    /// first-turn side call when it is still running.
220    pub async fn session_topic(&self) -> Option<String> {
221        self::session_topic::topic(&self.inner).await
222    }
223
224    /// Returns the already-recorded session topic without waiting on an
225    /// in-flight background topic generation call.
226    pub async fn cached_session_topic(&self) -> Option<String> {
227        self.inner.session.lock().await.topic().map(str::to_owned)
228    }
229
230    #[cfg(test)]
231    pub(crate) fn session_for_tests(
232        &self,
233    ) -> &Arc<tokio::sync::Mutex<crate::session::SessionState>> {
234        &self.inner.session
235    }
236
237    pub(crate) fn schedule_memory_maintenance(&self) {
238        self::memory_maintenance::schedule(&self.inner);
239    }
240
241    pub(crate) fn record_queued_input_accepted(&self, inputs: &[QueuedInputView]) {
242        self.inner.trajectory.record_queued_input_accepted(inputs);
243    }
244
245    pub(crate) fn close_trajectory(&self) {
246        self.inner.trajectory.close();
247    }
248
249    /// Saves the current resume-safe session state to the provided store.
250    ///
251    /// The in-memory cursor tracks the runtime's configured store. Another
252    /// directory is written as a complete journal when it has no header, and
253    /// that write does not move the cursor.
254    pub async fn save_session_to(&self, store: FileSessionStore) -> Result<(), RuntimeError> {
255        let active_permit = self.acquire_active_step_permit()?;
256        self.save_session_to_with_active_permit(store, &active_permit)
257            .await
258    }
259
260    pub(crate) async fn save_session_to_with_active_permit(
261        &self,
262        store: FileSessionStore,
263        _active_permit: &ActiveStepPermit,
264    ) -> Result<(), RuntimeError> {
265        let has_header =
266            crate::session::journal_destination_has_header(&store, &self.inner.session_id).await?;
267        let (bundle, tracked, adopt_destination) = {
268            let session = self.inner.session.lock().await;
269            let tracked_dir = self
270                .inner
271                .persistence
272                .store
273                .as_ref()
274                .map(FileSessionStore::sessions_dir)
275                .or_else(|| session.tracked_store_dir());
276            let adopt_destination = tracked_dir.is_none();
277            let tracked = adopt_destination || tracked_dir == Some(store.sessions_dir());
278            let cursor = session.cursor_for_destination(tracked, has_header);
279            let bundle = session.persistable_bundle_with_cursor(&cursor)?;
280            (bundle, tracked, adopt_destination)
281        };
282        let cursor = bundle.cursor.clone();
283        if !bundle.document_bytes.is_empty() {
284            store.write_bundle(bundle).await?;
285        }
286        if tracked {
287            let mut session = self.inner.session.lock().await;
288            if adopt_destination {
289                session.set_tracked_store_dir(store.sessions_dir().to_path_buf());
290            }
291            session.adopt_journal_cursor(cursor);
292        }
293        Ok(())
294    }
295
296    /// Saves the current resume-safe session state to the configured store.
297    pub async fn save_session(&self) -> Result<(), RuntimeError> {
298        let store = match self.inner.persistence.store.clone() {
299            Some(store) => store,
300            None => FileSessionStore::default_store()?,
301        };
302        self.save_session_to(store).await
303    }
304
305    /// Lists background processes retained by this session.
306    #[must_use]
307    pub fn background_processes(&self) -> Vec<crate::BackgroundProcessSummary> {
308        self.inner
309            .background_control
310            .as_ref()
311            .map(|control| control.list())
312            .unwrap_or_default()
313    }
314
315    /// Reads captured output for one retained background process.
316    pub fn read_background_process(
317        &self,
318        id: &crate::BackgroundProcessId,
319    ) -> Result<crate::BackgroundProcessOutput, crate::BackgroundProcessLookupError> {
320        match &self.inner.background_control {
321            Some(control) => control.read(id),
322            None => Err(crate::BackgroundProcessLookupError::new(
323                id.clone(),
324                Vec::new(),
325            )),
326        }
327    }
328
329    /// Stops one retained background process group.
330    pub fn stop_background_process(
331        &self,
332        id: &crate::BackgroundProcessId,
333    ) -> Result<crate::BackgroundProcessStop, crate::BackgroundProcessLookupError> {
334        match &self.inner.background_control {
335            Some(control) => control.stop(id),
336            None => Err(crate::BackgroundProcessLookupError::new(
337                id.clone(),
338                Vec::new(),
339            )),
340        }
341    }
342
343    /// Returns a compact snapshot of managed subagent statuses when configured.
344    pub async fn subagent_snapshot(&self) -> Option<Vec<crate::SubagentStatusView>> {
345        match &self.inner.subagents.manager {
346            Some(manager) => Some(manager.snapshot().await),
347            None => None,
348        }
349    }
350
351    /// Opens a lazy transcript & live event inspection session for one subagent.
352    pub async fn inspect_subagent(
353        &self,
354        agent_id: &merry_core::SubagentId,
355    ) -> Option<crate::SubagentInspectSession> {
356        match &self.inner.subagents.manager {
357            Some(manager) => manager.inspect(agent_id).await,
358            None => None,
359        }
360    }
361
362    /// Sends a follow-up user message directly to one managed subagent.
363    pub async fn send_subagent_message(
364        &self,
365        agent_id: &merry_core::SubagentId,
366        message: String,
367    ) -> Result<(), RuntimeError> {
368        match &self.inner.subagents.manager {
369            Some(manager) => manager.send_message(agent_id, message).await,
370            None => Err(RuntimeError::InvalidSubagentSelection {
371                operation: "send_subagent_message",
372            }),
373        }
374    }
375
376    /// Cancels one managed subagent.
377    pub async fn cancel_subagent(
378        &self,
379        agent_id: &merry_core::SubagentId,
380    ) -> Result<crate::WaitSubagentsOutput, RuntimeError> {
381        match &self.inner.subagents.manager {
382            Some(manager) => manager.cancel(std::slice::from_ref(agent_id)).await,
383            None => Err(RuntimeError::InvalidSubagentSelection {
384                operation: "cancel_subagents",
385            }),
386        }
387    }
388
389    pub(crate) fn subscribe_subagent_events(
390        &self,
391    ) -> tokio::sync::broadcast::Receiver<RuntimeJournalEvent> {
392        self.inner.subagents.event_sink.subscribe()
393    }
394
395    pub(crate) async fn flush_attached_session_store(&self) -> Result<(), RuntimeError> {
396        let Some(store) = self.inner.persistence.store.clone() else {
397            return Ok(());
398        };
399        let prepared = {
400            let session = self.inner.session.lock().await;
401            session.persistable_bundle_if_resume_safe()?
402        };
403        if let Some(bundle) = prepared {
404            let cursor = bundle.cursor.clone();
405            store.write_bundle(bundle).await?;
406            self.inner.session.lock().await.adopt_journal_cursor(cursor);
407        }
408        Ok(())
409    }
410
411    pub(crate) fn shutdown_background_processes(&self) {
412        let Some(control) = self.inner.background_control.as_ref() else {
413            return;
414        };
415        for process in control.list() {
416            if matches!(
417                process.state(),
418                crate::BackgroundProcessState::Running { .. }
419            ) {
420                let _ = control.stop(process.id());
421            }
422        }
423    }
424
425    pub(crate) fn subagent_completion_notify(&self) -> Option<Arc<Notify>> {
426        self.inner
427            .subagents
428            .manager
429            .as_ref()
430            .map(SubagentManager::completion_notify)
431    }
432
433    pub(crate) async fn take_subagent_completion_notifications(
434        &self,
435    ) -> Vec<crate::SubagentStatusView> {
436        match &self.inner.subagents.manager {
437            Some(manager) => manager.take_completion_notifications().await,
438            None => Vec::new(),
439        }
440    }
441
442    pub(crate) async fn has_subagent_completion_notifications(&self) -> bool {
443        match &self.inner.subagents.manager {
444            Some(manager) => manager.has_completion_notifications().await,
445            None => false,
446        }
447    }
448
449    pub(crate) async fn has_active_subagents(&self) -> bool {
450        match &self.inner.subagents.manager {
451            Some(manager) => manager.has_active_agents().await,
452            None => false,
453        }
454    }
455
456    /// Cancels all live subagents owned by this runtime and awaits their task handles.
457    pub async fn shutdown_subagents(&self) {
458        if let Some(manager) = &self.inner.subagents.manager {
459            manager.shutdown().await;
460        }
461    }
462
463    /// Returns the current Plan Mode and session plan list snapshot.
464    pub async fn plan_session_snapshot(&self) -> merry_core::PlanSessionSnapshot {
465        self.inner.session.lock().await.plan_state().snapshot()
466    }
467
468    /// Returns all Markdown plan documents authored in this session.
469    pub async fn plan_documents(&self) -> Vec<merry_core::PlanDocument> {
470        self.inner.session.lock().await.plan_state().documents()
471    }
472
473    /// Returns the current checklist items for this session.
474    pub async fn todo_items(&self) -> Vec<merry_core::TodoItem> {
475        self.inner.session.lock().await.todo_list().items().to_vec()
476    }
477
478    /// Returns whether a submitted plan is currently awaiting user review.
479    pub async fn awaiting_plan_approval(&self) -> bool {
480        self.inner
481            .session
482            .lock()
483            .await
484            .plan_state()
485            .awaiting_approval_plan_id()
486            .is_some()
487    }
488
489    /// Toggles Plan Mode from an explicit user control.
490    ///
491    /// Returns any durable journal event emitted if the mode changed.
492    pub async fn set_plan_mode(
493        &self,
494        enabled: bool,
495        turn_in_flight: bool,
496    ) -> Result<Option<RuntimeJournalEvent>, RuntimeError> {
497        let event = {
498            let mut session = self.inner.session.lock().await;
499            session
500                .plan_state_mut()
501                .set_mode_from_user(enabled, turn_in_flight)
502                .map(|mode| {
503                    session
504                        .record_event(merry_core::RuntimeJournalPayload::PlanModeChanged { mode })
505                })
506        };
507        if event.is_some() {
508            self.persist_resume_safe_snapshot_if_store_attached()
509                .await?;
510        }
511        Ok(event)
512    }
513
514    /// Activates `Pending` Plan Mode when a user prompt begins.
515    pub(crate) async fn activate_pending_plan_mode_for_prompt(
516        &self,
517    ) -> Option<RuntimeJournalEvent> {
518        let mut session = self.inner.session.lock().await;
519        session
520            .plan_state_mut()
521            .activate_on_user_prompt()
522            .map(|mode| {
523                session.record_event(merry_core::RuntimeJournalPayload::PlanModeChanged { mode })
524            })
525    }
526
527    /// Finalizes `ExitPending -> Inactive` when an in-flight turn completes.
528    pub(crate) async fn complete_deferred_plan_mode_exit(&self) -> Option<RuntimeJournalEvent> {
529        let mut session = self.inner.session.lock().await;
530        session
531            .plan_state_mut()
532            .complete_deferred_exit()
533            .map(|mode| {
534                session.record_event(merry_core::RuntimeJournalPayload::PlanModeChanged { mode })
535            })
536    }
537
538    /// Approves a submitted plan, exits Plan Mode, and persists the updated state.
539    pub async fn approve_plan(
540        &self,
541        plan_id: merry_core::PlanId,
542        note: Option<String>,
543    ) -> Result<(merry_core::PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError> {
544        let now_ms = crate::plan::unix_time_ms();
545        let (doc, events) = {
546            let mut session = self.inner.session.lock().await;
547            let (doc, decision) = session
548                .plan_state_mut()
549                .approve_plan(&plan_id, note, now_ms)?;
550            let reviewed = session.record_event(merry_core::RuntimeJournalPayload::PlanReviewed {
551                plan_id: doc.summary.id.clone(),
552                decision,
553            });
554            let mode_changed =
555                session.record_event(merry_core::RuntimeJournalPayload::PlanModeChanged {
556                    mode: merry_core::PlanModeState::Inactive,
557                });
558            (doc, vec![reviewed, mode_changed])
559        };
560        self.persist_resume_safe_snapshot_if_store_attached()
561            .await?;
562        Ok((doc, events))
563    }
564
565    /// Requests changes on a submitted plan, keeps Plan Mode active, and persists state.
566    pub async fn request_plan_changes(
567        &self,
568        plan_id: merry_core::PlanId,
569        feedback: String,
570    ) -> Result<(merry_core::PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError> {
571        let now_ms = crate::plan::unix_time_ms();
572        let (doc, events) = {
573            let mut session = self.inner.session.lock().await;
574            let (doc, decision) = session
575                .plan_state_mut()
576                .request_changes(&plan_id, feedback, now_ms)?;
577            let reviewed = session.record_event(merry_core::RuntimeJournalPayload::PlanReviewed {
578                plan_id: doc.summary.id.clone(),
579                decision,
580            });
581            let mode_changed =
582                session.record_event(merry_core::RuntimeJournalPayload::PlanModeChanged {
583                    mode: merry_core::PlanModeState::Active,
584                });
585            (doc, vec![reviewed, mode_changed])
586        };
587        self.persist_resume_safe_snapshot_if_store_attached()
588            .await?;
589        Ok((doc, events))
590    }
591
592    /// Abandons a submitted plan and exits Plan Mode without starting implementation.
593    pub async fn abandon_plan(
594        &self,
595        plan_id: merry_core::PlanId,
596    ) -> Result<(merry_core::PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError> {
597        let now_ms = crate::plan::unix_time_ms();
598        let (doc, events) = {
599            let mut session = self.inner.session.lock().await;
600            let (doc, decision) = session.plan_state_mut().abandon_plan(&plan_id, now_ms)?;
601            let reviewed = session.record_event(merry_core::RuntimeJournalPayload::PlanReviewed {
602                plan_id: doc.summary.id.clone(),
603                decision,
604            });
605            let mode_changed =
606                session.record_event(merry_core::RuntimeJournalPayload::PlanModeChanged {
607                    mode: merry_core::PlanModeState::Inactive,
608                });
609            (doc, vec![reviewed, mode_changed])
610        };
611        self.persist_resume_safe_snapshot_if_store_attached()
612            .await?;
613        Ok((doc, events))
614    }
615
616    async fn persist_resume_safe_snapshot_if_store_attached(&self) -> Result<(), RuntimeError> {
617        let Some(store) = self.inner.persistence.store.as_ref() else {
618            return Ok(());
619        };
620        let bundle = {
621            let session = self.inner.session.lock().await;
622            session.persistable_bundle_if_resume_safe()?
623        };
624        if let Some(bundle) = bundle
625            && !bundle.document_bytes.is_empty()
626        {
627            let cursor = bundle.cursor.clone();
628            store.write_bundle(bundle).await?;
629            self.inner.session.lock().await.adopt_journal_cursor(cursor);
630        }
631        Ok(())
632    }
633
634    /// Returns the low-level Merry-managed capabilities configured for this runtime.
635    #[must_use]
636    pub fn capabilities(&self) -> &RuntimeCapabilities {
637        &self.inner.capabilities
638    }
639
640    /// Returns the current runtime-owned trajectory projection.
641    pub async fn trajectory_snapshot(
642        &self,
643    ) -> Result<merry_core::TrajectorySnapshot, RuntimeError> {
644        Ok(self.inner.trajectory.snapshot())
645    }
646
647    /// Subscribes to trajectory changes and returns an atomic initial snapshot.
648    pub async fn trajectory_subscription(
649        &self,
650    ) -> Result<
651        (
652            merry_core::TrajectorySnapshot,
653            tokio::sync::broadcast::Receiver<merry_core::TrajectoryEvent>,
654        ),
655        RuntimeError,
656    > {
657        Ok(self.inner.trajectory.subscribe_with_snapshot())
658    }
659
660    /// Returns the configured skill metadata for UI/SDK discovery.
661    ///
662    /// This exposes only metadata already stored in the session. Skill bodies
663    /// remain on disk and do not enter prompt context through this accessor.
664    pub async fn skills(&self) -> Vec<crate::SkillMetadata> {
665        let session = self.inner.session.lock().await;
666        session
667            .skill_catalog()
668            .map(|catalog| catalog.skills().to_vec())
669            .unwrap_or_default()
670    }
671
672    /// Finds one configured skill by exact metadata name.
673    pub async fn find_skill(&self, name: &str) -> Option<crate::SkillMetadata> {
674        self.skills()
675            .await
676            .into_iter()
677            .find(|skill| skill.name() == name)
678    }
679
680    /// Returns whether this runtime asks the model for tool-progress commentary.
681    #[must_use]
682    pub fn progress_commentary(&self) -> bool {
683        self.inner.models.progress_commentary
684    }
685
686    /// Executes one pending tool call through a runtime-registered executor.
687    ///
688    /// Runtime code owns the resulting artifact id and `ToolCallResult`.
689    /// Executor infrastructure errors and cancellation leave the call pending.
690    /// Tool-domain failures should be returned as failed outcomes so the
691    /// runtime can still record a durable result and emit `ToolCallResolved`.
692    ///
693    /// This method acquires the active-step permit while the executor runs. The
694    /// executor receives provider-neutral pending call data and returns
695    /// provider-neutral artifact content; provider-specific tool wire formats do
696    /// not enter runtime state.
697    pub async fn execute_tool_call(
698        &self,
699        call_id: &ToolCallId,
700        context: ToolExecutionContext,
701    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
702        let _active_permit = self.acquire_active_step_permit()?;
703
704        self.execute_tool_call_with_active_permit(call_id, context, &_active_permit)
705            .await
706    }
707
708    pub(crate) async fn execute_tool_call_with_active_permit(
709        &self,
710        call_id: &ToolCallId,
711        context: ToolExecutionContext,
712        _active_permit: &ActiveStepPermit,
713    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
714        let result =
715            tool_execution::execute_tool_call_with_active_permit(&self.inner, call_id, context)
716                .await;
717        if let Ok(events) = &result {
718            self.inner.commit_journal_events(events).await;
719        }
720        result
721    }
722
723    pub(crate) async fn execute_tool_call_batch_with_active_permit(
724        &self,
725        calls: Vec<PendingToolCall>,
726        context: ToolExecutionContext,
727        _active_permit: &ActiveStepPermit,
728    ) -> tool_batch::ToolBatchExecution {
729        let execution =
730            tool_batch::execute_tool_call_batch_with_active_permit(&self.inner, calls, context)
731                .await;
732        if execution.is_successful() {
733            self.inner.commit_journal_events(execution.events()).await;
734        } else {
735            self.inner.project_journal_events(execution.events());
736        }
737        execution
738    }
739
740    pub(crate) async fn execute_tool_call_batch_streaming_with_active_permit(
741        &self,
742        calls: Vec<PendingToolCall>,
743        context: ToolExecutionContext,
744        event_tx: tokio::sync::mpsc::Sender<Vec<RuntimeJournalEvent>>,
745        _active_permit: &ActiveStepPermit,
746    ) -> Option<RuntimeError> {
747        let error = tool_batch::execute_tool_call_batch_streaming_with_active_permit(
748            &self.inner,
749            calls,
750            context,
751            event_tx,
752        )
753        .await;
754        if error.is_none() {
755            self.inner.refresh_resume_savepoint().await;
756        }
757        error
758    }
759
760    /// Payload-free summary of the installed compacted checkpoint, if any.
761    pub async fn compacted_checkpoint_summary(&self) -> Option<CompactedCheckpointSummary> {
762        let session = self.inner.session.lock().await;
763        session.compacted_checkpoint_summary()
764    }
765
766    /// Builds a model-facing citation compaction input for the compressible history prefix.
767    pub async fn citation_compaction_input(
768        &self,
769        policy: CitationCompactionPolicy,
770    ) -> Result<Option<CitationCompactionInput>, RuntimeError> {
771        let _active_permit = self.acquire_active_step_permit()?;
772        compaction_input_for_policy(&self.inner, policy).await
773    }
774
775    /// Installs a prose compaction summary and drops the covered history from the prompt.
776    pub async fn install_summary_compaction(
777        &self,
778        input: CitationCompactionInput,
779        summary: &str,
780    ) -> Result<CompactionOutcome, RuntimeError> {
781        let active_permit = self.acquire_active_step_permit()?;
782        install_summary_compaction_transactionally(
783            Arc::clone(&self.inner),
784            input,
785            summary,
786            CancellationToken::new(),
787            active_permit,
788        )
789        .await
790    }
791
792    /// Reduces history toward the destination budget, using bounded rolling passes if needed.
793    /// Returns aggregate coverage and the final checkpoint. Each pass installs durably;
794    /// cancellation or a later failure preserves any previously installed checkpoint.
795    pub async fn compact_context_once(
796        &self,
797        policy: CitationCompactionPolicy,
798        context: StepContext,
799    ) -> Result<Option<CompactionOutcome>, RuntimeError> {
800        self.compact_context_once_with_focus(policy, None, context)
801            .await
802    }
803
804    /// Reduces history toward the destination budget while incorporating optional
805    /// user-supplied `focus` instructions into the summary directive.
806    pub async fn compact_context_once_with_focus(
807        &self,
808        policy: CitationCompactionPolicy,
809        focus: Option<String>,
810        context: StepContext,
811    ) -> Result<Option<CompactionOutcome>, RuntimeError> {
812        let active_permit = self.acquire_active_step_permit()?;
813
814        let (token, _, _) = context.into_parts();
815        if token.is_cancelled() {
816            return Err(RuntimeError::Compaction {
817                source: CompactionError::InvalidModelResponseShape {
818                    reason: "compaction cancelled before input build",
819                },
820            });
821        }
822
823        compact_context_once_inner(&self.inner, policy, focus, token, active_permit, None).await
824    }
825
826    /// Reduces history toward the destination budget using either an explicit
827    /// `policy` override or the runtime's configured compaction policy, while
828    /// incorporating optional user-supplied `focus` instructions.
829    pub async fn compact_context(
830        &self,
831        policy: Option<CitationCompactionPolicy>,
832        focus: Option<String>,
833        context: StepContext,
834    ) -> Result<Option<CompactionOutcome>, RuntimeError> {
835        let resolved_policy = match policy {
836            Some(policy) => policy,
837            None => self.inner.models.automatic_compaction.read().await.policy(),
838        };
839        self.compact_context_once_with_focus(resolved_policy, focus, context)
840            .await
841    }
842
843    pub(crate) async fn compact_context_with_active_permit(
844        &self,
845        policy_override: Option<CitationCompactionPolicy>,
846        focus: Option<String>,
847        token: CancellationToken,
848        active_permit: ActiveStepPermit,
849        started_notify: tokio::sync::oneshot::Sender<()>,
850    ) -> Result<Option<CompactionOutcome>, RuntimeError> {
851        let policy = match policy_override {
852            Some(policy) => policy,
853            None => self.inner.models.automatic_compaction.read().await.policy(),
854        };
855        compact_context_once_inner(
856            &self.inner,
857            policy,
858            focus,
859            token,
860            active_permit,
861            Some(started_notify),
862        )
863        .await
864    }
865
866    pub(crate) async fn record_manual_compaction_started(&self) -> merry_core::RuntimeJournalEvent {
867        let event = {
868            let mut session = self.inner.session.lock().await;
869            session.record_compaction_started()
870        };
871        self.inner
872            .commit_journal_events(std::slice::from_ref(&event))
873            .await;
874        event
875    }
876
877    pub(crate) async fn record_manual_compaction_completed(
878        &self,
879        outcome: &CompactionOutcome,
880    ) -> merry_core::RuntimeJournalEvent {
881        let event = {
882            let mut session = self.inner.session.lock().await;
883            session.record_compaction_completed(
884                outcome.checkpoint_id().as_str().to_owned(),
885                outcome.covered_history_item_count(),
886            )
887        };
888        self.inner
889            .commit_journal_events(std::slice::from_ref(&event))
890            .await;
891        event
892    }
893
894    pub(crate) async fn record_manual_compaction_cancelled(
895        &self,
896        message: &str,
897    ) -> merry_core::RuntimeJournalEvent {
898        let diagnostic = diagnostic_from_text("manual_compaction_cancelled", message);
899        let event = {
900            let mut session = self.inner.session.lock().await;
901            session.record_cancelled(diagnostic)
902        };
903        self.inner
904            .commit_journal_events(std::slice::from_ref(&event))
905            .await;
906        event
907    }
908
909    pub(crate) async fn record_manual_compaction_failed(
910        &self,
911        message: &str,
912    ) -> merry_core::RuntimeJournalEvent {
913        let diagnostic = diagnostic_from_text("manual_compaction", message);
914        let event = {
915            let mut session = self.inner.session.lock().await;
916            session.record_failed(diagnostic)
917        };
918        self.inner
919            .commit_journal_events(std::slice::from_ref(&event))
920            .await;
921        event
922    }
923}
924
925impl Runtime {
926    /// Returns the automatic compaction policy used by subsequent requests.
927    pub async fn automatic_compaction_config(&self) -> CompactionConfig {
928        self.inner.models.automatic_compaction.read().await.clone()
929    }
930
931    pub(crate) async fn update_interactive_primary_model(
932        &self,
933        provider: Arc<dyn ModelProvider>,
934        model: ModelName,
935        retry_policy: ModelRetryPolicy,
936    ) {
937        self.update_interactive_role_model(
938            crate::RuntimeModelRole::Primary,
939            Some(crate::InteractivePrimaryModel::new(
940                provider,
941                model,
942                retry_policy,
943            )),
944        )
945        .await;
946    }
947
948    pub(crate) async fn update_interactive_role_model(
949        &self,
950        role: crate::RuntimeModelRole,
951        model: Option<crate::InteractivePrimaryModel>,
952    ) {
953        let entry = model.map(|selected| {
954            ModelProviderConfig::new(selected.provider, selected.model, selected.retry_policy)
955                .with_reasoning_effort(selected.reasoning_effort)
956        });
957        if role == crate::RuntimeModelRole::Primary
958            && let Some(ref cfg) = entry
959            && let Some(manager) = self.inner.subagents.manager.as_ref()
960        {
961            manager.update_parent_primary_model(crate::ParentPrimaryModel {
962                provider: cfg.provider(),
963                model: cfg.model().clone(),
964                retry_policy: cfg.retry_policy(),
965            });
966        }
967        self.inner
968            .models
969            .role_overrides
970            .write()
971            .await
972            .insert(role, entry);
973    }
974
975    pub(crate) fn update_interactive_max_parallel_tool_calls(&self, limit: std::num::NonZeroUsize) {
976        self.inner
977            .tools
978            .max_parallel_calls
979            .store(limit.get(), std::sync::atomic::Ordering::Release);
980    }
981
982    pub(crate) async fn update_interactive_permission_review_mode(
983        &self,
984        mode: crate::PermissionReviewMode,
985    ) {
986        *self.inner.permissions.review_mode.write().await = mode;
987    }
988
989    pub(crate) async fn update_interactive_permission_admission_source(
990        &self,
991        source: Arc<dyn crate::PermissionAdmissionSource>,
992    ) {
993        *self.inner.permissions.admission_source.write().await = Some(source);
994    }
995
996    pub(crate) async fn update_interactive_process_execution(
997        &self,
998        update: crate::InteractiveProcessExecutionUpdate,
999    ) {
1000        let mut lanes = self.inner.process_lanes.write().await;
1001        lanes.low_risk_runner = Some(Arc::clone(&update.runner));
1002        lanes.read_only_shell_runner = Some(Arc::clone(&update.runner));
1003        lanes.accepted_local_workspace_runner = Some(state::AcceptedLocalWorkspaceProcessRunner {
1004            admission: update.admission,
1005            runner: update.runner,
1006        });
1007        lanes.permissioned_runner_factory = Some(update.permissioned_factory);
1008    }
1009
1010    pub(crate) fn update_interactive_generation_config(
1011        &self,
1012        generation_config: merry_llm::GenerationConfig,
1013    ) {
1014        if let Some(manager) = self.inner.subagents.manager.as_ref() {
1015            manager.update_parent_generation_config(generation_config);
1016        }
1017    }
1018
1019    pub(crate) async fn update_interactive_subagents(
1020        &self,
1021        enabled: bool,
1022        config: crate::SubagentConfig,
1023    ) -> Result<(), RuntimeError> {
1024        let manager =
1025            self.inner
1026                .subagents
1027                .manager
1028                .as_ref()
1029                .ok_or(RuntimeError::InvalidStepInput {
1030                    reason: "interactive subagent runtime control is unavailable",
1031                })?;
1032        manager.update_policy(enabled, config).await
1033    }
1034
1035    pub(crate) async fn update_interactive_automatic_compaction(&self, config: CompactionConfig) {
1036        *self.inner.models.automatic_compaction.write().await = config;
1037    }
1038
1039    pub(crate) async fn update_interactive_context_window_tokens(
1040        &self,
1041        context_window_tokens: Option<NonZeroU64>,
1042    ) {
1043        *self.inner.models.context_window_tokens.write().await = context_window_tokens;
1044    }
1045
1046    pub(crate) fn native_hook_handler(&self) -> Option<&Arc<dyn crate::RuntimeHookHandler>> {
1047        self.inner.tools.hook_handler.as_ref()
1048    }
1049
1050    pub(crate) fn bridge_hook_subscriptions(&self) -> &crate::HookSubscriptions {
1051        &self.inner.tools.bridge_hook_subscriptions
1052    }
1053
1054    pub(crate) fn validate_registered_tool_input(
1055        &self,
1056        call: &merry_core::PendingToolCall,
1057    ) -> Option<Result<(), crate::tool_input_validation::ToolInputValidationError>> {
1058        self.inner.tools.registry.validate_tool_input(call)
1059    }
1060
1061    pub(crate) async fn compact_context_for_hook_with_active_permit(
1062        &self,
1063        cancellation_token: tokio_util::sync::CancellationToken,
1064        active_permit: &ActiveStepPermit,
1065    ) -> Result<Option<CompactionOutcome>, RuntimeError> {
1066        let policy = self.inner.models.automatic_compaction.read().await.policy();
1067        auto_compaction::compact_context_once_inner(
1068            &self.inner,
1069            policy,
1070            None,
1071            cancellation_token,
1072            active_permit.clone(),
1073            None,
1074        )
1075        .await
1076    }
1077}
1078#[cfg(test)]
1079mod tests;