Skip to main content

merry_runtime/
error.rs

1//! Runtime error types.
2//!
3//! Errors in this module describe runtime construction, admission,
4//! and tool execution contracts. Provider failures are normalized before they
5//! become runtime events; provider wire errors are not exposed as runtime state.
6
7use crate::ToolActionKind;
8use crate::checkpoint::CheckpointError;
9use crate::compaction::CompactionError;
10use crate::context::ContextError;
11use crate::session_store::SessionStoreError;
12use merry_core::{CoreError, SessionId, ToolCallBatchId, ToolCallId, ToolName, ToolOutputKind};
13use thiserror::Error;
14
15/// Errors raised by Merry runtime construction and step admission.
16///
17/// Variants are actionable contract failures at the runtime facade boundary.
18/// Cancellation and executor infrastructure failures leave pending tool calls
19/// unresolved unless a durable result was already recorded.
20#[derive(Debug, Error)]
21pub enum RuntimeError {
22    /// A new step was requested while another step still owns the runtime.
23    #[error("runtime step already active for session {session_id}")]
24    StepAlreadyActive {
25        /// Session with an active step.
26        session_id: SessionId,
27    },
28
29    /// An operation was requested on a runtime whose session has already been closed.
30    #[error("session {session_id} has been closed")]
31    SessionClosed {
32        /// Closed session identifier.
33        session_id: SessionId,
34    },
35
36    /// Step input failed runtime validation.
37    #[error("invalid step input: {reason}")]
38    InvalidStepInput {
39        /// Actionable validation detail.
40        reason: &'static str,
41    },
42
43    /// An agent-loop entry point received conflicting structured-output
44    /// contracts from its context and loop configuration.
45    #[error("invalid agent loop configuration: {source}")]
46    AgentLoopConfig {
47        /// Invalid loop configuration detail.
48        #[source]
49        source: crate::agent_loop::AgentLoopConfigError,
50    },
51
52    /// A child runtime factory could not materialize its runtime profile.
53    #[error("child runtime construction failed: {message}")]
54    ChildRuntimeBuild {
55        /// Profile construction detail from the owning composition layer.
56        message: String,
57    },
58
59    /// A subagent status operation did not select any child agents.
60    #[error("{operation} requires at least one agent id")]
61    InvalidSubagentSelection {
62        /// Provider-visible operation that received the empty selection.
63        operation: &'static str,
64    },
65
66    /// A Plan Mode operation failed validation or referenced an unknown plan.
67    #[error("plan error: {source}")]
68    Plan {
69        /// Source plan error.
70        #[from]
71        source: crate::PlanError,
72    },
73
74    /// A user image or image-bearing message failed runtime validation.
75    #[error("invalid user image input: {reason}")]
76    InvalidUserImageInput {
77        /// Actionable image validation detail.
78        reason: String,
79    },
80
81    /// A submitted tool result does not match any pending or resolved call.
82    #[error("tool call {call_id} is not pending in session {session_id}")]
83    UnknownToolCall {
84        /// Session receiving the result.
85        session_id: SessionId,
86        /// Tool call id that could not be found.
87        call_id: ToolCallId,
88    },
89
90    /// A bridge result submission did not contain any outcomes.
91    #[error("bridge tool result batch is empty in session {session_id}")]
92    BridgeToolResultBatchEmpty {
93        /// Session receiving the empty result batch.
94        session_id: SessionId,
95    },
96
97    /// A bridge result submission did not resolve exactly the requested calls.
98    #[error(
99        "bridge tool result batch does not match pending calls in session {session_id}: expected {expected_call_ids:?}, received {received_call_ids:?}"
100    )]
101    BridgeToolResultBatchMismatch {
102        /// Session receiving the mismatched result batch.
103        session_id: SessionId,
104        /// Call ids currently waiting for external execution.
105        expected_call_ids: Vec<ToolCallId>,
106        /// Call ids supplied by the external executor.
107        received_call_ids: Vec<ToolCallId>,
108    },
109
110    /// A bridge result was submitted for a different runtime-owned batch.
111    #[error(
112        "bridge tool result batch id does not match the pending batch in session {session_id}: expected {expected_batch_id}, received {received_batch_id}"
113    )]
114    BridgeToolResultBatchIdMismatch {
115        /// Session receiving the stale or mismatched result.
116        session_id: SessionId,
117        /// Runtime-owned batch id currently awaiting results.
118        expected_batch_id: ToolCallBatchId,
119        /// Batch id supplied by the host.
120        received_batch_id: ToolCallBatchId,
121    },
122
123    /// A host result could not be recorded, but the pending call can still be
124    /// resolved as a failed tool result so the model loop can recover.
125    #[error(
126        "bridge tool result was rejected in session {session_id}; the tool call was recorded as failed: {message}"
127    )]
128    BridgeToolResultRejected {
129        /// Session receiving the host result.
130        session_id: SessionId,
131        /// Original runtime validation or persistence detail.
132        message: String,
133    },
134
135    /// The run cannot read another message until its current host batch is resolved.
136    #[error(
137        "agent run has unresolved tool invocations in session {session_id} for batch {batch_id}"
138    )]
139    AgentRunToolInvocationsPending {
140        /// Session whose run is waiting for host results.
141        session_id: SessionId,
142        /// Batch that must be resolved first.
143        batch_id: ToolCallBatchId,
144    },
145
146    /// A host submitted results when the run has no active host batch.
147    #[error("agent run has no pending tool invocations in session {session_id}")]
148    NoPendingAgentRunToolInvocations {
149        /// Session receiving the submission.
150        session_id: SessionId,
151    },
152
153    /// A tool result was submitted after the call had already been resolved.
154    #[error("tool call {call_id} is already resolved in session {session_id}")]
155    ToolCallAlreadyResolved {
156        /// Session receiving the duplicate result.
157        session_id: SessionId,
158        /// Tool call id that already has a result.
159        call_id: ToolCallId,
160    },
161
162    /// Runtime construction tried to register the same tool name more than once.
163    #[error("tool {name} is already registered")]
164    DuplicateToolRegistration {
165        /// Duplicate tool name.
166        name: ToolName,
167    },
168
169    /// Runtime-reserved provider-visible tool name was registered by an application.
170    #[error("tool name {name} is reserved by the runtime")]
171    ReservedToolName {
172        /// Rejected reserved tool name.
173        name: ToolName,
174    },
175
176    /// Runtime construction received a tool schema that JSON Schema validation cannot compile.
177    #[error("tool {name} input schema is invalid: {message}")]
178    InvalidToolInputSchema {
179        /// Tool with the invalid input schema.
180        name: ToolName,
181        /// Actionable schema compiler detail.
182        message: String,
183    },
184
185    /// Runtime construction tried to register a bridge tool without explicit opt-in.
186    #[error("bridge tool {name} requires explicit bridge tool opt-in")]
187    BridgeToolsNotAllowed {
188        /// Bridge tool name.
189        name: ToolName,
190    },
191
192    /// Tool execution was cancelled before producing a durable result.
193    #[error("tool call {call_id} execution was cancelled in session {session_id}")]
194    ToolExecutionCancelled {
195        /// Session executing the tool call.
196        session_id: SessionId,
197        /// Tool call id that remained pending.
198        call_id: ToolCallId,
199    },
200
201    /// Tool executor infrastructure failed before producing a durable result.
202    #[error("tool call {call_id} executor failed in session {session_id}: {message}")]
203    ToolExecutionFailed {
204        /// Session executing the tool call.
205        session_id: SessionId,
206        /// Tool call id that remained pending.
207        call_id: ToolCallId,
208        /// Actionable executor failure detail.
209        message: String,
210    },
211
212    /// A runtime-owned agent run stopped before producing a terminal result.
213    #[error("agent run closed for session {session_id}: {message}")]
214    AgentRunClosed {
215        /// Session whose run ended unexpectedly.
216        session_id: SessionId,
217        /// Actionable stream lifecycle detail.
218        message: &'static str,
219    },
220
221    /// An admitted mutating action reported success without internal execution evidence.
222    #[error(
223        "tool call {call_id} admitted for {action_kind:?} in session {session_id} succeeded without required execution evidence"
224    )]
225    MissingActionExecutionEvidence {
226        /// Session executing the tool call.
227        session_id: SessionId,
228        /// Tool call id that remained pending.
229        call_id: ToolCallId,
230        /// Action kind that required internal execution evidence.
231        action_kind: ToolActionKind,
232    },
233
234    /// A mutating action reached the generic executor path before a commit lifecycle exists.
235    #[error(
236        "mutating tool action {action_kind:?} for tool call {call_id} in session {session_id} requires an explicit commit lifecycle before generic execution"
237    )]
238    MutatingActionCommitLifecycleRequired {
239        /// Session executing the tool call.
240        session_id: SessionId,
241        /// Tool call id that remained pending.
242        call_id: ToolCallId,
243        /// Mutating action kind that must use a commit lifecycle.
244        action_kind: ToolActionKind,
245    },
246
247    /// A tool result used invalid or blank output content.
248    #[error("tool call {call_id} result uses invalid {output_kind:?} output content")]
249    UnsupportedToolResultContent {
250        /// Tool call identifier for the submitted tool result.
251        call_id: ToolCallId,
252        /// Submitted output category.
253        output_kind: ToolOutputKind,
254    },
255
256    /// Transcript item ids are exhausted for this session.
257    #[error("transcript item id space is exhausted")]
258    TranscriptItemIdExhausted,
259
260    /// Model turn ids are exhausted for this session.
261    #[error("model turn id space is exhausted")]
262    ModelTurnIdExhausted,
263
264    /// A transcript mutation referenced a model turn that is not recorded.
265    #[error("model turn {model_turn_id} is not recorded")]
266    UnknownModelTurn { model_turn_id: u64 },
267
268    /// A transcript mutation attempted to change a terminal or incompatible turn.
269    #[error("model turn {model_turn_id} cannot {attempted} from its current status")]
270    InvalidModelTurnTransition {
271        model_turn_id: u64,
272        attempted: &'static str,
273    },
274
275    /// A pending tool call was not represented in the durable transcript.
276    #[error("tool call {call_id} has no originating transcript item")]
277    TranscriptToolCallMissing { call_id: ToolCallId },
278
279    /// A core protocol value could not be constructed.
280    #[error("core protocol error while constructing runtime state: {source}")]
281    Core {
282        /// Source core validation error.
283        #[from]
284        source: CoreError,
285    },
286
287    /// Context state could not be constructed or compiled.
288    #[error("context state error: {source}")]
289    Context {
290        /// Source context error.
291        #[from]
292        source: ContextError,
293    },
294
295    /// Checkpoint state could not be inspected or validated.
296    #[error("checkpoint state error: {source}")]
297    Checkpoint {
298        /// Source checkpoint error.
299        #[from]
300        source: CheckpointError,
301    },
302
303    /// Compaction state could not be constructed or applied.
304    #[error("compaction state error: {source}")]
305    Compaction {
306        /// Source compaction error.
307        #[from]
308        source: CompactionError,
309    },
310
311    /// Session persistence failed.
312    #[error("session store error: {source}")]
313    SessionStore {
314        /// Source session store error.
315        #[from]
316        source: SessionStoreError,
317    },
318
319    /// A runtime operation needed a model provider for a role that is not configured.
320    #[error("missing model provider for runtime role {role}")]
321    MissingModelProvider {
322        /// Missing model role.
323        role: &'static str,
324    },
325
326    /// Compaction model request construction failed.
327    #[error("compaction model request error: {message}")]
328    CompactionModelRequest {
329        /// Actionable model request error.
330        message: String,
331    },
332
333    /// The configured compaction model cannot accept the primary model's context window.
334    #[error(
335        "compaction model input window {compactor_window_tokens} tokens is smaller than primary context window {primary_window_tokens} tokens"
336    )]
337    CompactionModelWindowTooSmall {
338        /// Resolved primary model context window.
339        primary_window_tokens: u64,
340        /// Provider-reported compaction model input window.
341        compactor_window_tokens: u64,
342    },
343
344    /// The compiled compaction request cannot hold its input and reserved output together.
345    #[error(
346        "compaction model request estimated input {estimated_input_tokens} tokens plus max output {max_output_tokens} tokens exceeds compaction model window {compactor_window_tokens} tokens"
347    )]
348    CompactionModelRequestTooLarge {
349        /// Deterministic estimate of the compiled provider-neutral request input.
350        estimated_input_tokens: u64,
351        /// Output ceiling reserved for reasoning and checkpoint text.
352        max_output_tokens: u64,
353        /// Reported or primary-window-assumed compaction model window.
354        compactor_window_tokens: u64,
355    },
356
357    /// The compaction model stopped before it produced a complete checkpoint.
358    #[error("compaction model output was truncated: {message}")]
359    CompactionModelTruncated {
360        /// Actionable truncation diagnostic, including the provider's reason.
361        message: String,
362    },
363
364    /// Compaction model setup failed before a stream was returned.
365    #[error("compaction model setup error: {message}")]
366    CompactionModelSetup {
367        /// Actionable model setup error.
368        message: String,
369    },
370
371    /// Compaction model stream failed or returned an invalid candidate shape.
372    #[error("compaction model stream error: {message}")]
373    CompactionModelStream {
374        /// Actionable model stream error.
375        message: String,
376    },
377
378    /// A host-bridged hook invocation is still pending and must be resolved before reading further messages.
379    #[error("agent run for session {session_id} has pending hook invocation {invocation_id}")]
380    AgentRunHookInvocationPending {
381        /// Session whose run has a pending hook invocation.
382        session_id: SessionId,
383        /// Pending hook invocation identifier.
384        invocation_id: crate::HookInvocationId,
385    },
386
387    /// A caller attempted to submit a hook decision when no hook invocation is pending.
388    #[error("agent run for session {session_id} has no pending hook invocation")]
389    NoPendingAgentRunHookInvocation {
390        /// Session whose run has no pending hook invocation.
391        session_id: SessionId,
392    },
393
394    /// A submitted hook decision referenced the wrong invocation identifier.
395    #[error(
396        "hook invocation id mismatch for session {session_id}: expected {expected_invocation_id}, received {received_invocation_id}"
397    )]
398    HookInvocationIdMismatch {
399        /// Session whose run rejected the hook decision.
400        session_id: SessionId,
401        /// Active hook invocation identifier.
402        expected_invocation_id: crate::HookInvocationId,
403        /// Identifier submitted by the caller.
404        received_invocation_id: crate::HookInvocationId,
405    },
406
407    /// A lifecycle hook failed (fail-closed).
408    #[error("hook {hook_point} failed for session {session_id}: {message}")]
409    HookFailed {
410        /// Session whose hook failed.
411        session_id: SessionId,
412        /// Hook point that failed.
413        hook_point: crate::HookPoint,
414        /// Actionable failure detail.
415        message: String,
416    },
417
418    /// A lifecycle hook was cancelled cooperatively.
419    #[error("hook {hook_point} cancelled for session {session_id}")]
420    HookCancelled {
421        /// Session whose hook was cancelled.
422        session_id: SessionId,
423        /// Hook point that was cancelled.
424        hook_point: crate::HookPoint,
425    },
426}
427
428impl RuntimeError {
429    /// Returns the stable provider-neutral code for this runtime failure.
430    #[must_use]
431    pub const fn diagnostic_code(&self) -> &'static str {
432        match self {
433            Self::StepAlreadyActive { .. } => "step_already_active",
434            Self::SessionClosed { .. } => "session_closed",
435            Self::InvalidStepInput { .. } => "invalid_step_input",
436            Self::AgentLoopConfig { .. } => "agent_loop_config",
437            Self::ChildRuntimeBuild { .. } => "child_runtime_build",
438            Self::InvalidSubagentSelection { .. } => "invalid_subagent_selection",
439            Self::Plan { .. } => "plan_error",
440            Self::InvalidUserImageInput { .. } => "invalid_user_image_input",
441            Self::UnknownToolCall { .. } => "unknown_tool_call",
442            Self::BridgeToolResultBatchEmpty { .. } => "bridge_tool_result_batch_empty",
443            Self::BridgeToolResultBatchMismatch { .. } => "bridge_tool_result_batch_mismatch",
444            Self::BridgeToolResultBatchIdMismatch { .. } => "bridge_tool_result_batch_id_mismatch",
445            Self::BridgeToolResultRejected { .. } => "bridge_tool_result_rejected",
446            Self::AgentRunToolInvocationsPending { .. } => "agent_run_tool_invocations_pending",
447            Self::NoPendingAgentRunToolInvocations { .. } => {
448                "no_pending_agent_run_tool_invocations"
449            }
450            Self::ToolCallAlreadyResolved { .. } => "tool_call_already_resolved",
451            Self::DuplicateToolRegistration { .. } => "duplicate_tool_registration",
452            Self::ReservedToolName { .. } => "reserved_tool_name",
453            Self::InvalidToolInputSchema { .. } => "invalid_tool_input_schema",
454            Self::BridgeToolsNotAllowed { .. } => "bridge_tools_not_allowed",
455            Self::ToolExecutionCancelled { .. } => "tool_execution_cancelled",
456            Self::ToolExecutionFailed { .. } => "tool_execution_failed",
457            Self::AgentRunClosed { .. } => "agent_run_closed",
458            Self::MissingActionExecutionEvidence { .. } => "missing_action_execution_evidence",
459            Self::MutatingActionCommitLifecycleRequired { .. } => {
460                "mutating_action_commit_lifecycle_required"
461            }
462            Self::UnsupportedToolResultContent { .. } => "unsupported_tool_result_content",
463            Self::TranscriptItemIdExhausted => "transcript_item_id_exhausted",
464            Self::ModelTurnIdExhausted => "model_turn_id_exhausted",
465            Self::UnknownModelTurn { .. } => "unknown_model_turn",
466            Self::InvalidModelTurnTransition { .. } => "invalid_model_turn_transition",
467            Self::TranscriptToolCallMissing { .. } => "transcript_tool_call_missing",
468            Self::Core { .. } => "core_error",
469            Self::Context { .. } => "context_error",
470            Self::Checkpoint { .. } => "checkpoint_error",
471            Self::Compaction { .. } => "compaction_error",
472            Self::SessionStore {
473                source: SessionStoreError::SessionAlreadyReserved { .. },
474            } => "session_already_reserved",
475            Self::SessionStore { .. } => "session_store",
476            Self::MissingModelProvider { .. } => "missing_model_provider",
477            Self::CompactionModelRequest { .. } => "compaction_model_request",
478            Self::CompactionModelWindowTooSmall { .. } => "compaction_model_window_too_small",
479            Self::CompactionModelRequestTooLarge { .. } => "compaction_model_request_too_large",
480            Self::CompactionModelTruncated { .. } => "compaction_model_truncated",
481            Self::CompactionModelSetup { .. } => "compaction_model_setup",
482            Self::CompactionModelStream { .. } => "compaction_model_stream",
483            Self::AgentRunHookInvocationPending { .. } => "agent_run_hook_invocation_pending",
484            Self::NoPendingAgentRunHookInvocation { .. } => "no_pending_agent_run_hook_invocation",
485            Self::HookInvocationIdMismatch { .. } => "hook_invocation_id_mismatch",
486            Self::HookFailed { .. } => "hook_failed",
487            Self::HookCancelled { .. } => "hook_cancelled",
488        }
489    }
490
491    /// Returns whether a bridge result error can be corrected by resubmitting
492    /// the same active batch. This classification is shared by runtime and
493    /// language bindings so a binding cannot terminate a run on a validation
494    /// error that the host is expected to fix.
495    #[must_use]
496    pub fn is_retryable_bridge_tool_result(&self) -> bool {
497        matches!(
498            self,
499            Self::BridgeToolResultBatchEmpty { .. }
500                | Self::BridgeToolResultBatchMismatch { .. }
501                | Self::BridgeToolResultBatchIdMismatch { .. }
502                | Self::UnsupportedToolResultContent { .. }
503                | Self::Core {
504                    source: CoreError::InvalidToolCallResult { .. }
505                }
506        )
507    }
508}