modelrelay 6.5.0

Rust SDK for the ModelRelay API
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
//! Workflow run event types.
//!
//! This module contains types for workflow run events:
//! - `RunEventV0` - A run event with envelope and payload
//! - `RunEventEnvelope` - Common envelope fields for all events
//! - `RunEventPayload` - Event-specific payload data
//! - `RunEventTypeV0` - Type discriminator for events
//! - `StreamEventKind` - Kind of streaming event from LLM
//! - Various LLM call and tool call types

use std::fmt;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use super::ids::{ModelId, NodeId, PlanHash, RequestId, RunId};
use super::run::{NodeErrorV0, PayloadArtifactV0};
use crate::errors::{Error, Result, ValidationError};
use crate::identifiers::ProviderId;

/// Envelope version for run events. Schema specifies const "v2".
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EnvelopeVersion {
    #[serde(rename = "v2")]
    #[default]
    V2,
}

impl EnvelopeVersion {
    pub fn as_str(&self) -> &'static str {
        match self {
            EnvelopeVersion::V2 => "v2",
        }
    }
}

impl fmt::Display for EnvelopeVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Run event type discriminator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum RunEventTypeV0 {
    #[serde(rename = "run_compiled")]
    RunCompiled,
    #[serde(rename = "run_started")]
    RunStarted,
    #[serde(rename = "run_completed")]
    RunCompleted,
    #[serde(rename = "run_failed")]
    RunFailed,
    #[serde(rename = "run_canceled")]
    RunCanceled,
    #[serde(rename = "node_llm_call")]
    NodeLLMCall,
    #[serde(rename = "node_tool_call")]
    NodeToolCall,
    #[serde(rename = "node_tool_result")]
    NodeToolResult,
    #[serde(rename = "node_waiting")]
    NodeWaiting,
    #[serde(rename = "node_user_ask")]
    NodeUserAsk,
    #[serde(rename = "node_user_answer")]
    NodeUserAnswer,
    #[serde(rename = "node_started")]
    NodeStarted,
    #[serde(rename = "node_succeeded")]
    NodeSucceeded,
    #[serde(rename = "node_failed")]
    NodeFailed,
    #[serde(rename = "node_output_delta")]
    NodeOutputDelta,
    #[serde(rename = "node_output")]
    NodeOutput,
}

/// Stream event kind from an LLM provider.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum StreamEventKind {
    MessageStart,
    MessageDelta,
    MessageStop,
    ToolUseStart,
    ToolUseDelta,
    ToolUseStop,
    /// Unknown event kind for forward compatibility.
    #[serde(other)]
    Unknown,
}

/// Delta output from a streaming node.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeOutputDeltaV0 {
    pub kind: StreamEventKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text_delta: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Token usage for an LLM call.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TokenUsageV0 {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_tokens: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total_tokens: Option<u64>,
}

/// LLM call event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeLLMCallV0 {
    pub step: u64,
    pub request_id: RequestId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<ProviderId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<ModelId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<TokenUsageV0>,
}

/// Tool call data (arguments optional).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCallV0 {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<String>,
}

/// Tool call data with required arguments.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolCallWithArgumentsV0 {
    pub id: String,
    pub name: String,
    pub arguments: String,
}

/// Tool call event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeToolCallV0 {
    pub step: u64,
    pub request_id: RequestId,
    pub tool_call: ToolCallWithArgumentsV0,
}

/// Tool result event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeToolResultV0 {
    pub step: u64,
    pub request_id: RequestId,
    pub tool_call: ToolCallV0,
    pub output: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Pending tool call awaiting result.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PendingToolCallV0 {
    pub tool_call: ToolCallWithArgumentsV0,
}

/// Node waiting event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeWaitingV0 {
    pub step: u64,
    pub request_id: RequestId,
    pub pending_tool_calls: Vec<PendingToolCallV0>,
    pub reason: String,
}

/// User ask option for user.ask.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct UserAskOptionV0 {
    pub label: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
}

/// User ask event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeUserAskV0 {
    pub step: u64,
    pub request_id: RequestId,
    pub tool_call: ToolCallWithArgumentsV0,
    pub question: String,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub options: Vec<UserAskOptionV0>,
    pub allow_freeform: bool,
}

/// User answer event data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NodeUserAnswerV0 {
    pub step: u64,
    pub request_id: RequestId,
    pub tool_call: ToolCallV0,
    pub answer: String,
    pub is_freeform: bool,
}

/// Common envelope fields for all run events.
///
/// These fields are present in every event and can be accessed directly
/// via `event.envelope.run_id` instead of pattern matching.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RunEventEnvelope {
    #[serde(default)]
    pub envelope_version: EnvelopeVersion,
    pub run_id: RunId,
    pub seq: u64,
    pub ts: DateTime<Utc>,
}

