machi-types 1.0.0

Core types for the Machi agent runtime kernel
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
//! Structured errors and stable error codes.
//!
//! Control planes must branch on [`ErrorCode`] / [`RetryClass`], never on
//! substring matching of [`Display`](std::fmt::Display) output.

use std::fmt;
use std::sync::Arc;

use serde::{Deserialize, Serialize};

/// Machine-stable error code for control-plane handling.
///
/// Codes use dotted `domain.reason` strings via [`ErrorCode::as_str`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
    // --- types ---
    /// Invalid or empty identifier.
    TypesInvalidId,
    /// Message or payload failed validation.
    TypesValidation,
    /// Serialization failure.
    TypesSerde,

    // --- tool ---
    /// Tool not found in registry.
    ToolNotFound,
    /// Tool arguments failed schema/parse.
    ToolInvalidArgs,
    /// Tool execution failed.
    ToolExecution,
    /// Tool timed out.
    ToolTimeout,
    /// Tool cancelled.
    ToolCancelled,
    /// Tool denied by policy/capability.
    ToolDenied,
    /// Tool call rejected by approval gate.
    ToolApprovalDenied,
    /// Tool stream ended without a terminal item (protocol violation).
    ToolStreamProtocol,
    /// Tool rate limited by upstream service.
    ToolRateLimited,
    /// Tool concurrency limit exceeded.
    ToolConcurrencyLimit,
    /// Tool network failure.
    ToolNetwork,
    /// Tool upstream service unavailable.
    ToolServiceUnavailable,

    // --- llm ---
    /// LLM transport or provider failure.
    LlmProvider,
    /// LLM request cancelled.
    LlmCancelled,
    /// LLM response invalid.
    LlmInvalidResponse,
    /// LLM authentication / authorization failure.
    LlmAuth,
    /// LLM rate limited.
    LlmRateLimit,
    /// Stream/sample idle timeout between chunks.
    LlmIdleTimeout,
    /// Provider returned an empty completion (no text / tool calls).
    LlmEmptyResponse,
    /// Output truncated (max tokens / length limit).
    LlmTruncated,

    // --- agent ---
    /// Agent definition invalid.
    AgentInvalidDefinition,
    /// Agent build failure.
    AgentBuild,
    /// Agent type / definition not found for resolution.
    AgentNotFound,

    // --- runtime / turn ---
    /// Turn hit max steps.
    RuntimeMaxSteps,
    /// Turn cancelled.
    RuntimeCancelled,
    /// Runtime gate rejected the outcome.
    RuntimeGate,
    /// Structured output failed schema validation after retries.
    RuntimeStructuredOutput,
    /// Turn deadline exceeded.
    RuntimeDeadline,
    /// Identical tool calls repeated past the stationarity hard stop.
    RuntimeStationarity,

    // --- host ---
    /// Host spawn failed.
    HostSpawn,
    /// Agent budget exhausted.
    HostBudget,
    /// Nested spawn depth exceeded.
    HostDepth,
    /// Concurrent nested agent cap exceeded.
    HostConcurrency,
    /// Host capability unsupported.
    HostUnsupported,
    /// Host cancelled.
    HostCancelled,
    /// Isolation backend failure.
    HostIsolation,

    // --- workflow ---
    /// Workflow script compile/runtime failure.
    WorkflowScript,
    /// Journal divergence on resume.
    WorkflowDivergence,
    /// Journal I/O or integrity failure.
    WorkflowJournal,
    /// Workflow agent budget exceeded.
    WorkflowBudget,
    /// Workflow cancelled.
    WorkflowCancelled,
    /// Workflow validation / probe failure.
    WorkflowValidate,

    // --- state / memory ---
    /// Conversation state invariant violated (e.g. dangling tool call).
    StateInvariant,
    /// Persistence backend I/O failure.
    StatePersistence,

    // --- compaction ---
    /// Compaction strategy failed.
    CompactionFailed,
    /// Context still exceeds limits after compaction.
    CompactionOverflow,

    /// Generic internal failure.
    Internal,
}

