Skip to main content

merry_core/
runtime_event.rs

1//! Public runtime event contract for SDK/UI consumers.
2
3use crate::{
4    ErrorInfo, PendingToolCall, PendingToolCallBatch, PlanDocument, PlanId, PlanModeState,
5    PlanReviewDecision, SessionId, SessionUsage, SubagentId, SubagentTaskId, TodoItem, ToolCallId,
6    ToolCallResult,
7};
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10
11/// SDK-facing runtime event.
12#[non_exhaustive]
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
14#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
15pub enum RuntimeEvent {
16    /// A session was initialized.
17    SessionStarted { source: RuntimeEventSource },
18    /// A runtime step started.
19    StepStarted { source: RuntimeEventSource },
20    /// A runtime step completed.
21    StepCompleted { source: RuntimeEventSource },
22    /// Automatic context compaction started.
23    CompactionStarted { source: RuntimeEventSource },
24    /// Automatic context compaction installed a compacted checkpoint.
25    CompactionCompleted {
26        checkpoint_id: String,
27        covered_history_item_count: usize,
28        source: RuntimeEventSource,
29    },
30    /// Session usage was updated from a provider-reported model response.
31    UsageUpdated {
32        usage: SessionUsage,
33        source: RuntimeEventSource,
34    },
35    /// Live or usage-corrected throughput; None clears the active observation.
36    ModelOutputRateUpdated {
37        rate: Option<crate::ModelOutputRate>,
38        source: RuntimeEventSource,
39    },
40    /// The assistant produced user-facing text.
41    AssistantMessage {
42        text: String,
43        source: RuntimeEventSource,
44    },
45    /// Incremental assistant text from the active model stream.
46    ///
47    /// Consumers should treat this as progress and use the following
48    /// [`RuntimeEvent::AssistantMessage`] as the durable completion event.
49    AssistantMessageDelta {
50        delta: String,
51        source: RuntimeEventSource,
52    },
53    /// Incremental model reasoning shown while a turn is thinking.
54    ///
55    /// This is live progress, like [`RuntimeEvent::AssistantMessageDelta`]. The
56    /// following assistant message, tool call, or step completion closes the
57    /// thinking block.
58    ReasoningDelta {
59        delta: String,
60        source: RuntimeEventSource,
61    },
62    /// The model requested a tool call.
63    ToolCallStarted {
64        call: PendingToolCall,
65        source: RuntimeEventSource,
66    },
67    /// The model requested multiple ordered tool calls in one turn.
68    ToolCallBatchStarted {
69        batch: PendingToolCallBatch,
70        source: RuntimeEventSource,
71    },
72    /// A tool call finished with a recorded result.
73    ToolCallFinished {
74        result: ToolCallResult,
75        output: Option<ToolOutput>,
76        source: RuntimeEventSource,
77    },
78    /// Incremental live output chunk from an active tool call (e.g. `run_process`).
79    ///
80    /// Live progress only; durable tool output is recorded through
81    /// [`RuntimeEvent::ToolCallFinished`].
82    ToolCallOutputDelta {
83        call_id: ToolCallId,
84        stream: ToolOutputStream,
85        delta: String,
86        source: RuntimeEventSource,
87    },
88    /// A final-output contract recorded structured terminal output.
89    FinalOutputRecorded {
90        call_id: ToolCallId,
91        json: String,
92        source: RuntimeEventSource,
93    },
94    /// A model provider attempt started.
95    ModelRetryAttemptStarted {
96        attempt: usize,
97        max_attempts: usize,
98        source: RuntimeEventSource,
99    },
100    /// A retryable model provider failure scheduled another attempt.
101    ModelRetryScheduled {
102        attempt: usize,
103        next_attempt: usize,
104        max_attempts: usize,
105        delay_ms: u64,
106        error_kind: String,
107        source: RuntimeEventSource,
108    },
109    /// A retryable model provider failure exhausted retry budget.
110    ModelRetryExhausted {
111        attempts_run: usize,
112        max_attempts: usize,
113        error_kind: String,
114        source: RuntimeEventSource,
115    },
116    /// A model used a skill by reading its catalog-listed `SKILL.md`.
117    SkillUsed {
118        skill_name: String,
119        skill_md_path: String,
120        tool_call_id: ToolCallId,
121        source: RuntimeEventSource,
122    },
123    /// A subagent task was accepted for execution.
124    SubagentSpawned {
125        agent_id: SubagentId,
126        task_id: SubagentTaskId,
127        task_anchor: String,
128        #[serde(default, skip_serializing_if = "Option::is_none")]
129        display_name: Option<String>,
130        #[serde(default, skip_serializing_if = "Option::is_none")]
131        role: Option<String>,
132        source: RuntimeEventSource,
133    },
134    /// A subagent started executing.
135    SubagentStarted {
136        agent_id: SubagentId,
137        task_id: SubagentTaskId,
138        source: RuntimeEventSource,
139    },
140    /// A subagent reported a lifecycle status update.
141    SubagentStatusChanged {
142        agent_id: SubagentId,
143        task_id: SubagentTaskId,
144        status: SubagentStatus,
145        source: RuntimeEventSource,
146    },
147    /// A subagent completed and reported compact references to its work.
148    SubagentCompleted {
149        agent_id: SubagentId,
150        task_id: SubagentTaskId,
151        summary: String,
152        output_paths: Vec<String>,
153        changed_paths: Vec<String>,
154        #[serde(default, skip_serializing_if = "Option::is_none")]
155        usage: Option<crate::ModelUsage>,
156        source: RuntimeEventSource,
157    },
158    /// A subagent failed.
159    SubagentFailed {
160        agent_id: SubagentId,
161        task_id: SubagentTaskId,
162        diagnostic: ErrorInfo,
163        source: RuntimeEventSource,
164    },
165    /// A subagent was cancelled.
166    SubagentCancelled {
167        agent_id: SubagentId,
168        task_id: SubagentTaskId,
169        diagnostic: ErrorInfo,
170        source: RuntimeEventSource,
171    },
172    /// Session Plan Mode transitioned to a new state.
173    PlanModeChanged {
174        mode: PlanModeState,
175        source: RuntimeEventSource,
176    },
177    /// A Markdown plan document was created or updated in this session.
178    PlanSaved {
179        plan: PlanDocument,
180        source: RuntimeEventSource,
181    },
182    /// The agent submitted a Markdown plan and paused for user review.
183    PlanApprovalRequested {
184        plan: PlanDocument,
185        source: RuntimeEventSource,
186    },
187    /// The user approved, requested changes on, or abandoned a submitted plan.
188    PlanReviewed {
189        plan_id: PlanId,
190        decision: PlanReviewDecision,
191        source: RuntimeEventSource,
192    },
193    /// The session execution checklist was updated.
194    TodoListUpdated {
195        items: Vec<TodoItem>,
196        source: RuntimeEventSource,
197    },
198    /// The runtime failed.
199    RunFailed {
200        diagnostic: ErrorInfo,
201        source: RuntimeEventSource,
202    },
203    /// The runtime was cancelled.
204    RunCancelled {
205        diagnostic: ErrorInfo,
206        source: RuntimeEventSource,
207    },
208    /// Interactive driver state changed.
209    InteractiveRunStateChanged { state: InteractiveRunState },
210    /// Queued pending inputs became provider-visible together as one turn.
211    QueuedInputAccepted { inputs: Vec<QueuedInputView> },
212    /// The read-only pending-input queue or its pause state changed.
213    QueuedInputsChanged { inputs: QueuedInputsView },
214    /// A public runtime stream closed.
215    Closed,
216}
217
218impl RuntimeEvent {
219    /// Whether this live-only observation is excluded from retained run results.
220    #[must_use]
221    pub const fn is_transient(&self) -> bool {
222        matches!(
223            self,
224            Self::ModelOutputRateUpdated { .. }
225                | Self::AssistantMessageDelta { .. }
226                | Self::ReasoningDelta { .. }
227                | Self::ToolCallOutputDelta { .. }
228        )
229    }
230}
231
232/// Pointer from a public event back to the journal position that produced it.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
234#[serde(deny_unknown_fields)]
235pub struct RuntimeEventSource {
236    pub session_id: SessionId,
237    pub sequence: u64,
238}
239
240impl RuntimeEventSource {
241    #[must_use]
242    pub fn new(session_id: SessionId, sequence: u64) -> Self {
243        Self {
244            session_id,
245            sequence,
246        }
247    }
248}
249
250/// Compact lifecycle status for subagents.
251#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
252#[serde(rename_all = "snake_case")]
253pub enum SubagentStatus {
254    Queued,
255    Running,
256    Completed,
257    Failed,
258    Cancelled,
259    Blocked,
260}
261
262/// Output stream carrying a live [`RuntimeEvent::ToolCallOutputDelta`] chunk.
263#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
264#[serde(rename_all = "snake_case")]
265pub enum ToolOutputStream {
266    Stdout,
267    Stderr,
268}
269
270/// Kind of recorded tool output.
271#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
272#[serde(rename_all = "snake_case")]
273pub enum ToolOutputKind {
274    /// UTF-8 plain text.
275    Text,
276    /// Serialized JSON text.
277    Json,
278}
279
280/// Complete public text or JSON output for a tool result.
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
282#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
283pub enum ToolOutput {
284    Text { text: String },
285    Json { json: String },
286}
287
288impl ToolOutput {
289    /// Creates UTF-8 text tool output.
290    #[must_use]
291    pub fn text(text: impl Into<String>) -> Self {
292        Self::Text { text: text.into() }
293    }
294
295    /// Creates serialized JSON tool output.
296    #[must_use]
297    pub fn json(json: impl Into<String>) -> Self {
298        Self::Json { json: json.into() }
299    }
300
301    /// Returns the output kind.
302    #[must_use]
303    pub const fn kind(&self) -> ToolOutputKind {
304        match self {
305            Self::Text { .. } => ToolOutputKind::Text,
306            Self::Json { .. } => ToolOutputKind::Json,
307        }
308    }
309
310    /// Borrows the exact UTF-8 payload.
311    #[must_use]
312    pub fn as_str(&self) -> &str {
313        match self {
314            Self::Text { text } | Self::Json { json: text } => text,
315        }
316    }
317
318    /// Returns the exact UTF-8 byte length.
319    #[must_use]
320    pub fn byte_len(&self) -> usize {
321        self.as_str().len()
322    }
323
324    /// Creates a bounded UTF-8-safe preview without cloning the full payload.
325    #[must_use]
326    pub fn bounded_preview(&self, max_bytes: usize) -> ToolOutputPreview {
327        let value = self.as_str();
328        let byte_length = value.len();
329        if byte_length <= max_bytes {
330            return ToolOutputPreview::new(self.kind(), value.to_owned(), false, byte_length);
331        }
332        let mut end = 0;
333        for (index, character) in value.char_indices() {
334            let next = index + character.len_utf8();
335            if next > max_bytes {
336                break;
337            }
338            end = next;
339        }
340        ToolOutputPreview::new(self.kind(), value[..end].to_owned(), true, byte_length)
341    }
342}
343
344/// Bounded UTF-8 preview of a recorded tool output.
345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
346#[serde(deny_unknown_fields)]
347pub struct ToolOutputPreview {
348    kind: ToolOutputKind,
349    content: String,
350    truncated: bool,
351    byte_length: usize,
352}
353
354impl ToolOutputPreview {
355    /// Creates a bounded tool output preview.
356    #[must_use]
357    pub fn new(kind: ToolOutputKind, content: String, truncated: bool, byte_length: usize) -> Self {
358        Self {
359            kind,
360            content,
361            truncated,
362            byte_length,
363        }
364    }
365
366    /// Returns the tool output kind.
367    #[must_use]
368    pub const fn kind(&self) -> ToolOutputKind {
369        self.kind
370    }
371
372    /// Borrows the bounded UTF-8 preview content.
373    #[must_use]
374    pub fn content(&self) -> &str {
375        &self.content
376    }
377
378    /// Returns whether the exact output exceeded the preview bound.
379    #[must_use]
380    pub const fn truncated(&self) -> bool {
381        self.truncated
382    }
383
384    /// Returns the exact byte length of the full recorded output.
385    #[must_use]
386    pub const fn byte_length(&self) -> usize {
387        self.byte_length
388    }
389}
390
391/// Lightweight public summary of an attached image without raw bytes.
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
393#[serde(deny_unknown_fields)]
394pub struct ImageSummary {
395    label: String,
396    width: u32,
397    height: u32,
398}
399
400impl ImageSummary {
401    /// Creates an image summary.
402    #[must_use]
403    pub fn new(label: impl Into<String>, width: u32, height: u32) -> Self {
404        Self {
405            label: label.into(),
406            width,
407            height,
408        }
409    }
410
411    /// Borrows the human-readable image label.
412    #[must_use]
413    pub fn label(&self) -> &str {
414        &self.label
415    }
416
417    /// Returns decoded image width in pixels.
418    #[must_use]
419    pub const fn width(&self) -> u32 {
420        self.width
421    }
422
423    /// Returns decoded image height in pixels.
424    #[must_use]
425    pub const fn height(&self) -> u32 {
426        self.height
427    }
428}
429
430/// Public interactive driver state.
431#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
432#[serde(rename_all = "snake_case")]
433pub enum InteractiveRunState {
434    WaitingForInput,
435    RunningModel,
436    RunningTool,
437    Interrupting,
438    Closed,
439}
440
441/// Read-only public view of one pending queued input.
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
443#[serde(deny_unknown_fields)]
444pub struct QueuedInputView {
445    /// Stable runtime-assigned identifier for targeted edit or removal.
446    pub id: u64,
447    /// Message text waiting to be sent.
448    pub text: String,
449    /// Zero-based position in the pending queue.
450    pub position: usize,
451}
452
453/// Read-only public view of the single pending-input queue.
454#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
455#[serde(deny_unknown_fields)]
456pub struct QueuedInputsView {
457    /// Pending inputs waiting to be dispatched together at the next boundary.
458    pub items: Vec<QueuedInputView>,
459    /// Whether automatic dispatch is paused (e.g., while editing a pending item
460    /// or after an interrupt).
461    pub paused: bool,
462}