harn-vm 0.8.61

Async bytecode virtual machine for the Harn programming language
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use harn_lexer::Span;

use super::VmValue;

/// Bound expressing how many arguments a callable accepts. Used in
/// [`VmError::ArityMismatch`] so error messages can render the exact
/// signature contract the caller violated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArityExpect {
    /// Exactly N parameters, no defaults, no rest.
    Exact(usize),
    /// `min..=max`: some params have defaults but the upper bound is fixed.
    Range { min: usize, max: usize },
    /// At least N parameters; further args land in a rest list. Used for
    /// `print` / `log` / variadics.
    AtLeast(usize),
}

impl std::fmt::Display for ArityExpect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ArityExpect::Exact(n) => write!(f, "{n}"),
            ArityExpect::Range { min, max } => write!(f, "{min}..={max}"),
            ArityExpect::AtLeast(n) => write!(f, "at least {n}"),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ArityMismatchError {
    pub callee: String,
    pub expected: ArityExpect,
    pub got: usize,
    pub span: Option<Span>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeadlockDiagnostic {
    SelfDeadlock,
    WaitForGraph,
}

impl DeadlockDiagnostic {
    fn code(self) -> &'static str {
        match self {
            Self::SelfDeadlock => "HARN-ORC-011",
            Self::WaitForGraph => "HARN-ORC-012",
        }
    }
}

/// Payload for [`VmError::Deadlock`]. `kind` is the primitive kind
/// (`"mutex"`, `"channel"`) or `"task"`; `key` is the primitive key or task
/// id; `detail` names the specific footgun.
#[derive(Debug, Clone)]
pub struct DeadlockError {
    pub diagnostic: DeadlockDiagnostic,
    pub kind: String,
    pub key: String,
    pub detail: String,
}

impl DeadlockError {
    pub(crate) fn self_deadlock(
        kind: impl Into<String>,
        key: impl Into<String>,
        detail: impl Into<String>,
    ) -> Self {
        Self {
            diagnostic: DeadlockDiagnostic::SelfDeadlock,
            kind: kind.into(),
            key: key.into(),
            detail: detail.into(),
        }
    }

    pub(crate) fn wait_for_graph(
        kind: impl Into<String>,
        key: impl Into<String>,
        detail: impl Into<String>,
    ) -> Self {
        Self {
            diagnostic: DeadlockDiagnostic::WaitForGraph,
            kind: kind.into(),
            key: key.into(),
            detail: detail.into(),
        }
    }
}

#[derive(Debug, Clone)]
pub struct ArgTypeMismatchError {
    pub callee: String,
    pub param: String,
    pub expected: String,
    pub got: &'static str,
    pub span: Option<Span>,
}

#[derive(Debug, Clone)]
pub enum VmError {
    StackUnderflow,
    StackOverflow,
    UndefinedVariable(String),
    UndefinedBuiltin(String),
    ImmutableAssignment(String),
    TypeError(String),
    Runtime(String),
    DivisionByZero,
    Thrown(VmValue),
    /// Thrown with error category for structured error handling.
    CategorizedError {
        message: String,
        category: ErrorCategory,
    },
    DaemonQueueFull {
        daemon_id: String,
        capacity: usize,
    },
    /// A deterministic, provably-unresolvable self-deadlock caught before the
    /// VM would block forever (Rust's borrow checker prevents data races but
    /// not deadlocks; this is the Go-runtime "all goroutines asleep" analogue
    /// for the cases we can prove). Boxed — like [`VmError::ArityMismatch`] —
    /// so the rare three-`String` payload doesn't enlarge `VmError` on the
    /// pervasive `Result<VmValue, VmError>` hot path. Carries `HARN-ORC-011`.
    Deadlock(Box<DeadlockError>),
    Return(VmValue),
    InvalidInstruction(u8),
    /// Wrong number of arguments at a call site. Distinct from
    /// [`VmError::TypeError`] so the runtime can match-and-recover (and
    /// so error UX renders `expected 2..=3 got 1` consistently).
    ArityMismatch(Box<ArityMismatchError>),
    /// Argument value did not satisfy the declared parameter type.
    /// `expected` is a pretty-printed type expression; `got` is the value's
    /// runtime type name (`VmValue::type_name`). Used for both
    /// user-defined function parameters (with declared types) and
    /// registry-known builtin parameters.
    ArgTypeMismatch(Box<ArgTypeMismatchError>),
}

