merry-runtime 0.1.3

Structured session, task ledger, context compaction, memory, permission, and tool runtime for Merry.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Runtime error types.
//!
//! Errors in this module describe runtime construction, admission,
//! and tool execution contracts. Provider failures are normalized before they
//! become runtime events; provider wire errors are not exposed as runtime state.

use crate::ToolActionKind;
use crate::checkpoint::CheckpointError;
use crate::compaction::CompactionError;
use crate::context::ContextError;
use crate::session_store::SessionStoreError;
use merry_core::{CoreError, SessionId, ToolCallBatchId, ToolCallId, ToolName, ToolOutputKind};
use thiserror::Error;

/// Errors raised by Merry runtime construction and step admission.
///
/// Variants are actionable contract failures at the runtime facade boundary.
/// Cancellation and executor infrastructure failures leave pending tool calls
/// unresolved unless a durable result was already recorded.
#[derive(Debug, Error)]
pub enum RuntimeError {
    /// A new step was requested while another step still owns the runtime.
    #[error("runtime step already active for session {session_id}")]
    StepAlreadyActive {
        /// Session with an active step.
        session_id: SessionId,
    },

    /// An operation was requested on a runtime whose session has already been closed.
    #[error("session {session_id} has been closed")]
    SessionClosed {
        /// Closed session identifier.
        session_id: SessionId,
    },

    /// Step input failed runtime validation.
    #[error("invalid step input: {reason}")]
    InvalidStepInput {
        /// Actionable validation detail.
        reason: &'static str,
    },

    /// An agent-loop entry point received conflicting structured-output
    /// contracts from its context and loop configuration.
    #[error("invalid agent loop configuration: {source}")]
    AgentLoopConfig {
        /// Invalid loop configuration detail.
        #[source]
        source: crate::agent_loop::AgentLoopConfigError,
    },

    /// A child runtime factory could not materialize its runtime profile.
    #[error("child runtime construction failed: {message}")]
    ChildRuntimeBuild {
        /// Profile construction detail from the owning composition layer.
        message: String,
    },

    /// A subagent status operation did not select any child agents.
    #[error("{operation} requires at least one agent id")]
    InvalidSubagentSelection {
        /// Provider-visible operation that received the empty selection.
        operation: &'static str,
    },

    /// A Plan Mode operation failed validation or referenced an unknown plan.
    #[error("plan error: {source}")]
    Plan {
        /// Source plan error.
        #[from]
        source: crate::PlanError,
    },

    /// A user image or image-bearing message failed runtime validation.
    #[error("invalid user image input: {reason}")]
    InvalidUserImageInput {
        /// Actionable image validation detail.
        reason: String,
    },

    /// A submitted tool result does not match any pending or resolved call.
    #[error("tool call {call_id} is not pending in session {session_id}")]
    UnknownToolCall {
        /// Session receiving the result.
        session_id: SessionId,
        /// Tool call id that could not be found.
        call_id: ToolCallId,
    },

    /// A bridge result submission did not contain any outcomes.
    #[error("bridge tool result batch is empty in session {session_id}")]
    BridgeToolResultBatchEmpty {
        /// Session receiving the empty result batch.
        session_id: SessionId,
    },

