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