/// Error categories for structured error handling in agent orchestration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ErrorCategory {
    /// Network/connection timeout
    Timeout,
    /// Authentication/authorization failure
    Auth,
    /// Rate limit exceeded (HTTP 429 / quota)
    RateLimit,
    /// Upstream provider is overloaded (HTTP 503 / 529).
    /// Distinct from RateLimit: the client hasn't exceeded a quota — the
    /// provider is shedding load and will recover on its own.
    Overloaded,
    /// Provider-side 5xx error (500, 502) that isn't specifically overload.
    ServerError,
    /// Network-level transient failure (connection reset, DNS hiccup,
    /// partial stream) — retryable but not provider-status-coded.
    TransientNetwork,
    /// LLM output failed schema validation. Retryable via `schema_retries`.
    SchemaValidation,
    /// LLM streaming response was aborted mid-stream because the partial
    /// JSON content could not conceivably satisfy `output_schema`. Surfaced
    /// by `llm_call` when `schema_stream_abort` is on (the default for
    /// schema-bearing calls). Consumes one `schema_retries` budget slot;
    /// the retry replays the prompt with a corrective nudge that cites
    /// the abort path + reason.
    SchemaStreamAborted,
    /// Tool execution failure
    ToolError,
    /// Tool was rejected by the host (not permitted / not in allowlist)
    ToolRejected,
    /// Outbound network egress was blocked by policy.
    EgressBlocked,
    /// Operation was cancelled
    Cancelled,
    /// Resource not found
    NotFound,
    /// Circuit breaker is open
    CircuitOpen,
    /// LLM cost or token budget would be exceeded
    BudgetExceeded,
    /// Generic/unclassified error
    Generic,
}

impl ErrorCategory {
    pub fn as_str(&self) -> &'static str {
        match self {
            ErrorCategory::Timeout => "timeout",
            ErrorCategory::Auth => "auth",
            ErrorCategory::RateLimit => "rate_limit",
            ErrorCategory::Overloaded => "overloaded",
            ErrorCategory::ServerError => "server_error",
            ErrorCategory::TransientNetwork => "transient_network",
            ErrorCategory::SchemaValidation => "schema_validation",
            ErrorCategory::SchemaStreamAborted => "schema_stream_aborted",
            ErrorCategory::ToolError => "tool_error",
            ErrorCategory::ToolRejected => "tool_rejected",
            ErrorCategory::EgressBlocked => "egress_blocked",
            ErrorCategory::Cancelled => "cancelled",
            ErrorCategory::NotFound => "not_found",
            ErrorCategory::CircuitOpen => "circuit_open",
            ErrorCategory::BudgetExceeded => "budget_exceeded",
            ErrorCategory::Generic => "generic",
        }
    }

    pub fn parse(s: &str) -> Self {
        match s {
            "timeout" => ErrorCategory::Timeout,
            "auth" => ErrorCategory::Auth,
            "rate_limit" => ErrorCategory::RateLimit,
            "overloaded" => ErrorCategory::Overloaded,
            "server_error" => ErrorCategory::ServerError,
            "transient_network" => ErrorCategory::TransientNetwork,
            "schema_validation" => ErrorCategory::SchemaValidation,
            "schema_stream_aborted" => ErrorCategory::SchemaStreamAborted,
            "tool_error" => ErrorCategory::ToolError,
            "tool_rejected" => ErrorCategory::ToolRejected,
            "egress_blocked" => ErrorCategory::EgressBlocked,
            "cancelled" => ErrorCategory::Cancelled,
            "not_found" => ErrorCategory::NotFound,
            "circuit_open" => ErrorCategory::CircuitOpen,
            "budget_exceeded" => ErrorCategory::BudgetExceeded,
            _ => ErrorCategory::Generic,
        }
    }

    /// Whether an error of this category is worth retrying for a transient
    /// provider-side reason. Agent loops consult this to decide whether to
    /// back off and retry vs surface the error to the user.
    pub fn is_transient(&self) -> bool {
        matches!(
            self,
            ErrorCategory::Timeout
                | ErrorCategory::RateLimit
                | ErrorCategory::Overloaded
                | ErrorCategory::ServerError
                | ErrorCategory::TransientNetwork
        )
    }
}

/// Create a categorized error conveniently.
pub fn categorized_error(message: impl Into<String>, category: ErrorCategory) -> VmError {
    VmError::CategorizedError {
        message: message.into(),
        category,
    }
}