    /// A bridge result submission did not resolve exactly the requested calls.
    #[error(
        "bridge tool result batch does not match pending calls in session {session_id}: expected {expected_call_ids:?}, received {received_call_ids:?}"
    )]
    BridgeToolResultBatchMismatch {
        /// Session receiving the mismatched result batch.
        session_id: SessionId,
        /// Call ids currently waiting for external execution.
        expected_call_ids: Vec<ToolCallId>,
        /// Call ids supplied by the external executor.
        received_call_ids: Vec<ToolCallId>,
    },

    /// A bridge result was submitted for a different runtime-owned batch.
    #[error(
        "bridge tool result batch id does not match the pending batch in session {session_id}: expected {expected_batch_id}, received {received_batch_id}"
    )]
    BridgeToolResultBatchIdMismatch {
        /// Session receiving the stale or mismatched result.
        session_id: SessionId,
        /// Runtime-owned batch id currently awaiting results.
        expected_batch_id: ToolCallBatchId,
        /// Batch id supplied by the host.
        received_batch_id: ToolCallBatchId,
    },

    /// A host result could not be recorded, but the pending call can still be
    /// resolved as a failed tool result so the model loop can recover.
    #[error(
        "bridge tool result was rejected in session {session_id}; the tool call was recorded as failed: {message}"
    )]
    BridgeToolResultRejected {
        /// Session receiving the host result.
        session_id: SessionId,
        /// Original runtime validation or persistence detail.
        message: String,
    },

    /// The run cannot read another message until its current host batch is resolved.
    #[error(
        "agent run has unresolved tool invocations in session {session_id} for batch {batch_id}"
    )]
    AgentRunToolInvocationsPending {
        /// Session whose run is waiting for host results.
        session_id: SessionId,
        /// Batch that must be resolved first.
        batch_id: ToolCallBatchId,
    },

    /// A host submitted results when the run has no active host batch.
    #[error("agent run has no pending tool invocations in session {session_id}")]
    NoPendingAgentRunToolInvocations {
        /// Session receiving the submission.
        session_id: SessionId,
    },

    /// A tool result was submitted after the call had already been resolved.
    #[error("tool call {call_id} is already resolved in session {session_id}")]
    ToolCallAlreadyResolved {
        /// Session receiving the duplicate result.
        session_id: SessionId,
        /// Tool call id that already has a result.
        call_id: ToolCallId,
    },

    /// Runtime construction tried to register the same tool name more than once.
    #[error("tool {name} is already registered")]
    DuplicateToolRegistration {
        /// Duplicate tool name.
        name: ToolName,
    },

    /// Runtime-reserved provider-visible tool name was registered by an application.
    #[error("tool name {name} is reserved by the runtime")]
    ReservedToolName {
        /// Rejected reserved tool name.
        name: ToolName,
    },

    /// Runtime construction received a tool schema that JSON Schema validation cannot compile.
    #[error("tool {name} input schema is invalid: {message}")]
    InvalidToolInputSchema {
        /// Tool with the invalid input schema.
        name: ToolName,
        /// Actionable schema compiler detail.
        message: String,
    },

    /// Runtime construction tried to register a bridge tool without explicit opt-in.
    #[error("bridge tool {name} requires explicit bridge tool opt-in")]
    BridgeToolsNotAllowed {
        /// Bridge tool name.
        name: ToolName,
    },

    /// Tool execution was cancelled before producing a durable result.
    #[error("tool call {call_id} execution was cancelled in session {session_id}")]
    ToolExecutionCancelled {
        /// Session executing the tool call.
        session_id: SessionId,
        /// Tool call id that remained pending.
        call_id: ToolCallId,
    },

    /// Tool executor infrastructure failed before producing a durable result.
    #[error("tool call {call_id} executor failed in session {session_id}: {message}")]
    ToolExecutionFailed {
        /// Session executing the tool call.
        session_id: SessionId,
        /// Tool call id that remained pending.
        call_id: ToolCallId,
        /// Actionable executor failure detail.
        message: String,
    },

    /// A runtime-owned agent run stopped before producing a terminal result.
    #[error("agent run closed for session {session_id}: {message}")]
    AgentRunClosed {
        /// Session whose run ended unexpectedly.
        session_id: SessionId,
        /// Actionable stream lifecycle detail.
        message: &'static str,
    },

    /// An admitted mutating action reported success without internal execution evidence.
    #[error(
        "tool call {call_id} admitted for {action_kind:?} in session {session_id} succeeded without required execution evidence"
    )]
    MissingActionExecutionEvidence {
        /// Session executing the tool call.
        session_id: SessionId,
        /// Tool call id that remained pending.
        call_id: ToolCallId,
        /// Action kind that required internal execution evidence.
        action_kind: ToolActionKind,
    },

    /// A mutating action reached the generic executor path before a commit lifecycle exists.
    #[error(
        "mutating tool action {action_kind:?} for tool call {call_id} in session {session_id} requires an explicit commit lifecycle before generic execution"
    )]
    MutatingActionCommitLifecycleRequired {
        /// Session executing the tool call.
        session_id: SessionId,
        /// Tool call id that remained pending.
        call_id: ToolCallId,
        /// Mutating action kind that must use a commit lifecycle.
        action_kind: ToolActionKind,
    },

    /// A tool result used invalid or blank output content.
    #[error("tool call {call_id} result uses invalid {output_kind:?} output content")]
    UnsupportedToolResultContent {
        /// Tool call identifier for the submitted tool result.
        call_id: ToolCallId,
        /// Submitted output category.
        output_kind: ToolOutputKind,
    },

    /// Transcript item ids are exhausted for this session.
    #[error("transcript item id space is exhausted")]
    TranscriptItemIdExhausted,

    /// Model turn ids are exhausted for this session.
    #[error("model turn id space is exhausted")]
    ModelTurnIdExhausted,

    /// A transcript mutation referenced a model turn that is not recorded.
    #[error("model turn {model_turn_id} is not recorded")]
    UnknownModelTurn { model_turn_id: u64 },

    /// A transcript mutation attempted to change a terminal or incompatible turn.
    #[error("model turn {model_turn_id} cannot {attempted} from its current status")]
    InvalidModelTurnTransition {
        model_turn_id: u64,
        attempted: &'static str,
    },

    /// A pending tool call was not represented in the durable transcript.
    #[error("tool call {call_id} has no originating transcript item")]
    TranscriptToolCallMissing { call_id: ToolCallId },

    /// A core protocol value could not be constructed.
    #[error("core protocol error while constructing runtime state: {source}")]
    Core {
        /// Source core validation error.
        #[from]
        source: CoreError,
    },

    /// Context state could not be constructed or compiled.
    #[error("context state error: {source}")]
    Context {
        /// Source context error.
        #[from]
        source: ContextError,
    },

    /// Checkpoint state could not be inspected or validated.
    #[error("checkpoint state error: {source}")]
    Checkpoint {
        /// Source checkpoint error.
        #[from]
        source: CheckpointError,
    },

    /// Compaction state could not be constructed or applied.
    #[error("compaction state error: {source}")]
    Compaction {
        /// Source compaction error.
        #[from]
        source: CompactionError,
    },

    /// Session persistence failed.
    #[error("session store error: {source}")]
    SessionStore {
        /// Source session store error.
        #[from]
        source: SessionStoreError,
    },

    /// A runtime operation needed a model provider for a role that is not configured.
    #[error("missing model provider for runtime role {role}")]
    MissingModelProvider {
        /// Missing model role.
        role: &'static str,
    },

    /// Compaction model request construction failed.
    #[error("compaction model request error: {message}")]
    CompactionModelRequest {
        /// Actionable model request error.
        message: String,
    },

    /// The configured compaction model cannot accept the primary model's context window.
    #[error(
        "compaction model input window {compactor_window_tokens} tokens is smaller than primary context window {primary_window_tokens} tokens"
    )]
    CompactionModelWindowTooSmall {
        /// Resolved primary model context window.
        primary_window_tokens: u64,
        /// Provider-reported compaction model input window.
        compactor_window_tokens: u64,
    },

    /// The compiled compaction request cannot hold its input and reserved output together.
    #[error(
        "compaction model request estimated input {estimated_input_tokens} tokens plus max output {max_output_tokens} tokens exceeds compaction model window {compactor_window_tokens} tokens"
    )]
    CompactionModelRequestTooLarge {
        /// Deterministic estimate of the compiled provider-neutral request input.
        estimated_input_tokens: u64,
        /// Output ceiling reserved for reasoning and checkpoint text.
        max_output_tokens: u64,
        /// Reported or primary-window-assumed compaction model window.
        compactor_window_tokens: u64,
    },

    /// The compaction model stopped before it produced a complete checkpoint.
    #[error("compaction model output was truncated: {message}")]
    CompactionModelTruncated {
        /// Actionable truncation diagnostic, including the provider's reason.
        message: String,
    },

    /// Compaction model setup failed before a stream was returned.
    #[error("compaction model setup error: {message}")]
    CompactionModelSetup {
        /// Actionable model setup error.
        message: String,
    },

    /// Compaction model stream failed or returned an invalid candidate shape.
    #[error("compaction model stream error: {message}")]
    CompactionModelStream {
        /// Actionable model stream error.
        message: String,
    },

    /// A host-bridged hook invocation is still pending and must be resolved before reading further messages.
    #[error("agent run for session {session_id} has pending hook invocation {invocation_id}")]
    AgentRunHookInvocationPending {
        /// Session whose run has a pending hook invocation.
        session_id: SessionId,
        /// Pending hook invocation identifier.
        invocation_id: crate::HookInvocationId,
    },

    /// A caller attempted to submit a hook decision when no hook invocation is pending.
    #[error("agent run for session {session_id} has no pending hook invocation")]
    NoPendingAgentRunHookInvocation {
        /// Session whose run has no pending hook invocation.
        session_id: SessionId,
    },

    /// A submitted hook decision referenced the wrong invocation identifier.
    #[error(
        "hook invocation id mismatch for session {session_id}: expected {expected_invocation_id}, received {received_invocation_id}"
    )]
    HookInvocationIdMismatch {
        /// Session whose run rejected the hook decision.
        session_id: SessionId,
        /// Active hook invocation identifier.
        expected_invocation_id: crate::HookInvocationId,
        /// Identifier submitted by the caller.
        received_invocation_id: crate::HookInvocationId,
    },

    /// A lifecycle hook failed (fail-closed).
    #[error("hook {hook_point} failed for session {session_id}: {message}")]
    HookFailed {
        /// Session whose hook failed.
        session_id: SessionId,
        /// Hook point that failed.
        hook_point: crate::HookPoint,
        /// Actionable failure detail.
        message: String,
    },

    /// A lifecycle hook was cancelled cooperatively.
    #[error("hook {hook_point} cancelled for session {session_id}")]
    HookCancelled {
        /// Session whose hook was cancelled.
        session_id: SessionId,
        /// Hook point that was cancelled.
        hook_point: crate::HookPoint,
    },
}

