Skip to main content

Runtime

Struct Runtime 

Source
pub struct Runtime { /* private fields */ }
Expand description

Merry runtime handle for one session.

A cloned handle points at the same session-owned state. Runtime::step and direct mutation APIs such as [Runtime::record_artifact], Runtime::record_context_entry, Runtime::submit_tool_result, and Runtime::execute_tool_call acquire the active-step permit.

Implementations§

Source§

impl Runtime

Source

pub async fn run_agent_loop( &self, input: StepInput, context: StepContext, config: AgentLoopConfig, ) -> Result<AgentLoopResult, AgentLoopError>

Runs a bounded runtime-owned agent loop.

The loop starts with one Runtime::step. If the step completes, fails, or is cancelled, the corresponding status is returned with all observed events. If the step records pending tool calls and more step budget remains, the loop executes registered runtime tools, appends their events, and starts a continuation step without adding a new user message.

A batch preserves model order around exclusive tools. Adjacent tools explicitly registered as parallel-safe may execute concurrently up to the runtime limit; all other tools execute serially. The loop does not introduce provider conversation state. It owns the runtime active-step permit for the full step -> tool execution -> continuation sequence. While the loop is running, cloned runtime handles reject concurrent direct mutation APIs with RuntimeError::StepAlreadyActive. Cancellation and generation controls are reused from context for every step and tool execution.

Source

pub fn run_agent_loop_stream( &self, input: StepInput, context: StepContext, config: AgentLoopConfig, ) -> Result<AgentRun, RuntimeError>

Starts a bounded runtime-owned agent loop and returns live events.

This has the same loop semantics as Runtime::run_agent_loop, but it returns an AgentRun handle that yields each observed merry_core::RuntimeJournalEvent as soon as the underlying step or tool execution produces it. Dropping the handle cancels the loop token and aborts the loop producer as a final cleanup guard.

Source§

impl Runtime

Source§

impl Runtime

Source

pub async fn external_tool_catalog(&self) -> SessionToolCatalog

Returns the session’s frozen external definitions, independently of availability.

Source

