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