merry-core 0.1.1

Core IDs, schemas, artifacts, events, and error contracts for the Merry agent runtime.
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
//! Public runtime event contract for SDK/UI consumers.

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

/// SDK-facing runtime event.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum RuntimeEvent {
    /// A session was initialized.
    SessionStarted { source: RuntimeEventSource },
    /// A runtime step started.
    StepStarted { source: RuntimeEventSource },
    /// A runtime step completed.
    StepCompleted { source: RuntimeEventSource },
    /// Automatic context compaction started.
    CompactionStarted { source: RuntimeEventSource },
    /// Automatic context compaction installed a compacted checkpoint.
    CompactionCompleted {
        checkpoint_id: String,
        covered_history_item_count: usize,
        source: RuntimeEventSource,
    },
    /// Session usage was updated from a provider-reported model response.
    UsageUpdated {
        usage: SessionUsage,
        source: RuntimeEventSource,
    },
    /// Live or usage-corrected throughput; None clears the active observation.
    ModelOutputRateUpdated {
        rate: Option<crate::ModelOutputRate>,
        source: RuntimeEventSource,
    },
    /// The assistant produced user-facing text.
    AssistantMessage {
        text: String,
        source: RuntimeEventSource,
    },
    /// Incremental assistant text from the active model stream.
    ///
    /// Consumers should treat this as progress and use the following
    /// [`RuntimeEvent::AssistantMessage`] as the durable completion event.
    AssistantMessageDelta {
        delta: String,
        source: RuntimeEventSource,
    },
    /// Incremental model reasoning shown while a turn is thinking.
    ///
    /// This is live progress, like [`RuntimeEvent::AssistantMessageDelta`]. The
    /// following assistant message, tool call, or step completion closes the
    /// thinking block.
    ReasoningDelta {
        delta: String,
        source: RuntimeEventSource,
    },
    /// The model requested a tool call.
    ToolCallStarted {
        call: PendingToolCall,
        source: RuntimeEventSource,
    },
    /// The model requested multiple ordered tool calls in one turn.
    ToolCallBatchStarted {
        batch: PendingToolCallBatch,
        source: RuntimeEventSource,
    },
    /// A tool call finished with a recorded result.
    ToolCallFinished {
        result: ToolCallResult,
        output: Option<ToolOutput>,
        source: RuntimeEventSource,
    },
    /// Incremental live output chunk from an active tool call (e.g. `run_process`).
    ///
    /// Live progress only; durable tool output is recorded through
    /// [`RuntimeEvent::ToolCallFinished`].
    ToolCallOutputDelta {
        call_id: ToolCallId,
        stream: ToolOutputStream,
        delta: String,
        source: RuntimeEventSource,
    },
    /// A final-output contract recorded structured terminal output.
    FinalOutputRecorded {
        call_id: ToolCallId,
        json: String,
        source: RuntimeEventSource,
    },
    /// A model provider attempt started.
    ModelRetryAttemptStarted {
        attempt: usize,
        max_attempts: usize,
        source: RuntimeEventSource,
    },
    /// A retryable model provider failure scheduled another attempt.
    ModelRetryScheduled {
        attempt: usize,
        next_attempt: usize,
        max_attempts: usize,
        delay_ms: u64,
        error_kind: String,
        source: RuntimeEventSource,
    },
    /// A retryable model provider failure exhausted retry budget.
    ModelRetryExhausted {
        attempts_run: usize,
        max_attempts: usize,
        error_kind: String,
        source: RuntimeEventSource,
    },
    /// A model used a skill by reading its catalog-listed `SKILL.md`.
    SkillUsed {
        skill_name: String,
        skill_md_path: String,
        tool_call_id: ToolCallId,
        source: RuntimeEventSource,
    },
    /// 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>,
        source: RuntimeEventSource,
    },
    /// A subagent started executing.
    SubagentStarted {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        source: RuntimeEventSource,
    },
    /// A subagent reported a lifecycle status update.
    SubagentStatusChanged {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        status: SubagentStatus,
        source: RuntimeEventSource,
    },
    /// 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>,
        source: RuntimeEventSource,
    },
    /// A subagent failed.
    SubagentFailed {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        diagnostic: ErrorInfo,
        source: RuntimeEventSource,
    },
    /// A subagent was cancelled.
    SubagentCancelled {
        agent_id: SubagentId,
        task_id: SubagentTaskId,
        diagnostic: ErrorInfo,
        source: RuntimeEventSource,
    },
    /// Session Plan Mode transitioned to a new state.
    PlanModeChanged {
        mode: PlanModeState,
        source: RuntimeEventSource,
    },
    /// A Markdown plan document was created or updated in this session.
    PlanSaved {
        plan: PlanDocument,
        source: RuntimeEventSource,
    },
    /// The agent submitted a Markdown plan and paused for user review.
    PlanApprovalRequested {
        plan: PlanDocument,
        source: RuntimeEventSource,
    },
    /// The user approved, requested changes on, or abandoned a submitted plan.
    PlanReviewed {
        plan_id: PlanId,
        decision: PlanReviewDecision,
        source: RuntimeEventSource,
    },
    /// The session execution checklist was updated.
    TodoListUpdated {
        items: Vec<TodoItem>,
        source: RuntimeEventSource,
    },
    /// The runtime failed.
    RunFailed {
        diagnostic: ErrorInfo,
        source: RuntimeEventSource,
    },
    /// The runtime was cancelled.
    RunCancelled {
        diagnostic: ErrorInfo,
        source: RuntimeEventSource,
    },
    /// Interactive driver state changed.
    InteractiveRunStateChanged { state: InteractiveRunState },
    /// Queued pending inputs became provider-visible together as one turn.
    QueuedInputAccepted { inputs: Vec<QueuedInputView> },
    /// The read-only pending-input queue or its pause state changed.
    QueuedInputsChanged { inputs: QueuedInputsView },
    /// A public runtime stream closed.
    Closed,
}