impl ErrorCode {
    /// Stable `snake_case` dotted code string.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::TypesInvalidId => "types.invalid_id",
            Self::TypesValidation => "types.validation",
            Self::TypesSerde => "types.serde",
            Self::ToolNotFound => "tool.not_found",
            Self::ToolInvalidArgs => "tool.invalid_args",
            Self::ToolExecution => "tool.execution",
            Self::ToolTimeout => "tool.timeout",
            Self::ToolCancelled => "tool.cancelled",
            Self::ToolDenied => "tool.denied",
            Self::ToolApprovalDenied => "tool.approval_denied",
            Self::ToolStreamProtocol => "tool.stream_protocol",
            Self::ToolRateLimited => "tool.rate_limited",
            Self::ToolConcurrencyLimit => "tool.concurrency_limit",
            Self::ToolNetwork => "tool.network",
            Self::ToolServiceUnavailable => "tool.service_unavailable",
            Self::LlmProvider => "llm.provider",
            Self::LlmCancelled => "llm.cancelled",
            Self::LlmInvalidResponse => "llm.invalid_response",
            Self::LlmAuth => "llm.auth",
            Self::LlmRateLimit => "llm.rate_limit",
            Self::LlmIdleTimeout => "llm.idle_timeout",
            Self::LlmEmptyResponse => "llm.empty_response",
            Self::LlmTruncated => "llm.truncated",
            Self::AgentInvalidDefinition => "agent.invalid_definition",
            Self::AgentBuild => "agent.build",
            Self::AgentNotFound => "agent.not_found",
            Self::RuntimeMaxSteps => "runtime.max_steps",
            Self::RuntimeCancelled => "runtime.cancelled",
            Self::RuntimeGate => "runtime.gate",
            Self::RuntimeStructuredOutput => "runtime.structured_output",
            Self::RuntimeDeadline => "runtime.deadline",
            Self::RuntimeStationarity => "runtime.stationarity",
            Self::HostSpawn => "host.spawn",
            Self::HostBudget => "host.budget",
            Self::HostDepth => "host.depth",
            Self::HostConcurrency => "host.concurrency",
            Self::HostUnsupported => "host.unsupported",
            Self::HostCancelled => "host.cancelled",
            Self::HostIsolation => "host.isolation",
            Self::WorkflowScript => "workflow.script",
            Self::WorkflowDivergence => "workflow.divergence",
            Self::WorkflowJournal => "workflow.journal",
            Self::WorkflowBudget => "workflow.budget",
            Self::WorkflowCancelled => "workflow.cancelled",
            Self::WorkflowValidate => "workflow.validate",
            Self::StateInvariant => "state.invariant",
            Self::StatePersistence => "state.persistence",
            Self::CompactionFailed => "compaction.failed",
            Self::CompactionOverflow => "compaction.overflow",
            Self::Internal => "internal",
        }
    }

    /// Domain prefix (`types`, `tool`, `llm`, …).
    #[must_use]
    pub const fn domain(self) -> &'static str {
        match self {
            Self::TypesInvalidId | Self::TypesValidation | Self::TypesSerde => "types",
            Self::ToolNotFound
            | Self::ToolInvalidArgs
            | Self::ToolExecution
            | Self::ToolTimeout
            | Self::ToolCancelled
            | Self::ToolDenied
            | Self::ToolApprovalDenied
            | Self::ToolStreamProtocol
            | Self::ToolRateLimited
            | Self::ToolConcurrencyLimit
            | Self::ToolNetwork
            | Self::ToolServiceUnavailable => "tool",
            Self::LlmProvider
            | Self::LlmCancelled
            | Self::LlmInvalidResponse
            | Self::LlmAuth
            | Self::LlmRateLimit
            | Self::LlmIdleTimeout
            | Self::LlmEmptyResponse
            | Self::LlmTruncated => "llm",
            Self::AgentInvalidDefinition | Self::AgentBuild | Self::AgentNotFound => "agent",
            Self::RuntimeMaxSteps
            | Self::RuntimeCancelled
            | Self::RuntimeGate
            | Self::RuntimeStructuredOutput
            | Self::RuntimeDeadline
            | Self::RuntimeStationarity => "runtime",
            Self::HostSpawn
            | Self::HostBudget
            | Self::HostDepth
            | Self::HostConcurrency
            | Self::HostUnsupported
            | Self::HostCancelled
            | Self::HostIsolation => "host",
            Self::WorkflowScript
            | Self::WorkflowDivergence
            | Self::WorkflowJournal
            | Self::WorkflowBudget
            | Self::WorkflowCancelled
            | Self::WorkflowValidate => "workflow",
            Self::StateInvariant | Self::StatePersistence => "state",
            Self::CompactionFailed | Self::CompactionOverflow => "compaction",
            Self::Internal => "internal",
        }
    }

    /// Default retry classification for this code.
    ///
    /// Kernel paths set an explicit [`RetryClass`] when they know more; this
    /// is the baseline hosts may consult.
    #[must_use]
    pub const fn default_retry(self) -> RetryClass {
        match self {
            Self::LlmRateLimit | Self::LlmProvider | Self::LlmEmptyResponse => RetryClass::Backoff,
            Self::LlmAuth => RetryClass::AuthRefresh,
            Self::ToolTimeout => RetryClass::Immediate,
            Self::ToolCancelled
            | Self::LlmCancelled
            | Self::LlmIdleTimeout
            | Self::LlmTruncated
            | Self::RuntimeCancelled
            | Self::HostCancelled
            | Self::WorkflowCancelled
            | Self::ToolDenied
            | Self::ToolApprovalDenied
            | Self::ToolNotFound
            | Self::ToolInvalidArgs
            | Self::ToolStreamProtocol
            | Self::TypesInvalidId
            | Self::TypesValidation
            | Self::TypesSerde
            | Self::AgentInvalidDefinition
            | Self::AgentBuild
            | Self::AgentNotFound
            | Self::RuntimeMaxSteps
            | Self::RuntimeGate
            | Self::RuntimeStructuredOutput
            | Self::RuntimeDeadline
            | Self::RuntimeStationarity
            | Self::HostBudget
            | Self::HostDepth
            | Self::HostConcurrency
            | Self::HostUnsupported
            | Self::WorkflowDivergence
            | Self::WorkflowBudget
            | Self::WorkflowValidate
            | Self::StateInvariant
            | Self::CompactionOverflow
            | Self::Internal => RetryClass::Never,
            Self::ToolExecution
            | Self::ToolRateLimited
            | Self::ToolConcurrencyLimit
            | Self::ToolNetwork
            | Self::ToolServiceUnavailable
            | Self::LlmInvalidResponse
            | Self::HostSpawn
            | Self::HostIsolation
            | Self::WorkflowScript
            | Self::WorkflowJournal
            | Self::StatePersistence
            | Self::CompactionFailed => RetryClass::Never,
        }
    }
}

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

