Skip to main content

merry_runtime/runtime/
session_access.rs

1use super::{Runtime, RuntimeError, diagnostic_from_text};
2use crate::{
3    ContextEntry, ContextSummary, SessionContextSnapshot, SessionTranscriptItem,
4    events::ActiveStepPermit, tool_input_validation::ToolInputValidationError,
5};
6use merry_core::{
7    ErrorInfo, PendingToolCall, RuntimeJournalEvent, TOOL_CANCELLED_BY_USER_CODE, ToolCallId,
8    ToolCallResult, ToolCallResultStatus, ToolOutput, ToolOutputPreview,
9};
10use std::sync::atomic::Ordering;
11
12/// Diagnostic code recorded for a tool call a settling run gave up on.
13const TOOL_ABANDONED_BY_SETTLEMENT_CODE: &str = "tool_abandoned_by_run_settlement";
14
15impl Runtime {
16    /// Returns whether [`Self::close`] has closed this runtime session.
17    #[must_use]
18    pub fn is_closed(&self) -> bool {
19        self.inner.closed.load(Ordering::Acquire)
20    }
21
22    /// Closes this runtime session, releasing any held OS-level session lock
23    /// and removing an untouched empty session directory from the store.
24    ///
25    /// Closing is idempotent once completed. Calling `close` while an active
26    /// step, run, or interactive session still owns the runtime fails with
27    /// [`RuntimeError::StepAlreadyActive`] so in-flight persistence cannot
28    /// continue without the session lock.
29    pub async fn close(&self) -> Result<(), RuntimeError> {
30        if self.inner.closed.load(Ordering::Acquire) {
31            return Ok(());
32        }
33        let _active_permit = match self.acquire_active_step_permit() {
34            Ok(permit) => permit,
35            Err(RuntimeError::SessionClosed { .. }) => return Ok(()),
36            Err(error) => return Err(error),
37        };
38        self.inner.closed.store(true, Ordering::Release);
39        self.inner.memory.close_token.cancel();
40        super::session_topic::cancel(&self.inner).await;
41        super::memory_maintenance::shutdown(&self.inner).await;
42        self.shutdown_subagents().await;
43        self.shutdown_background_processes();
44        self.close_trajectory();
45        let reservation = self
46            .inner
47            .persistence
48            .reservation
49            .lock()
50            .unwrap_or_else(|poisoned| poisoned.into_inner())
51            .take();
52        if let (Some(reservation), Some(store)) =
53            (reservation, self.inner.persistence.store.as_ref())
54        {
55            store
56                .release_empty_reservation(&self.inner.session_id, reservation)
57                .await;
58        }
59        Ok(())
60    }
61
62    /// Returns the session's frozen external definitions, independently of availability.
63    pub async fn external_tool_catalog(&self) -> merry_core::SessionToolCatalog {
64        self.inner
65            .session
66            .lock()
67            .await
68            .external_tool_catalog()
69            .clone()
70    }
71
72    /// Resolves one pending tool call with its recorded output.
73    ///
74    /// The output is durably recorded in the session transcript before
75    /// `ToolCallResolved` is emitted.
76    ///
77    /// Cancellation or executor infrastructure failures do not resolve the call;
78    /// a pending tool call remains pending until this method or
79    /// [`Runtime::execute_tool_call`] records a durable result.
80    pub async fn submit_tool_result(
81        &self,
82        result: ToolCallResult,
83        output: ToolOutput,
84    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
85        let _active_permit = self.acquire_active_step_permit()?;
86
87        self.submit_tool_result_with_active_permit(result, output, &_active_permit)
88            .await
89    }
90
91    pub(crate) async fn submit_tool_result_with_active_permit(
92        &self,
93        result: ToolCallResult,
94        output: ToolOutput,
95        _active_permit: &ActiveStepPermit,
96    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
97        let events = {
98            let mut session = self.inner.session.lock().await;
99            session.submit_tool_result(result, output)?
100        };
101        self.inner.commit_journal_events(&events).await;
102        Ok(events)
103    }
104
105    pub(crate) async fn validate_tool_execution_outcomes_with_active_permit(
106        &self,
107        outcomes: &[(ToolCallId, crate::ToolExecutionOutcome)],
108        _active_permit: &ActiveStepPermit,
109    ) -> Result<(), RuntimeError> {
110        let session = self.inner.session.lock().await;
111        session.validate_tool_execution_outcomes(outcomes)
112    }
113
114    pub(crate) async fn submit_tool_execution_outcomes_with_active_permit(
115        &self,
116        outcomes: Vec<(ToolCallId, crate::ToolExecutionOutcome)>,
117        _active_permit: &ActiveStepPermit,
118    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
119        let events = {
120            let mut session = self.inner.session.lock().await;
121            session.submit_tool_execution_outcomes(outcomes)?
122        };
123        self.inner.commit_journal_events(&events).await;
124        Ok(events)
125    }
126
127    pub(crate) async fn record_final_output_tool_call(
128        &self,
129        call: PendingToolCall,
130    ) -> Result<(crate::FinalOutput, Vec<RuntimeJournalEvent>), RuntimeError> {
131        let json = serde_json::to_string(call.arguments().as_object())
132            .expect("tool call arguments are JSON object values and must serialize");
133        let output = {
134            let mut session = self.inner.session.lock().await;
135            session.record_final_output(call.id().clone(), json)?
136        };
137        self.inner.commit_journal_events(&output.1).await;
138        Ok(output)
139    }
140
141    pub(crate) async fn submit_tool_input_validation_failure_with_active_permit(
142        &self,
143        call: &PendingToolCall,
144        error: ToolInputValidationError,
145        _active_permit: &ActiveStepPermit,
146    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
147        let content = error.content_for_call(call);
148        let diagnostic = error.diagnostic();
149        let events = {
150            let mut session = self.inner.session.lock().await;
151            session.submit_tool_execution_outcome(
152                call.id(),
153                ToolCallResultStatus::Failed,
154                content,
155                Some(diagnostic),
156                None,
157            )?
158        };
159        self.inner.commit_journal_events(&events).await;
160        Ok(events)
161    }
162
163    pub(crate) async fn submit_tool_interrupt_failure_with_active_permit(
164        &self,
165        call_id: &ToolCallId,
166        _active_permit: &ActiveStepPermit,
167    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
168        let diagnostic = ErrorInfo::new(
169            TOOL_CANCELLED_BY_USER_CODE,
170            &format!("tool call {call_id} was cancelled by user interrupt"),
171        )
172        .expect("static diagnostic code and runtime-owned call id are valid");
173        let events = {
174            let mut session = self.inner.session.lock().await;
175            session.submit_tool_execution_outcome(
176                call_id,
177                ToolCallResultStatus::Failed,
178                ToolOutput::text("Tool execution was cancelled by user interrupt."),
179                Some(diagnostic),
180                None,
181            )?
182        };
183        self.inner.commit_journal_events(&events).await;
184        Ok(events)
185    }
186
187    /// Resolves every pending tool call with a durable failed result so the
188    /// session reaches a resume-safe boundary, returning how many were resolved.
189    pub async fn abandon_pending_tool_calls(&self, reason: &str) -> Result<usize, RuntimeError> {
190        let active_permit = self.acquire_active_step_permit()?;
191        let pending = {
192            let session = self.inner.session.lock().await;
193            session.pending_tool_calls()
194        };
195        for call in &pending {
196            self.submit_tool_abandoned_failure_with_active_permit(
197                call.id(),
198                reason,
199                &active_permit,
200            )
201            .await?;
202        }
203        Ok(pending.len())
204    }
205
206    pub(crate) async fn submit_tool_abandoned_failure_with_active_permit(
207        &self,
208        call_id: &ToolCallId,
209        reason: &str,
210        _active_permit: &ActiveStepPermit,
211    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
212        let diagnostic = diagnostic_from_text(TOOL_ABANDONED_BY_SETTLEMENT_CODE, reason);
213        let events = {
214            let mut session = self.inner.session.lock().await;
215            session.submit_tool_execution_outcome(
216                call_id,
217                ToolCallResultStatus::Failed,
218                ToolOutput::text(format!("Tool execution was abandoned: {reason}")),
219                Some(diagnostic),
220                None,
221            )?
222        };
223        self.inner.commit_journal_events(&events).await;
224        Ok(events)
225    }
226
227    pub(crate) async fn replace_pending_tool_call_arguments_with_active_permit(
228        &self,
229        call_id: &ToolCallId,
230        arguments: merry_core::ToolCallArguments,
231        _active_permit: &ActiveStepPermit,
232    ) -> Result<PendingToolCall, RuntimeError> {
233        let mut session = self.inner.session.lock().await;
234        session.replace_pending_tool_call_arguments(call_id, arguments)
235    }
236
237    pub(crate) async fn replace_tool_result_output_with_active_permit(
238        &self,
239        call_id: &ToolCallId,
240        output: ToolOutput,
241        _active_permit: &ActiveStepPermit,
242    ) -> Result<(), RuntimeError> {
243        {
244            let mut session = self.inner.session.lock().await;
245            session.replace_tool_result_output(call_id, output)?;
246        }
247        self.inner.refresh_resume_savepoint().await;
248        Ok(())
249    }
250
251    pub(crate) async fn submit_hook_denied_tool_call_with_active_permit(
252        &self,
253        call: &PendingToolCall,
254        message: &str,
255        _active_permit: &ActiveStepPermit,
256    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
257        let diagnostic = diagnostic_from_text("hook_tool_denied", message);
258        let content = ToolOutput::json(
259            serde_json::json!({
260                "ok": false,
261                "tool": call.name().as_str(),
262                "error": {
263                    "code": "hook_tool_denied",
264                    "message": message,
265                }
266            })
267            .to_string(),
268        );
269        let events = {
270            let mut session = self.inner.session.lock().await;
271            session.submit_tool_execution_outcome(
272                call.id(),
273                ToolCallResultStatus::Failed,
274                content,
275                Some(diagnostic),
276                None,
277            )?
278        };
279        self.inner.commit_journal_events(&events).await;
280        Ok(events)
281    }
282
283    pub(crate) async fn submit_hook_short_circuit_tool_call_with_active_permit(
284        &self,
285        call_id: &ToolCallId,
286        output: ToolOutput,
287        _active_permit: &ActiveStepPermit,
288    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
289        let events = {
290            let mut session = self.inner.session.lock().await;
291            session.submit_tool_execution_outcome(
292                call_id,
293                ToolCallResultStatus::Succeeded,
294                output,
295                None,
296                None,
297            )?
298        };
299        self.inner.commit_journal_events(&events).await;
300        Ok(events)
301    }
302
303    /// Durably settles all remaining pending tool calls when a hook stops the turn,
304    /// keeping the session transcript valid for subsequent turns and `resume`.
305    pub(crate) async fn settle_pending_tool_calls_stopped_by_hook_with_active_permit(
306        &self,
307        reason: &str,
308        active_permit: &ActiveStepPermit,
309    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
310        let pending = {
311            let session = self.inner.session.lock().await;
312            session.pending_tool_calls()
313        };
314        let mut all_events = Vec::new();
315        for call in pending {
316            let diagnostic = diagnostic_from_text("hook_stopped_turn", reason);
317            let mut events = {
318                let mut session = self.inner.session.lock().await;
319                session.submit_tool_execution_outcome(
320                    call.id(),
321                    ToolCallResultStatus::Failed,
322                    ToolOutput::text(format!(
323                        "Tool execution skipped because hook stopped turn: {reason}"
324                    )),
325                    Some(diagnostic),
326                    None,
327                )?
328            };
329            self.inner.commit_journal_events(&events).await;
330            all_events.append(&mut events);
331        }
332        let _ = active_permit;
333        Ok(all_events)
334    }
335
336    /// Converts an executor infrastructure failure into a durable failed
337    /// result for an interactive continuation.
338    pub(crate) async fn submit_tool_execution_failure_with_active_permit(
339        &self,
340        call_id: &ToolCallId,
341        message: &str,
342        _active_permit: &ActiveStepPermit,
343    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
344        let diagnostic = diagnostic_from_text("tool_execution_failed", message);
345        let events = {
346            let mut session = self.inner.session.lock().await;
347            session.submit_tool_execution_outcome(
348                call_id,
349                ToolCallResultStatus::Failed,
350                ToolOutput::text(format!("Tool execution failed: {message}")),
351                Some(diagnostic),
352                None,
353            )?
354        };
355        self.inner.commit_journal_events(&events).await;
356        Ok(events)
357    }
358
359    pub(crate) async fn submit_structured_output_failure_with_active_permit(
360        &self,
361        call_id: &ToolCallId,
362        message: &str,
363        _active_permit: &ActiveStepPermit,
364    ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError> {
365        let diagnostic = diagnostic_from_text("structured_output_invalid", message);
366        let events = {
367            let mut session = self.inner.session.lock().await;
368            session.submit_tool_execution_outcome(
369                call_id,
370                ToolCallResultStatus::Failed,
371                ToolOutput::text(format!(
372                    "Structured output was invalid: {message}. Call merry_final_output again with a value matching the requested schema."
373                )),
374                Some(diagnostic),
375                None,
376            )?
377        };
378        self.inner.commit_journal_events(&events).await;
379        Ok(events)
380    }
381
382    /// Reads the full recorded output for one resolved tool call.
383    ///
384    /// Checks hot in-memory session state first, then falls back to archived
385    /// compacted segments on disk when a session store is attached.
386    /// Returns `Ok(None)` when `call_id` has no recorded result in this session.
387    pub async fn read_tool_output(
388        &self,
389        call_id: &ToolCallId,
390    ) -> Result<Option<ToolOutput>, RuntimeError> {
391        let hot = {
392            let session = self.inner.session.lock().await;
393            session.read_tool_output(call_id)
394        };
395        if hot.is_some() {
396            return Ok(hot);
397        }
398        let Some(store) = self.inner.persistence.store.as_ref() else {
399            return Ok(None);
400        };
401        Ok(
402            crate::session::read_archived_tool_output(store, &self.inner.session_id, call_id)
403                .await?,
404        )
405    }
406
407    /// Reads a bounded UTF-8 preview of one resolved tool call without cloning
408    /// the full output when it is still in hot memory.
409    ///
410    /// Falls back to archived compacted segments on disk when a session store
411    /// is attached. Returns `Ok(None)` when `call_id` has no recorded result
412    /// in this session.
413    pub async fn read_tool_output_preview(
414        &self,
415        call_id: &ToolCallId,
416        max_bytes: usize,
417    ) -> Result<Option<ToolOutputPreview>, RuntimeError> {
418        let hot = {
419            let session = self.inner.session.lock().await;
420            session.read_tool_output_preview(call_id, max_bytes)
421        };
422        if hot.is_some() {
423            return Ok(hot);
424        }
425        let Some(store) = self.inner.persistence.store.as_ref() else {
426            return Ok(None);
427        };
428        let archived =
429            crate::session::read_archived_tool_output(store, &self.inner.session_id, call_id)
430                .await?;
431        Ok(archived.map(|output| output.bounded_preview(max_bytes)))
432    }
433
434    /// Records a structured context entry into the owning session.
435    pub async fn record_context_entry(&self, entry: ContextEntry) -> Result<(), RuntimeError> {
436        let _active_permit = self.acquire_active_step_permit()?;
437
438        let mut session = self.inner.session.lock().await;
439        session.record_context_entry(entry)?;
440        Ok(())
441    }
442
443    /// Records a summary context entry into the owning session.
444    pub async fn record_context_summary(
445        &self,
446        summary: ContextSummary,
447    ) -> Result<(), RuntimeError> {
448        self.record_context_entry(ContextEntry::summary(summary))
449            .await
450    }
451
452    /// Builds a sealed context snapshot from session-owned context state.
453    pub async fn context_snapshot(&self) -> SessionContextSnapshot {
454        let session = self.inner.session.lock().await;
455        session.context_snapshot()
456    }
457
458    /// Returns a snapshot of provider-neutral tool calls currently awaiting results.
459    pub async fn pending_tool_calls(&self) -> Vec<PendingToolCall> {
460        let session = self.inner.session.lock().await;
461        session.pending_tool_calls()
462    }
463
464    /// Returns the persisted transcript as a UI/SDK-friendly read-only view.
465    pub async fn session_transcript(&self) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
466        let snapshots = {
467            let session = self.inner.session.lock().await;
468            session.full_transcript_snapshot()
469        };
470        Ok(snapshots
471            .into_iter()
472            .map(SessionTranscriptItem::from)
473            .collect())
474    }
475
476    /// Lists surviving archived compaction segment numbers in ascending order
477    /// (`1, 2, ...`) when a session store is attached.
478    pub async fn archived_segment_numbers(&self) -> Result<Vec<u32>, RuntimeError> {
479        let Some(store) = self.inner.persistence.store.as_ref() else {
480            return Ok(Vec::new());
481        };
482        Ok(crate::session::list_archived_segment_numbers(store, &self.inner.session_id).await?)
483    }
484
485    /// Reads one archived compaction segment as UI/SDK transcript items for
486    /// on-demand upward scrollback loading.
487    pub async fn read_archived_segment_transcript(
488        &self,
489        segment_number: u32,
490    ) -> Result<Vec<SessionTranscriptItem>, RuntimeError> {
491        let Some(store) = self.inner.persistence.store.as_ref() else {
492            return Ok(Vec::new());
493        };
494        Ok(crate::session::read_archived_segment_transcript(
495            store,
496            &self.inner.session_id,
497            segment_number,
498        )
499        .await?)
500    }
501}