/// Extract error category from a VmError.
///
/// Classification priority:
/// 1. Explicit CategorizedError variant (set by throw_error or internal code)
/// 2. Thrown dict with a "category" field (user-created structured errors)
/// 3. HTTP status code extraction (standard, unambiguous)
/// 4. Deadline exceeded (VM-internal)
/// 5. Fallback to Generic
pub fn error_to_category(err: &VmError) -> ErrorCategory {
    match err {
        VmError::CategorizedError { category, .. } => category.clone(),
        VmError::Thrown(VmValue::Dict(d)) => d
            .get("category")
            .map(|v| ErrorCategory::parse(&v.display()))
            .unwrap_or(ErrorCategory::Generic),
        VmError::Thrown(VmValue::String(s)) => classify_error_message(s),
        VmError::Runtime(msg) => classify_error_message(msg),
        // A deadlock is permanently non-retryable and not provider-related —
        // `Generic` is the correct "surface it, don't back off" bucket.
        VmError::Deadlock(_) => ErrorCategory::Generic,
        _ => ErrorCategory::Generic,
    }
}

/// Classify an error message using HTTP status codes and well-known patterns.
/// Prefers unambiguous signals (status codes) over substring heuristics.
pub fn classify_error_message(msg: &str) -> ErrorCategory {
    // 1. HTTP status codes — most reliable signal
    if let Some(cat) = classify_by_http_status(msg) {
        return cat;
    }
    // 2. Well-known error identifiers from major APIs
    //    (Anthropic, OpenAI, and standard HTTP patterns)
    let lower = msg.to_lowercase();
    if lower.contains("cancelled") || lower.contains("canceled") {
        return ErrorCategory::Cancelled;
    }
    if msg.contains("Deadline exceeded") || msg.contains("context deadline exceeded") {
        return ErrorCategory::Timeout;
    }
    if msg.contains("overloaded_error") {
        // Anthropic overloaded_error surfaces as HTTP 529.
        return ErrorCategory::Overloaded;
    }
    if msg.contains("api_error") {
        // Anthropic catch-all server-side error.
        return ErrorCategory::ServerError;
    }
    if msg.contains("insufficient_quota") || msg.contains("billing_hard_limit_reached") {
        // OpenAI-specific quota error types.
        return ErrorCategory::RateLimit;
    }
    if msg.contains("invalid_api_key") || msg.contains("authentication_error") {
        return ErrorCategory::Auth;
    }
    if msg.contains("not_found_error") || msg.contains("model_not_found") {
        return ErrorCategory::NotFound;
    }
    if msg.contains("circuit_open") {
        return ErrorCategory::CircuitOpen;
    }
    // Network-level transient patterns (pre-HTTP-status, pre-provider-framing).
    if lower.contains("connection reset")
        || lower.contains("connection refused")
        || lower.contains("connection closed")
        || lower.contains("broken pipe")
        || lower.contains("dns error")
        || lower.contains("stream error")
        || lower.contains("unexpected eof")
    {
        return ErrorCategory::TransientNetwork;
    }
    ErrorCategory::Generic
}

/// Classify errors by HTTP status code if one appears in the message.
/// This is the most reliable classification method since status codes
/// are standardized (RFC 9110) and unambiguous.
fn classify_by_http_status(msg: &str) -> Option<ErrorCategory> {
    // Extract 3-digit HTTP status codes from common patterns:
    // "HTTP 429", "status 429", "429 Too Many", "error: 401"
    for code in extract_http_status_codes(msg) {
        return Some(match code {
            401 | 403 => ErrorCategory::Auth,
            404 | 410 => ErrorCategory::NotFound,
            408 | 504 | 522 | 524 => ErrorCategory::Timeout,
            429 => ErrorCategory::RateLimit,
            503 | 529 => ErrorCategory::Overloaded,
            500 | 502 => ErrorCategory::ServerError,
            _ => continue,
        });
    }
    None
}

/// Extract plausible HTTP status codes from an error message.
fn extract_http_status_codes(msg: &str) -> Vec<u16> {
    let mut codes = Vec::new();
    let bytes = msg.as_bytes();
    for i in 0..bytes.len().saturating_sub(2) {
        // Look for 3-digit sequences in the 100-599 range
        if bytes[i].is_ascii_digit()
            && bytes[i + 1].is_ascii_digit()
            && bytes[i + 2].is_ascii_digit()
        {
            // Ensure it's not part of a longer number
            let before_ok = i == 0 || !bytes[i - 1].is_ascii_digit();
            let after_ok = i + 3 >= bytes.len() || !bytes[i + 3].is_ascii_digit();
            if before_ok && after_ok {
                if let Ok(code) = msg[i..i + 3].parse::<u16>() {
                    if (400..=599).contains(&code) {
                        codes.push(code);
                    }
                }
            }
        }
    }
    codes
}

