merry-core 0.1.2

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
//! Runtime event protocol vocabulary.

use crate::CoreError;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, de};
use std::collections::BTreeMap;

const MAX_DIAGNOSTIC_CODE_LEN: usize = 128;
const MAX_DIAGNOSTIC_MESSAGE_LEN: usize = 4096;
const MAX_ERROR_HINT_LEN: usize = 512;
const MAX_ERROR_CONTEXT_VALUE_LEN: usize = 512;

const ALLOWED_ERROR_CONTEXT_KEYS: &[&str] = &[
    "session_id",
    "turn_id",
    "call_id",
    "tool_name",
    "provider_name",
    "model_role",
    "config_path",
    "field_path",
    "checkpoint_id",
    "http_status",
    "exit_code",
];

/// Serializable runtime diagnostic.
///
/// This type carries stable diagnostic text only; it does not serialize Rust
/// error internals such as source chains or backtraces.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ErrorInfo {
    /// Stable diagnostic code or category.
    code: String,
    /// Human-readable diagnostic message.
    message: String,
}

impl ErrorInfo {
    /// Creates a validated serializable diagnostic.
    pub fn new(code: &str, message: &str) -> Result<Self, CoreError> {
        validate_diagnostic_code(code)?;
        validate_diagnostic_message(message)?;
        Ok(Self {
            code: code.to_owned(),
            message: message.to_owned(),
        })
    }

    /// Borrows the stable diagnostic code or category.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

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

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ErrorInfoWire {
    code: String,
    message: String,
}

impl<'de> Deserialize<'de> for ErrorInfo {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = ErrorInfoWire::deserialize(deserializer)?;
        Self::new(&wire.code, &wire.message).map_err(de::Error::custom)
    }
}

/// Stable SDK-facing error domain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MerryErrorDomain {
    /// Configuration loading, parsing, or validation failed.
    Config,
    /// A model/provider adapter failed.
    Provider,
    /// Runtime orchestration failed.
    Runtime,
    /// Tool declaration, dispatch, or execution failed.
    Tool,
    /// A runtime policy rejected or blocked work.
    Policy,
    /// Context compilation or context budget handling failed.
    Context,
    /// Compaction failed or produced invalid state.
    Compaction,
    /// Sandbox execution or permission handling failed.
    Sandbox,
    /// An internal invariant failed.
    Internal,
}

/// Stable SDK-facing retry guidance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum MerryRetryability {
    /// The operation may succeed if retried without user changes.
    Retryable,
    /// Retrying the same operation is not expected to help.
    NotRetryable,
    /// The user must change input, configuration, or permissions before retrying.
    UserActionRequired,
    /// The operation stopped because cancellation was requested or observed.
    Cancelled,
    /// Retry behavior is unknown.
    Unknown,
}

/// Stable SDK-facing diagnostic metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct MerryErrorInfo {
    /// Stable SDK-facing diagnostic code.
    code: String,
    /// Provider-neutral error domain.
    domain: MerryErrorDomain,
    /// Human-readable diagnostic message.
    message: String,
    /// Optional actionable hint.
    hint: Option<String>,
    /// Provider-neutral retry guidance.
    retryability: MerryRetryability,
    /// Bounded non-sensitive context values.
    context: BTreeMap<String, String>,
}

impl MerryErrorInfo {
    /// Starts building stable SDK-facing diagnostic metadata.
    #[must_use]
    pub fn builder(
        code: &str,
        domain: MerryErrorDomain,
        message: &str,
        retryability: MerryRetryability,
    ) -> MerryErrorInfoBuilder {
        MerryErrorInfoBuilder {
            code: code.to_owned(),
            domain,
            message: message.to_owned(),
            hint: None,
            retryability,
            context: BTreeMap::new(),
        }
    }

    /// Borrows the stable SDK-facing diagnostic code.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Borrows the provider-neutral error domain.
    #[must_use]
    pub fn domain(&self) -> &MerryErrorDomain {
        &self.domain
    }

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

    /// Borrows the optional actionable hint.
    #[must_use]
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }

    /// Borrows the provider-neutral retry guidance.
    #[must_use]
    pub fn retryability(&self) -> &MerryRetryability {
        &self.retryability
    }

    /// Borrows the bounded non-sensitive context values.
    #[must_use]
    pub fn context(&self) -> &BTreeMap<String, String> {
        &self.context
    }
}

/// Builder for stable SDK-facing diagnostic metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MerryErrorInfoBuilder {
    code: String,
    domain: MerryErrorDomain,
    message: String,
    hint: Option<String>,
    retryability: MerryRetryability,
    context: BTreeMap<String, String>,
}

impl MerryErrorInfoBuilder {
    /// Adds an actionable hint.
    #[must_use]
    pub fn hint(mut self, hint: &str) -> Self {
        self.hint = Some(hint.to_owned());
        self
    }