/// Whether an automatic retry may be appropriate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RetryClass {
    /// Do not retry.
    #[default]
    Never,
    /// Safe to retry immediately.
    Immediate,
    /// Retry with backoff.
    Backoff,
    /// Refresh credentials then retry.
    AuthRefresh,
}

/// Kernel error with stable code, message, and optional source.
#[derive(Debug, Clone, thiserror::Error)]
pub struct MachiError {
    code: ErrorCode,
    message: String,
    retry: RetryClass,
    #[source]
    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
}

impl MachiError {
    /// Create an error with code and message.
    ///
    /// Retry class defaults to [`ErrorCode::default_retry`].
    #[must_use]
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code,
            message: message.into(),
            retry: code.default_retry(),
            source: None,
        }
    }

    /// Attach retry classification (overrides default).
    #[must_use]
    pub const fn with_retry(mut self, retry: RetryClass) -> Self {
        self.retry = retry;
        self
    }

    /// Attach a source error.
    #[must_use]
    pub fn with_source(mut self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        self.source = Some(Arc::new(source));
        self
    }

    /// Stable code.
    #[must_use]
    pub const fn code(&self) -> ErrorCode {
        self.code
    }

    /// Retry class.
    #[must_use]
    pub const fn retry_class(&self) -> RetryClass {
        self.retry
    }

    /// Human-readable message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Convenience: cancelled-style runtime error.
    #[must_use]
    pub fn cancelled(message: impl Into<String>) -> Self {
        Self::new(ErrorCode::RuntimeCancelled, message)
    }
}

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

/// Result alias using [`MachiError`].
pub type Result<T> = std::result::Result<T, MachiError>;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn display_includes_code() {
        let err = MachiError::new(ErrorCode::ToolTimeout, "exceeded 5s");
        assert!(err.to_string().contains("tool.timeout"), "{err}");
        assert_eq!(err.retry_class(), RetryClass::Immediate);
    }

    #[test]
    fn rate_limit_defaults_to_backoff() {
        let err = MachiError::new(ErrorCode::LlmRateLimit, "429");
        assert_eq!(err.retry_class(), RetryClass::Backoff);
        assert_eq!(err.code().domain(), "llm");
    }

    #[test]
    fn all_codes_have_domain_prefix_in_as_str() {
        let codes = [
            ErrorCode::TypesInvalidId,
            ErrorCode::ToolApprovalDenied,
            ErrorCode::ToolStreamProtocol,
            ErrorCode::LlmAuth,
            ErrorCode::LlmRateLimit,
            ErrorCode::AgentNotFound,
            ErrorCode::RuntimeStructuredOutput,
            ErrorCode::RuntimeDeadline,
            ErrorCode::HostIsolation,
            ErrorCode::WorkflowValidate,
            ErrorCode::StateInvariant,
            ErrorCode::StatePersistence,
            ErrorCode::CompactionFailed,
            ErrorCode::CompactionOverflow,
            ErrorCode::Internal,
        ];
        for code in codes {
            let s = code.as_str();
            assert!(
                s.starts_with(code.domain()) || code == ErrorCode::Internal,
                "code {s} should start with domain {}",
                code.domain()
            );
        }
    }
}

include!("error_code_matrix.rs");