/// Event-specific payload data.
///
/// Each variant contains only the fields unique to that event type.
/// Common fields (envelope_version, run_id, seq, ts) are in `RunEventEnvelope`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum RunEventPayload {
    #[serde(rename = "run_compiled")]
    RunCompiled { plan_hash: PlanHash },

    #[serde(rename = "run_started")]
    RunStarted { plan_hash: PlanHash },

    #[serde(rename = "run_completed")]
    RunCompleted {
        plan_hash: PlanHash,
        outputs: PayloadArtifactV0,
    },

    #[serde(rename = "run_failed")]
    RunFailed {
        plan_hash: PlanHash,
        error: NodeErrorV0,
    },

    #[serde(rename = "run_canceled")]
    RunCanceled {
        plan_hash: PlanHash,
        error: NodeErrorV0,
    },

    #[serde(rename = "node_started")]
    NodeStarted { node_id: NodeId },

    #[serde(rename = "node_succeeded")]
    NodeSucceeded { node_id: NodeId },

    #[serde(rename = "node_failed")]
    NodeFailed { node_id: NodeId, error: NodeErrorV0 },

    #[serde(rename = "node_llm_call")]
    NodeLLMCall {
        node_id: NodeId,
        llm_call: NodeLLMCallV0,
    },

    #[serde(rename = "node_tool_call")]
    NodeToolCall {
        node_id: NodeId,
        tool_call: NodeToolCallV0,
    },

    #[serde(rename = "node_tool_result")]
    NodeToolResult {
        node_id: NodeId,
        tool_result: NodeToolResultV0,
    },

    #[serde(rename = "node_waiting")]
    NodeWaiting {
        node_id: NodeId,
        waiting: NodeWaitingV0,
    },

    #[serde(rename = "node_user_ask")]
    NodeUserAsk {
        node_id: NodeId,
        user_ask: NodeUserAskV0,
    },

    #[serde(rename = "node_user_answer")]
    NodeUserAnswer {
        node_id: NodeId,
        user_answer: NodeUserAnswerV0,
    },

    #[serde(rename = "node_output_delta")]
    NodeOutputDelta {
        node_id: NodeId,
        delta: NodeOutputDeltaV0,
    },

    #[serde(rename = "node_output")]
    NodeOutput {
        node_id: NodeId,
        output: PayloadArtifactV0,
    },
}

/// A run event with envelope metadata and payload.
///
/// The envelope contains common fields (envelope_version, run_id, seq, ts)
/// that are present in every event. The payload contains event-specific data.
///
/// # Example
/// ```ignore
/// // Direct field access (no pattern matching needed)
/// let run_id = event.envelope.run_id;
/// let seq = event.envelope.seq;
///
/// // Pattern match only for payload-specific data
/// match &event.payload {
///     RunEventPayload::RunCompleted { outputs, .. } => {
///         println!("Run completed with {} bytes", outputs.info.bytes);
///     }
///     _ => {}
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RunEventV0 {
    /// Common envelope fields (envelope_version, run_id, seq, ts)
    #[serde(flatten)]
    pub envelope: RunEventEnvelope,
    /// Event-specific payload
    #[serde(flatten)]
    pub payload: RunEventPayload,
}

impl RunEventV0 {
    /// Returns the envelope version.
    pub fn envelope_version(&self) -> EnvelopeVersion {
        self.envelope.envelope_version
    }

    /// Returns the run ID.
    pub fn run_id(&self) -> &RunId {
        &self.envelope.run_id
    }

    /// Returns the sequence number.
    pub fn seq(&self) -> u64 {
        self.envelope.seq
    }

    /// Returns the timestamp.
    pub fn ts(&self) -> DateTime<Utc> {
        self.envelope.ts
    }

    /// Validates the run event.
    /// Note: envelope_version is now an enum (EnvelopeVersion::V2), so invalid
    /// versions are caught at deserialization time rather than validation time.
    pub fn validate(&self) -> Result<()> {
        if self.envelope.seq < 1 {
            return Err(Error::Validation(ValidationError::new(
                "run event seq must be >= 1",
            )));
        }

        match &self.payload {
            RunEventPayload::NodeOutput { output, .. } => {
                if output.info.included {
                    return Err(Error::Validation(ValidationError::new(
                        "node_output output.info.included must be false",
                    )));
                }
            }
            RunEventPayload::RunCompleted { outputs, .. } => {
                if outputs.info.included {
                    return Err(Error::Validation(ValidationError::new(
                        "run_completed outputs.info.included must be false",
                    )));
                }
            }
            RunEventPayload::NodeOutputDelta { delta, .. } => {
                if delta.kind == StreamEventKind::Unknown {
                    return Err(Error::Validation(ValidationError::new(
                        "node_output_delta delta.kind is required",
                    )));
                }
            }
            RunEventPayload::NodeWaiting { waiting, .. } => {
                // step is u64, so always >= 0
                if waiting.request_id.0.is_nil() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_waiting waiting.request_id is required",
                    )));
                }
                if waiting.pending_tool_calls.is_empty() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_waiting waiting.pending_tool_calls is required",
                    )));
                }
                if waiting.reason.trim().is_empty() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_waiting waiting.reason is required",
                    )));
                }
                for call in &waiting.pending_tool_calls {
                    if call.tool_call.id.trim().is_empty() || call.tool_call.name.trim().is_empty()
                    {
                        return Err(Error::Validation(ValidationError::new(
                            "node_waiting waiting.pending_tool_calls items must include tool_call.id and tool_call.name",
                        )));
                    }
                }
            }
            RunEventPayload::NodeUserAsk { user_ask, .. } => {
                if user_ask.request_id.0.is_nil() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_ask user_ask.request_id is required",
                    )));
                }
                if user_ask.tool_call.id.trim().is_empty()
                    || user_ask.tool_call.name.trim().is_empty()
                {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_ask user_ask.tool_call.id and tool_call.name are required",
                    )));
                }
                if user_ask.question.trim().is_empty() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_ask user_ask.question is required",
                    )));
                }
            }
            RunEventPayload::NodeUserAnswer { user_answer, .. } => {
                if user_answer.request_id.0.is_nil() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_answer user_answer.request_id is required",
                    )));
                }
                if user_answer.tool_call.id.trim().is_empty()
                    || user_answer.tool_call.name.trim().is_empty()
                {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_answer user_answer.tool_call.id and tool_call.name are required",
                    )));
                }
                if user_answer.answer.trim().is_empty() {
                    return Err(Error::Validation(ValidationError::new(
                        "node_user_answer user_answer.answer is required",
                    )));
                }
            }
            _ => {}
        }

        Ok(())
    }
}