impl RuntimeError {
    /// Returns the stable provider-neutral code for this runtime failure.
    #[must_use]
    pub const fn diagnostic_code(&self) -> &'static str {
        match self {
            Self::StepAlreadyActive { .. } => "step_already_active",
            Self::SessionClosed { .. } => "session_closed",
            Self::InvalidStepInput { .. } => "invalid_step_input",
            Self::AgentLoopConfig { .. } => "agent_loop_config",
            Self::ChildRuntimeBuild { .. } => "child_runtime_build",
            Self::InvalidSubagentSelection { .. } => "invalid_subagent_selection",
            Self::Plan { .. } => "plan_error",
            Self::InvalidUserImageInput { .. } => "invalid_user_image_input",
            Self::UnknownToolCall { .. } => "unknown_tool_call",
            Self::BridgeToolResultBatchEmpty { .. } => "bridge_tool_result_batch_empty",
            Self::BridgeToolResultBatchMismatch { .. } => "bridge_tool_result_batch_mismatch",
            Self::BridgeToolResultBatchIdMismatch { .. } => "bridge_tool_result_batch_id_mismatch",
            Self::BridgeToolResultRejected { .. } => "bridge_tool_result_rejected",
            Self::AgentRunToolInvocationsPending { .. } => "agent_run_tool_invocations_pending",
            Self::NoPendingAgentRunToolInvocations { .. } => {
                "no_pending_agent_run_tool_invocations"
            }
            Self::ToolCallAlreadyResolved { .. } => "tool_call_already_resolved",
            Self::DuplicateToolRegistration { .. } => "duplicate_tool_registration",
            Self::ReservedToolName { .. } => "reserved_tool_name",
            Self::InvalidToolInputSchema { .. } => "invalid_tool_input_schema",
            Self::BridgeToolsNotAllowed { .. } => "bridge_tools_not_allowed",
            Self::ToolExecutionCancelled { .. } => "tool_execution_cancelled",
            Self::ToolExecutionFailed { .. } => "tool_execution_failed",
            Self::AgentRunClosed { .. } => "agent_run_closed",
            Self::MissingActionExecutionEvidence { .. } => "missing_action_execution_evidence",
            Self::MutatingActionCommitLifecycleRequired { .. } => {
                "mutating_action_commit_lifecycle_required"
            }
            Self::UnsupportedToolResultContent { .. } => "unsupported_tool_result_content",
            Self::TranscriptItemIdExhausted => "transcript_item_id_exhausted",
            Self::ModelTurnIdExhausted => "model_turn_id_exhausted",
            Self::UnknownModelTurn { .. } => "unknown_model_turn",
            Self::InvalidModelTurnTransition { .. } => "invalid_model_turn_transition",
            Self::TranscriptToolCallMissing { .. } => "transcript_tool_call_missing",
            Self::Core { .. } => "core_error",
            Self::Context { .. } => "context_error",
            Self::Checkpoint { .. } => "checkpoint_error",
            Self::Compaction { .. } => "compaction_error",
            Self::SessionStore {
                source: SessionStoreError::SessionAlreadyReserved { .. },
            } => "session_already_reserved",
            Self::SessionStore { .. } => "session_store",
            Self::MissingModelProvider { .. } => "missing_model_provider",
            Self::CompactionModelRequest { .. } => "compaction_model_request",
            Self::CompactionModelWindowTooSmall { .. } => "compaction_model_window_too_small",
            Self::CompactionModelRequestTooLarge { .. } => "compaction_model_request_too_large",
            Self::CompactionModelTruncated { .. } => "compaction_model_truncated",
            Self::CompactionModelSetup { .. } => "compaction_model_setup",
            Self::CompactionModelStream { .. } => "compaction_model_stream",
            Self::AgentRunHookInvocationPending { .. } => "agent_run_hook_invocation_pending",
            Self::NoPendingAgentRunHookInvocation { .. } => "no_pending_agent_run_hook_invocation",
            Self::HookInvocationIdMismatch { .. } => "hook_invocation_id_mismatch",
            Self::HookFailed { .. } => "hook_failed",
            Self::HookCancelled { .. } => "hook_cancelled",
        }
    }

    /// Returns whether a bridge result error can be corrected by resubmitting
    /// the same active batch. This classification is shared by runtime and
    /// language bindings so a binding cannot terminate a run on a validation
    /// error that the host is expected to fix.
    #[must_use]
    pub fn is_retryable_bridge_tool_result(&self) -> bool {
        matches!(
            self,
            Self::BridgeToolResultBatchEmpty { .. }
                | Self::BridgeToolResultBatchMismatch { .. }
                | Self::BridgeToolResultBatchIdMismatch { .. }
                | Self::UnsupportedToolResultContent { .. }
                | Self::Core {
                    source: CoreError::InvalidToolCallResult { .. }
                }
        )
    }
}