impl std::fmt::Display for VmError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VmError::StackUnderflow => write!(f, "Stack underflow"),
            VmError::StackOverflow => write!(f, "Stack overflow: too many nested calls"),
            VmError::UndefinedVariable(n) => write!(f, "Undefined variable: {n}"),
            VmError::UndefinedBuiltin(n) => write!(f, "Undefined builtin: {n}"),
            VmError::ImmutableAssignment(n) => {
                write!(f, "Cannot assign to immutable binding: {n}")
            }
            VmError::TypeError(msg) => write!(f, "Type error: {msg}"),
            VmError::Runtime(msg) => write!(f, "Runtime error: {msg}"),
            VmError::DivisionByZero => write!(f, "Division by zero"),
            VmError::Thrown(v) => write!(f, "Thrown: {}", v.display()),
            VmError::CategorizedError { message, category } => {
                write!(f, "Error [{}]: {}", category.as_str(), message)
            }
            VmError::DaemonQueueFull {
                daemon_id,
                capacity,
            } => write!(
                f,
                "Daemon queue full: daemon '{daemon_id}' reached its event_queue_capacity of {capacity}"
            ),
            VmError::Deadlock(err) => match err.diagnostic {
                DeadlockDiagnostic::SelfDeadlock => write!(
                    f,
                    "{}: deadlock detected: {} ({} '{}') — this wait can never complete and would block forever",
                    err.diagnostic.code(),
                    err.detail,
                    err.kind,
                    err.key
                ),
                DeadlockDiagnostic::WaitForGraph => write!(
                    f,
                    "{}: wait-for deadlock detected: {} ({} '{}') — no active task can make progress",
                    err.diagnostic.code(),
                    err.detail,
                    err.kind,
                    err.key
                ),
            },
            VmError::Return(_) => write!(f, "Return from function"),
            VmError::InvalidInstruction(op) => write!(f, "Invalid instruction: 0x{op:02x}"),
            VmError::ArityMismatch(err) => {
                let arg_word = match err.expected {
                    ArityExpect::Exact(1) | ArityExpect::AtLeast(1) => "argument",
                    _ => "arguments",
                };
                write!(
                    f,
                    "Arity mismatch: '{}' expects {} {}, got {}{}",
                    err.callee,
                    err.expected,
                    arg_word,
                    err.got,
                    fmt_span_suffix(&err.span)
                )
            }
            VmError::ArgTypeMismatch(err) => {
                write!(
                    f,
                    "Type error: '{}' parameter `{}` expects {}, got {}{}",
                    err.callee,
                    err.param,
                    err.expected,
                    err.got,
                    fmt_span_suffix(&err.span)
                )
            }
        }
    }
}

fn fmt_span_suffix(span: &Option<Span>) -> String {
    match span {
        Some(s) => format!(" (at byte {}..{})", s.start, s.end),
        None => String::new(),
    }
}

impl std::error::Error for VmError {}

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

    #[test]
    fn classifies_cancelled_messages() {
        assert_eq!(
            classify_error_message("Bridge: operation cancelled"),
            ErrorCategory::Cancelled
        );
        assert_eq!(
            classify_error_message("operation canceled by host"),
            ErrorCategory::Cancelled
        );
    }

    #[test]
    fn deadlock_renders_with_stable_code() {
        let err = VmError::Deadlock(Box::new(DeadlockError::self_deadlock(
            "mutex",
            "__default__",
            "re-entrant acquire",
        )));
        assert!(
            err.to_string().starts_with("HARN-ORC-011"),
            "deadlock Display must carry the stable code: {err}"
        );
    }

    #[test]
    fn deadlock_maps_to_generic_category() {
        let err = VmError::Deadlock(Box::new(DeadlockError::self_deadlock(
            "task",
            "task_1",
            "self-join",
        )));
        let category = error_to_category(&err);
        assert_eq!(category, ErrorCategory::Generic);
        assert!(
            !category.is_transient(),
            "a deadlock must not be treated as a retryable transient error"
        );
    }
}