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