merry-core 0.1.2

Core IDs, schemas, artifacts, events, and error contracts for the Merry agent runtime.
Documentation
//! Internal ordered runtime journal contract.

use crate::{
    ErrorInfo, PendingToolCall, PendingToolCallBatch, PlanDocument, PlanId, PlanModeState,
    PlanReviewDecision, SessionId, SessionUsage, SubagentId, SubagentTaskId, TodoItem, ToolCallId,
    ToolCallResult,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Ordered runtime journal event.
///
/// Ordered execution records and live observations. Transient payloads are
/// delivered to subscribers but excluded from replay and retained run results.
/// Replaceable telemetry, such as output rate, may be coalesced by a stream
/// consumer; semantic records retain their ordered delivery contract. This is
/// not the default SDK/UI event stream.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RuntimeJournalEvent {
    /// Session that emitted the event.
    pub session_id: SessionId,
    /// Monotonic event sequence within the session.
    pub sequence: u64,
    /// Event payload.
    pub payload: RuntimeJournalPayload,
}

impl RuntimeJournalEvent {
    /// Creates a runtime journal event.
    #[must_use]
    pub fn new(session_id: SessionId, sequence: u64, payload: RuntimeJournalPayload) -> Self {
        Self {
            session_id,
            sequence,
            payload,
        }
    }
}

/// Ordered runtime journal payload.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuntimeJournalPayload {
    /// A session was initialized.
    SessionStarted,
    /// A runtime step started.
    StepStarted,
    /// Transient receive-side output throughput; not prompt or ledger state.
    /// Consumers should treat this as replaceable telemetry rather than a
    /// complete history of every intermediate sample.
    ModelOutputRateUpdated {
        rate: Option<crate::ModelOutputRate>,
    },
    /// A model provider attempt started.
    ModelRetryAttemptStarted {
        /// 1-based attempt number.
        attempt: usize,
        /// Maximum attempts configured for this model turn.
        max_attempts: usize,
    },
    /// A retryable model provider failure scheduled another attempt.
    ModelRetryScheduled {
        /// 1-based failed attempt number.
        attempt: usize,
        /// 1-based next attempt number.
        next_attempt: usize,
        /// Maximum attempts configured for this model turn.
        max_attempts: usize,
        /// Delay before the next attempt, in milliseconds.
        delay_ms: u64,
        /// Provider-neutral error category.
        error_kind: String,
    },
    /// A retryable model provider failure exhausted retry budget.
    ModelRetryExhausted {
        /// Number of attempts that ran.
        attempts_run: usize,
        /// Maximum attempts configured for this model turn.
        max_attempts: usize,
        /// Provider-neutral error category.
        error_kind: String,
    },
    /// A runtime step completed.
    StepCompleted,
    /// Automatic context compaction started.
    CompactionStarted,
    /// Automatic context compaction installed a compacted checkpoint.
    CompactionCompleted {
        /// Installed checkpoint id.
        checkpoint_id: String,
        /// Number of history items covered by the new checkpoint.
        covered_history_item_count: usize,
    },
    /// Session usage was updated from a provider-reported model response.
    SessionUsageUpdated { usage: SessionUsage },
    /// Incremental assistant text output from the active model stream.
    ///
    /// This is an ordered progress event. It does not make the text durable or
    /// provider-visible; the final assistant output is still recorded through
    /// [`RuntimeJournalPayload::AssistantOutputRecorded`].
    AssistantOutputDelta { delta: String },
    /// Incremental model reasoning text. Live progress only; it is not durable evidence.
    ReasoningOutputDelta { delta: String },
    /// Assistant text output was durably recorded.
    AssistantOutputRecorded { text: String },
    /// A model requested a tool call that is waiting for runtime policy/execution.
    ToolCallPending { call: PendingToolCall },
    /// A model requested an ordered batch of tool calls in one turn.
    ToolCallBatchPending { batch: PendingToolCallBatch },
    /// A model requested a bridge tool call that must be executed by an external runner.
    BridgeToolCallRequested { call: PendingToolCall },
    /// A pending tool call was resolved with a recorded result.
    ToolCallResolved { result: ToolCallResult },
    /// A runtime-owned final-output tool call recorded structured terminal output.
    FinalOutputRecorded {
        /// Provider-originated call id for the final-output tool call.
        call_id: ToolCallId,
        /// Exact JSON final structured output.
        json: String,
    },
    /// A model used a skill by successfully reading its catalog-listed `SKILL.md`.
    SkillUsed {
        /// Model-visible skill name from `SKILL.md` frontmatter.
        skill_name: String,
        /// Catalog-listed workspace-readable path to the skill body.
        skill_md_path: String,
        /// Tool call that read the skill body.
        tool_call_id: ToolCallId,
    },
    /// A subagent task was accepted for execution.
    SubagentSpawned {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        task_anchor: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        display_name: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        role: Option<String>,
    },
    /// A subagent started executing its assigned task.
    SubagentStarted {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
    },
    /// A subagent reported a provider-neutral status update.
    SubagentStatusChanged {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        status: crate::SubagentStatus,
    },
    /// A subagent completed and reported compact references to its work.
    SubagentCompleted {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        summary: String,
        output_paths: Vec<String>,
        changed_paths: Vec<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        usage: Option<crate::ModelUsage>,
    },
    /// A subagent failed.
    SubagentFailed {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        diagnostic: ErrorInfo,
    },
    /// A subagent was cancelled.
    SubagentCancelled {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        diagnostic: ErrorInfo,
    },
    /// Session Plan Mode transitioned to a new state.
    PlanModeChanged { mode: PlanModeState },
    /// A Markdown plan document was created or updated in this session.
    PlanSaved { plan: PlanDocument },
    /// The agent submitted a Markdown plan and paused for user review.
    PlanApprovalRequested { plan: PlanDocument },
    /// The user approved, requested changes on, or abandoned a submitted plan.
    PlanReviewed {
        plan_id: PlanId,
        decision: PlanReviewDecision,
    },
    /// The session execution checklist was updated.
    TodoListUpdated { items: Vec<TodoItem> },
    /// The runtime was cancelled.
    Cancelled { diagnostic: ErrorInfo },
    /// The runtime failed.
    Failed { diagnostic: ErrorInfo },
}

impl RuntimeJournalPayload {
    /// Whether this live-only observation is excluded from retained execution evidence.
    #[must_use]
    pub const fn is_transient(&self) -> bool {
        matches!(
            self,
            Self::ModelOutputRateUpdated { .. }
                | Self::AssistantOutputDelta { .. }
                | Self::ReasoningOutputDelta { .. }
        )
    }
}