    /// Adds bounded non-sensitive context metadata.
    #[must_use]
    pub fn context(mut self, key: &str, value: &str) -> Self {
        self.context.insert(key.to_owned(), value.to_owned());
        self
    }

    /// Builds validated SDK-facing diagnostic metadata.
    pub fn build(self) -> Result<MerryErrorInfo, CoreError> {
        validate_diagnostic_code(&self.code)?;
        validate_diagnostic_message(&self.message)?;
        validate_error_hint(self.hint.as_deref())?;
        validate_error_context(&self.context)?;

        Ok(MerryErrorInfo {
            code: self.code,
            domain: self.domain,
            message: self.message,
            hint: self.hint,
            retryability: self.retryability,
            context: self.context,
        })
    }
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct MerryErrorInfoWire {
    code: String,
    domain: MerryErrorDomain,
    message: String,
    hint: Option<String>,
    retryability: MerryRetryability,
    context: BTreeMap<String, String>,
}

impl<'de> Deserialize<'de> for MerryErrorInfo {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = MerryErrorInfoWire::deserialize(deserializer)?;
        MerryErrorInfo::builder(&wire.code, wire.domain, &wire.message, wire.retryability)
            .maybe_hint(wire.hint)
            .context_map(wire.context)
            .build()
            .map_err(de::Error::custom)
    }
}

fn validate_diagnostic_code(code: &str) -> Result<(), CoreError> {
    if code.trim().is_empty() {
        return Err(invalid_diagnostic(
            "ErrorInfo code",
            code,
            "must not be blank",
        ));
    }

    if code.trim() != code {
        return Err(invalid_diagnostic(
            "ErrorInfo code",
            code,
            "must not have leading or trailing whitespace",
        ));
    }

    if code.chars().count() > MAX_DIAGNOSTIC_CODE_LEN {
        return Err(invalid_diagnostic(
            "ErrorInfo code",
            code,
            "is longer than the allowed maximum length",
        ));
    }

    if code.chars().any(char::is_control) {
        return Err(invalid_diagnostic(
            "ErrorInfo code",
            code,
            "must not contain control characters",
        ));
    }

    Ok(())
}

fn validate_diagnostic_message(message: &str) -> Result<(), CoreError> {
    if message.trim().is_empty() {
        return Err(invalid_diagnostic(
            "ErrorInfo message",
            message,
            "must not be blank",
        ));
    }

    if message.chars().count() > MAX_DIAGNOSTIC_MESSAGE_LEN {
        return Err(invalid_diagnostic(
            "ErrorInfo message",
            message,
            "is longer than the allowed maximum length",
        ));
    }

    if message.chars().any(char::is_control) {
        return Err(invalid_diagnostic(
            "ErrorInfo message",
            message,
            "must not contain control characters",
        ));
    }

    Ok(())
}

fn validate_error_hint(hint: Option<&str>) -> Result<(), CoreError> {
    let Some(hint) = hint else {
        return Ok(());
    };

    if hint.trim().is_empty() {
        return Err(invalid_diagnostic(
            "MerryErrorInfo hint",
            hint,
            "must not be blank",
        ));
    }

    if hint.chars().count() > MAX_ERROR_HINT_LEN {
        return Err(invalid_diagnostic(
            "MerryErrorInfo hint",
            hint,
            "is longer than the allowed maximum length",
        ));
    }

    if hint.chars().any(char::is_control) {
        return Err(invalid_diagnostic(
            "MerryErrorInfo hint",
            hint,
            "must not contain control characters",
        ));
    }

    Ok(())
}

fn validate_error_context(context: &BTreeMap<String, String>) -> Result<(), CoreError> {
    for (key, value) in context {
        if !ALLOWED_ERROR_CONTEXT_KEYS.contains(&key.as_str()) {
            return Err(invalid_diagnostic(
                "MerryErrorInfo context",
                key,
                "context key is not allowed",
            ));
        }

        if value.chars().count() > MAX_ERROR_CONTEXT_VALUE_LEN {
            return Err(invalid_diagnostic(
                "MerryErrorInfo context value",
                value,
                "is longer than the allowed maximum length",
            ));
        }

        if value.chars().any(char::is_control) {
            return Err(invalid_diagnostic(
                "MerryErrorInfo context value",
                value,
                "must not contain control characters",
            ));
        }
    }

    Ok(())
}

fn invalid_diagnostic(kind: &'static str, value: &str, reason: &'static str) -> CoreError {
    CoreError::InvalidIdentifier {
        kind,
        value: value.to_owned(),
        reason,
    }
}

impl MerryErrorInfoBuilder {
    fn maybe_hint(mut self, hint: Option<String>) -> Self {
        self.hint = hint;
        self
    }

    fn context_map(mut self, context: BTreeMap<String, String>) -> Self {
        self.context = context;
        self
    }
}