impl RuntimeEvent {
    /// Whether this live-only observation is excluded from retained run results.
    #[must_use]
    pub const fn is_transient(&self) -> bool {
        matches!(
            self,
            Self::ModelOutputRateUpdated { .. }
                | Self::AssistantMessageDelta { .. }
                | Self::ReasoningDelta { .. }
                | Self::ToolCallOutputDelta { .. }
        )
    }
}

/// Pointer from a public event back to the journal position that produced it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RuntimeEventSource {
    pub session_id: SessionId,
    pub sequence: u64,
}

impl RuntimeEventSource {
    #[must_use]
    pub fn new(session_id: SessionId, sequence: u64) -> Self {
        Self {
            session_id,
            sequence,
        }
    }
}

/// Compact lifecycle status for subagents.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SubagentStatus {
    Queued,
    Running,
    Completed,
    Failed,
    Cancelled,
    Blocked,
}

/// Output stream carrying a live [`RuntimeEvent::ToolCallOutputDelta`] chunk.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ToolOutputStream {
    Stdout,
    Stderr,
}

/// Kind of recorded tool output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ToolOutputKind {
    /// UTF-8 plain text.
    Text,
    /// Serialized JSON text.
    Json,
}

/// Complete public text or JSON output for a tool result.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ToolOutput {
    Text { text: String },
    Json { json: String },
}

impl ToolOutput {
    /// Creates UTF-8 text tool output.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text { text: text.into() }
    }

    /// Creates serialized JSON tool output.
    #[must_use]
    pub fn json(json: impl Into<String>) -> Self {
        Self::Json { json: json.into() }
    }

    /// Returns the output kind.
    #[must_use]
    pub const fn kind(&self) -> ToolOutputKind {
        match self {
            Self::Text { .. } => ToolOutputKind::Text,
            Self::Json { .. } => ToolOutputKind::Json,
        }
    }

    /// Borrows the exact UTF-8 payload.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Text { text } | Self::Json { json: text } => text,
        }
    }

    /// Returns the exact UTF-8 byte length.
    #[must_use]
    pub fn byte_len(&self) -> usize {
        self.as_str().len()
    }

    /// Creates a bounded UTF-8-safe preview without cloning the full payload.
    #[must_use]
    pub fn bounded_preview(&self, max_bytes: usize) -> ToolOutputPreview {
        let value = self.as_str();
        let byte_length = value.len();
        if byte_length <= max_bytes {
            return ToolOutputPreview::new(self.kind(), value.to_owned(), false, byte_length);
        }
        let mut end = 0;
        for (index, character) in value.char_indices() {
            let next = index + character.len_utf8();
            if next > max_bytes {
                break;
            }
            end = next;
        }
        ToolOutputPreview::new(self.kind(), value[..end].to_owned(), true, byte_length)
    }
}

/// Bounded UTF-8 preview of a recorded tool output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ToolOutputPreview {
    kind: ToolOutputKind,
    content: String,
    truncated: bool,
    byte_length: usize,
}

impl ToolOutputPreview {
    /// Creates a bounded tool output preview.
    #[must_use]
    pub fn new(kind: ToolOutputKind, content: String, truncated: bool, byte_length: usize) -> Self {
        Self {
            kind,
            content,
            truncated,
            byte_length,
        }
    }

    /// Returns the tool output kind.
    #[must_use]
    pub const fn kind(&self) -> ToolOutputKind {
        self.kind
    }

    /// Borrows the bounded UTF-8 preview content.
    #[must_use]
    pub fn content(&self) -> &str {
        &self.content
    }

    /// Returns whether the exact output exceeded the preview bound.
    #[must_use]
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Returns the exact byte length of the full recorded output.
    #[must_use]
    pub const fn byte_length(&self) -> usize {
        self.byte_length
    }
}

/// Lightweight public summary of an attached image without raw bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ImageSummary {
    label: String,
    width: u32,
    height: u32,
}

impl ImageSummary {
    /// Creates an image summary.
    #[must_use]
    pub fn new(label: impl Into<String>, width: u32, height: u32) -> Self {
        Self {
            label: label.into(),
            width,
            height,
        }
    }

    /// Borrows the human-readable image label.
    #[must_use]
    pub fn label(&self) -> &str {
        &self.label
    }

    /// Returns decoded image width in pixels.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Returns decoded image height in pixels.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }
}

/// Public interactive driver state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InteractiveRunState {
    WaitingForInput,
    RunningModel,
    RunningTool,
    Interrupting,
    Closed,
}

/// Read-only public view of one pending queued input.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QueuedInputView {
    /// Stable runtime-assigned identifier for targeted edit or removal.
    pub id: u64,
    /// Message text waiting to be sent.
    pub text: String,
    /// Zero-based position in the pending queue.
    pub position: usize,
}

/// Read-only public view of the single pending-input queue.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct QueuedInputsView {
    /// Pending inputs waiting to be dispatched together at the next boundary.
    pub items: Vec<QueuedInputView>,
    /// Whether automatic dispatch is paused (e.g., while editing a pending item
    /// or after an interrupt).
    pub paused: bool,
}