1use 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#[derive(Clone)]
84pub struct Runtime {
85 inner: Arc<RuntimeInner>,
86}
87
88impl Runtime {
89 #[must_use]
94 pub fn builder(session_id: SessionId) -> RuntimeBuilder {
95 RuntimeBuilder::new(session_id)
96 }
97
98 #[must_use]
100 pub fn subscribe_subagent_activity(&self) -> SubagentActivityReceiver {
101 self.inner.subagents.activity_hub.subscribe()
102 }
103
104 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 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 pub fn journal_stream(
143 &self,
144 input: StepInput,
145 context: StepContext,
146 ) -> Result<RuntimeJournalEventStream, RuntimeError> {
147 self.step(input, context)
148 }
149
150 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 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 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 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 pub async fn session_topic(&self) -> Option<String> {
221 self::session_topic::topic(&self.inner).await
222 }
223
224 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 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 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 #[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 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 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 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 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 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 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 pub async fn shutdown_subagents(&self) {
458 if let Some(manager) = &self.inner.subagents.manager {
459 manager.shutdown().await;
460 }
461 }
462
463 pub async fn plan_session_snapshot(&self) -> merry_core::PlanSessionSnapshot {
465 self.inner.session.lock().await.plan_state().snapshot()
466 }
467
468 pub async fn plan_documents(&self) -> Vec<merry_core::PlanDocument> {
470 self.inner.session.lock().await.plan_state().documents()
471 }
472
473 pub async fn todo_items(&self) -> Vec<merry_core::TodoItem> {
475 self.inner.session.lock().await.todo_list().items().to_vec()
476 }
477
478 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 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 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 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 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 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 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 #[must_use]
636 pub fn capabilities(&self) -> &RuntimeCapabilities {
637 &self.inner.capabilities
638 }
639
640 pub async fn trajectory_snapshot(
642 &self,
643 ) -> Result<merry_core::TrajectorySnapshot, RuntimeError> {
644 Ok(self.inner.trajectory.snapshot())
645 }
646
647 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 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 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 #[must_use]
682 pub fn progress_commentary(&self) -> bool {
683 self.inner.models.progress_commentary
684 }
685
686 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 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 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 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 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 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 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 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;