pub async fn submit_tool_result( &self, result: ToolCallResult, output: ToolOutput, ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError>

Resolves one pending tool call with its recorded output.

The output is durably recorded in the session transcript before ToolCallResolved is emitted.

Cancellation or executor infrastructure failures do not resolve the call; a pending tool call remains pending until this method or Runtime::execute_tool_call records a durable result.

Source

pub async fn abandon_pending_tool_calls( &self, reason: &str, ) -> Result<usize, RuntimeError>

Resolves every pending tool call with a durable failed result so the session reaches a resume-safe boundary, returning how many were resolved.

Source

pub async fn read_tool_output( &self, call_id: &ToolCallId, ) -> Result<Option<ToolOutput>, RuntimeError>

Reads the full recorded output for one resolved tool call.

Checks hot in-memory session state first, then falls back to archived compacted segments on disk when a session store is attached. Returns Ok(None) when call_id has no recorded result in this session.

Source

pub async fn read_tool_output_preview( &self, call_id: &ToolCallId, max_bytes: usize, ) -> Result<Option<ToolOutputPreview>, RuntimeError>

Reads a bounded UTF-8 preview of one resolved tool call without cloning the full output when it is still in hot memory.

Falls back to archived compacted segments on disk when a session store is attached. Returns Ok(None) when call_id has no recorded result in this session.

Source

pub async fn record_context_entry( &self, entry: ContextEntry, ) -> Result<(), RuntimeError>

Records a structured context entry into the owning session.

Source

pub async fn record_context_summary( &self, summary: ContextSummary, ) -> Result<(), RuntimeError>

Records a summary context entry into the owning session.

Source

pub async fn context_snapshot(&self) -> SessionContextSnapshot

Builds a sealed context snapshot from session-owned context state.

Source

pub async fn pending_tool_calls(&self) -> Vec<PendingToolCall>

Returns a snapshot of provider-neutral tool calls currently awaiting results.

Source

pub async fn session_transcript( &self, ) -> Result<Vec<SessionTranscriptItem>, RuntimeError>

Returns the persisted transcript as a UI/SDK-friendly read-only view.

Source

pub async fn archived_segment_numbers(&self) -> Result<Vec<u32>, RuntimeError>

Lists surviving archived compaction segment numbers in ascending order (1, 2, ...) when a session store is attached.

Source

pub async fn read_archived_segment_transcript( &self, segment_number: u32, ) -> Result<Vec<SessionTranscriptItem>, RuntimeError>

Reads one archived compaction segment as UI/SDK transcript items for on-demand upward scrollback loading.

Source§

impl Runtime

Source

pub fn builder(session_id: SessionId) -> RuntimeBuilder

Creates a runtime builder for the provided session.

The session id defines the ownership boundary for transcript state, context, pending tool calls, and emitted runtime events.

Source

pub fn subscribe_subagent_activity(&self) -> SubagentActivityReceiver

Subscribes to the latest UI-only activity snapshots for managed subagents.

Source

pub async fn resume(session_id: SessionId) -> Result<Self, RuntimeError>

Resumes a session from the default XDG state store.

Source

pub fn step( &self, input: StepInput, context: StepContext, ) -> Result<RuntimeJournalEventStream, RuntimeError>

Starts a runtime step and returns its event stream.

Only one step or direct mutation may own the runtime at a time. The step producer owns the initial active-step permit. Dropping the returned RuntimeJournalEventStream cancels and aborts the producer; the runtime becomes available after the producer and any in-flight persistence transaction have dropped their permit handles.

All events emitted by the step are provider-neutral RuntimeJournalEvent values. The runtime records session transcript and pending-tool state before the corresponding event becomes observable.

Cancellation records a cancelled event when the producer reaches a cancellation checkpoint. Pending tool calls remain pending unless a durable result has already been recorded. If compaction persistence is already in flight, its transaction keeps the active-step permit until the staged state is discarded or durably installed.

Source

pub fn journal_stream( &self, input: StepInput, context: StepContext, ) -> Result<RuntimeJournalEventStream, RuntimeError>

Starts a runtime step and returns the raw ordered journal stream.

This is the explicit low-level alias for Runtime::step. Runtime internals, debugging tools, and replay inspection should use this API when they need exact journal payloads rather than SDK-facing projection.

Source

pub fn stream( &self, input: StepInput, context: StepContext, ) -> Result<RuntimeEventStream, RuntimeError>

Starts a runtime step and returns SDK-facing public events.

Public events are projected from the internal journal after the corresponding session state is recorded. They expose assistant text and tool activity directly while omitting internal bridge handoff details.

Source

pub async fn project_journal_events( &self, events: &[RuntimeJournalEvent], ) -> Result<Vec<RuntimeEvent>, RuntimeError>

Projects raw ordered journal events into SDK-facing public events.

This helper is read-only and is intended for SDK bindings that need to return public events for a completed run while preserving raw journal evidence inside Rust runtime results.

Source

pub async fn usage(&self) -> Option<SessionUsage>

Returns the latest authoritative session usage snapshot.

Source

pub fn session_id(&self) -> &SessionId

Source

pub async fn session_topic(&self) -> Option<String>

Returns the model-written session topic, waiting briefly for the first-turn side call when it is still running.

Source

pub async fn cached_session_topic(&self) -> Option<String>

Returns the already-recorded session topic without waiting on an in-flight background topic generation call.

Source

pub async fn save_session_to( &self, store: FileSessionStore, ) -> Result<(), RuntimeError>

Saves the current resume-safe session state to the provided store.

The in-memory cursor tracks the runtime’s configured store. Another directory is written as a complete journal when it has no header, and that write does not move the cursor.

Source

pub async fn save_session(&self) -> Result<(), RuntimeError>

Saves the current resume-safe session state to the configured store.

Source

pub fn background_processes(&self) -> Vec<BackgroundProcessSummary>

Lists background processes retained by this session.

Source

pub fn read_background_process( &self, id: &BackgroundProcessId, ) -> Result<BackgroundProcessOutput, BackgroundProcessLookupError>

Reads captured output for one retained background process.

Source

pub fn stop_background_process( &self, id: &BackgroundProcessId, ) -> Result<BackgroundProcessStop, BackgroundProcessLookupError>

Stops one retained background process group.

Source

pub async fn subagent_snapshot(&self) -> Option<Vec<SubagentStatusView>>

Returns a compact snapshot of managed subagent statuses when configured.

Source

pub async fn inspect_subagent( &self, agent_id: &SubagentId, ) -> Option<SubagentInspectSession>

Opens a lazy transcript & live event inspection session for one subagent.

Source

pub async fn send_subagent_message( &self, agent_id: &SubagentId, message: String, ) -> Result<(), RuntimeError>

Sends a follow-up user message directly to one managed subagent.

Source

pub async fn cancel_subagent( &self, agent_id: &SubagentId, ) -> Result<WaitSubagentsOutput, RuntimeError>

Cancels one managed subagent.

Source

pub async fn shutdown_subagents(&self)

Cancels all live subagents owned by this runtime and awaits their task handles.

Source

pub async fn plan_session_snapshot(&self) -> PlanSessionSnapshot

Returns the current Plan Mode and session plan list snapshot.

Source

pub async fn plan_documents(&self) -> Vec<PlanDocument>

Returns all Markdown plan documents authored in this session.

Source

pub async fn todo_items(&self) -> Vec<TodoItem>

Returns the current checklist items for this session.

Source

pub async fn awaiting_plan_approval(&self) -> bool

Returns whether a submitted plan is currently awaiting user review.

Source

pub async fn set_plan_mode( &self, enabled: bool, turn_in_flight: bool, ) -> Result<Option<RuntimeJournalEvent>, RuntimeError>

Toggles Plan Mode from an explicit user control.

Returns any durable journal event emitted if the mode changed.

Source

pub async fn approve_plan( &self, plan_id: PlanId, note: Option<String>, ) -> Result<(PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError>

Approves a submitted plan, exits Plan Mode, and persists the updated state.

Source

pub async fn request_plan_changes( &self, plan_id: PlanId, feedback: String, ) -> Result<(PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError>

Requests changes on a submitted plan, keeps Plan Mode active, and persists state.

Source

pub async fn abandon_plan( &self, plan_id: PlanId, ) -> Result<(PlanDocument, Vec<RuntimeJournalEvent>), RuntimeError>

Abandons a submitted plan and exits Plan Mode without starting implementation.

Source

pub fn capabilities(&self) -> &RuntimeCapabilities

Returns the low-level Merry-managed capabilities configured for this runtime.

Source

pub async fn trajectory_snapshot( &self, ) -> Result<TrajectorySnapshot, RuntimeError>

Returns the current runtime-owned trajectory projection.

Source

pub async fn trajectory_subscription( &self, ) -> Result<(TrajectorySnapshot, Receiver<TrajectoryEvent>), RuntimeError>

Subscribes to trajectory changes and returns an atomic initial snapshot.

Source

pub async fn skills(&self) -> Vec<SkillMetadata>

Returns the configured skill metadata for UI/SDK discovery.

This exposes only metadata already stored in the session. Skill bodies remain on disk and do not enter prompt context through this accessor.

Source

pub async fn find_skill(&self, name: &str) -> Option<SkillMetadata>

Finds one configured skill by exact metadata name.

Source

pub fn progress_commentary(&self) -> bool

Returns whether this runtime asks the model for tool-progress commentary.

Source

pub async fn execute_tool_call( &self, call_id: &ToolCallId, context: ToolExecutionContext, ) -> Result<Vec<RuntimeJournalEvent>, RuntimeError>

Executes one pending tool call through a runtime-registered executor.

Runtime code owns the resulting artifact id and ToolCallResult. Executor infrastructure errors and cancellation leave the call pending. Tool-domain failures should be returned as failed outcomes so the runtime can still record a durable result and emit ToolCallResolved.

This method acquires the active-step permit while the executor runs. The executor receives provider-neutral pending call data and returns provider-neutral artifact content; provider-specific tool wire formats do not enter runtime state.

Source

pub async fn compacted_checkpoint_summary( &self, ) -> Option<CompactedCheckpointSummary>

Payload-free summary of the installed compacted checkpoint, if any.

Source

pub async fn citation_compaction_input( &self, policy: CitationCompactionPolicy, ) -> Result<Option<CitationCompactionInput>, RuntimeError>

Builds a model-facing citation compaction input for the compressible history prefix.

Source

pub async fn install_summary_compaction( &self, input: CitationCompactionInput, summary: &str, ) -> Result<CompactionOutcome, RuntimeError>

Installs a prose compaction summary and drops the covered history from the prompt.

Source

pub async fn compact_context_once( &self, policy: CitationCompactionPolicy, context: StepContext, ) -> Result<Option<CompactionOutcome>, RuntimeError>

Reduces history toward the destination budget, using bounded rolling passes if needed. Returns aggregate coverage and the final checkpoint. Each pass installs durably; cancellation or a later failure preserves any previously installed checkpoint.

Source

pub async fn compact_context_once_with_focus( &self, policy: CitationCompactionPolicy, focus: Option<String>, context: StepContext, ) -> Result<Option<CompactionOutcome>, RuntimeError>

Reduces history toward the destination budget while incorporating optional user-supplied focus instructions into the summary directive.

Source§

impl Runtime

Source

pub async fn automatic_compaction_config(&self) -> CompactionConfig

Returns the automatic compaction policy used by subsequent requests.

Trait Implementations§

Source§

impl Clone for Runtime

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more