everruns-core 0.8.34

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
// Model Router domain types
//
// Design intent lives in `specs/model-router.md`.
//
// A Model Router is an org-scoped, named container of named routes. Each
// route picks a concrete LLM model via a strategy and a list of candidates;
// candidates carry provider-agnostic request overrides (reasoning_effort,
// temperature, etc.). Harnesses, agents, sessions, and org settings can bind
// to either a concrete model (today's behavior, preserved) or to a router.
//
// This module defines the entity, the route, the candidate, the strategy
// enum, and structural validation. Storage trait, REST APIs, runtime
// resolver, binding migrations, and UI ship as follow-up vertical slices.

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

use crate::typed_id::{ModelId, ModelRouterId};

#[cfg(feature = "openapi")]
use utoipa::ToSchema;

/// Router lifecycle status. Mirrors other building-block lifecycles.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum ModelRouterStatus {
    Active,
    Archived,
    Deleted,
}

impl std::fmt::Display for ModelRouterStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ModelRouterStatus::Active => write!(f, "active"),
            ModelRouterStatus::Archived => write!(f, "archived"),
            ModelRouterStatus::Deleted => write!(f, "deleted"),
        }
    }
}

impl From<&str> for ModelRouterStatus {
    fn from(s: &str) -> Self {
        match s {
            "archived" => ModelRouterStatus::Archived,
            "deleted" => ModelRouterStatus::Deleted,
            _ => ModelRouterStatus::Active,
        }
    }
}

/// Selection strategy for a route. See `specs/model-router.md` for behavior.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum ModelRouterStrategy {
    /// Exactly one candidate; trivial selection.
    Single,
    /// Try candidates in `position` order; fall through to the next on
    /// transient errors.
    OrderedFallback,
    /// Sample a candidate by `weight` per call.
    Weighted,
    /// Evaluate candidate `rules` against binding `params`; first match wins.
    Rules,
    /// Hand off to an embedded resolver registered by the host runtime.
    /// Database stores the candidate list as advisory metadata.
    Custom,
}

impl std::fmt::Display for ModelRouterStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ModelRouterStrategy::Single => write!(f, "single"),
            ModelRouterStrategy::OrderedFallback => write!(f, "ordered_fallback"),
            ModelRouterStrategy::Weighted => write!(f, "weighted"),
            ModelRouterStrategy::Rules => write!(f, "rules"),
            ModelRouterStrategy::Custom => write!(f, "custom"),
        }
    }
}

impl ModelRouterStrategy {
    /// Parse from the canonical string form (matches the DB CHECK constraint
    /// on `model_router_routes.strategy`).
    pub fn parse(s: &str) -> Result<Self, String> {
        match s {
            "single" => Ok(ModelRouterStrategy::Single),
            "ordered_fallback" => Ok(ModelRouterStrategy::OrderedFallback),
            "weighted" => Ok(ModelRouterStrategy::Weighted),
            "rules" => Ok(ModelRouterStrategy::Rules),
            "custom" => Ok(ModelRouterStrategy::Custom),
            other => Err(format!(
                "unknown model router strategy '{other}'; expected one of single, ordered_fallback, weighted, rules, custom"
            )),
        }
    }
}

/// A Model Router — org-scoped named container of routes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ModelRouter {
    /// External identifier (`mrtr_<32-hex>`). Shown as `id` in API responses.
    #[serde(rename = "id")]
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "mrtr_01933b5a000070008000000000000001")
    )]
    pub public_id: ModelRouterId,
    /// Internal UUID primary key. Used for FK references. Never exposed in API.
    #[serde(skip, default = "Uuid::nil")]
    pub internal_id: Uuid,
    /// Human-readable name, unique per org while not deleted.
    pub name: String,
    /// Optional description for the UI.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// JSON Schema describing caller-supplied params validated at binding
    /// time. Defaults to an empty object — `{}` means no parameters expected
    /// — never JSON `null`, so wire and DB shapes stay consistent.
    #[serde(default = "default_empty_object")]
    pub param_schema: serde_json::Value,
    pub status: ModelRouterStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived_at: Option<DateTime<Utc>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<DateTime<Utc>>,
    /// Routes belonging to this router. Populated by service-layer joins.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub routes: Vec<ModelRouterRoute>,
}

/// A named route inside a router. Carries the human-facing `purpose` and
/// the model-facing `when_to_use` description used by the future
/// `set_model` discoverability tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ModelRouterRoute {
    pub id: Uuid,
    /// Stable identifier within router (e.g. `base`, `analysis`).
    pub key: String,
    /// Human-facing label.
    pub purpose: String,
    /// Model-facing description (used by future `set_model` tool).
    pub when_to_use: String,
    pub strategy: ModelRouterStrategy,
    /// Display order within router.
    pub position: i32,
    /// Candidates inside this route, in position order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<ModelRouterCandidate>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

/// An ordered candidate inside a route. References a concrete model and may
/// carry provider-agnostic request overrides plus a weight (for `weighted`)
/// or rules (for `rules`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(ToSchema))]
pub struct ModelRouterCandidate {
    pub id: Uuid,
    /// The concrete model to invoke.
    #[cfg_attr(
        feature = "openapi",
        schema(value_type = String, example = "model_01933b5a000070008000000000000001")
    )]
    pub model_id: ModelId,
    /// Provider-agnostic overrides applied at LLM-call time
    /// (`reasoning_effort`, `temperature`, `max_output_tokens`, ...).
    /// Defaults to an empty object so missing fields stay object-shaped on
    /// the wire, matching the DB JSONB default of `{}`.
    #[serde(default = "default_empty_object")]
    pub request_overrides: serde_json::Value,
    /// Used by `weighted` strategy. Defaults to `1` (uniform).
    #[serde(default = "default_weight")]
    pub weight: i32,
    /// Used by `rules` strategy. None for other strategies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rules: Option<serde_json::Value>,
    /// Used by `ordered_fallback` strategy.
    pub position: i32,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

fn default_weight() -> i32 {
    1
}

fn default_empty_object() -> serde_json::Value {
    serde_json::Value::Object(serde_json::Map::new())
}

/// Maximum length for a route key (matches the DB column).
pub const MAX_ROUTE_KEY_LEN: usize = 64;

/// Validate a route `key` (lowercase letters, digits, and hyphens; no
/// leading/trailing hyphen; max 64 chars). Mirrors the DB CHECK constraint
/// on `model_router_routes.key`.
pub fn validate_route_key(key: &str) -> Result<(), String> {
    if key.is_empty() {
        return Err("route key must not be empty".into());
    }
    if key.len() > MAX_ROUTE_KEY_LEN {
        return Err(format!(
            "route key must be at most {MAX_ROUTE_KEY_LEN} characters"
        ));
    }
    if !key
        .bytes()
        .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
    {
        return Err("route key must contain only lowercase letters, digits, and hyphens".into());
    }
    if key.starts_with('-') || key.ends_with('-') {
        return Err("route key must not start or end with a hyphen".into());
    }
    Ok(())
}

/// Validate a candidate's structural shape (without DB access). Domain-level
/// cross-validation (model belongs to caller's org, route exists, etc.) is
/// performed at the server layer.
pub fn validate_candidate_shape(
    candidate: &ModelRouterCandidate,
    strategy: ModelRouterStrategy,
) -> Result<(), String> {
    if candidate.weight < 0 {
        return Err(format!(
            "candidate.weight must be non-negative, got {}",
            candidate.weight
        ));
    }
    match strategy {
        ModelRouterStrategy::Rules => {
            if candidate.rules.is_none() {
                return Err(
                    "candidates under a 'rules' strategy must have a rules document set"
                        .to_string(),
                );
            }
        }
        ModelRouterStrategy::Single
        | ModelRouterStrategy::OrderedFallback
        | ModelRouterStrategy::Weighted
        | ModelRouterStrategy::Custom => {
            // No strategy-specific structural requirement on the candidate beyond weight.
        }
    }
    Ok(())
}

/// Validate a route's full shape (key + strategy + candidate count rules).
/// Cross-row uniqueness (route `key` per router, candidate ordering) is
/// enforced at the storage layer via unique indexes.
pub fn validate_route_shape(route: &ModelRouterRoute) -> Result<(), String> {
    validate_route_key(&route.key)?;
    if matches!(route.strategy, ModelRouterStrategy::Single) && route.candidates.len() != 1 {
        return Err(format!(
            "route '{}' has strategy 'single' but {} candidates; single-strategy routes must have exactly one candidate",
            route.key,
            route.candidates.len()
        ));
    }
    for candidate in &route.candidates {
        validate_candidate_shape(candidate, route.strategy)?;
    }
    Ok(())
}

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

    fn now() -> DateTime<Utc> {
        DateTime::<Utc>::from_timestamp(1_700_000_000, 0).unwrap()
    }

    fn candidate(weight: i32, rules: Option<serde_json::Value>) -> ModelRouterCandidate {
        ModelRouterCandidate {
            id: Uuid::nil(),
            model_id: ModelId::from_seed(1),
            request_overrides: serde_json::Value::Null,
            weight,
            rules,
            position: 0,
            created_at: now(),
            updated_at: now(),
        }
    }

    #[test]
    fn status_round_trip() {
        assert_eq!(ModelRouterStatus::from("active").to_string(), "active");
        assert_eq!(ModelRouterStatus::from("archived").to_string(), "archived");
        assert_eq!(ModelRouterStatus::from("deleted").to_string(), "deleted");
        assert_eq!(ModelRouterStatus::from("unknown").to_string(), "active");
    }

    #[test]
    fn strategy_parse_round_trip() {
        for s in ["single", "ordered_fallback", "weighted", "rules", "custom"] {
            assert_eq!(ModelRouterStrategy::parse(s).unwrap().to_string(), s);
        }
    }

    #[test]
    fn strategy_parse_rejects_unknown() {
        let err = ModelRouterStrategy::parse("invalid").unwrap_err();
        assert!(err.contains("unknown model router strategy"));
    }

    #[test]
    fn route_key_accepts_canonical_keys() {
        for key in ["base", "utility", "analysis", "review", "fast-path", "v1"] {
            assert!(validate_route_key(key).is_ok(), "should accept key '{key}'");
        }
    }

    #[test]
    fn route_key_rejects_empty() {
        assert!(validate_route_key("").is_err());
    }

    #[test]
    fn route_key_rejects_uppercase() {
        assert!(validate_route_key("Analysis").is_err());
    }

    #[test]
    fn route_key_rejects_underscore() {
        assert!(validate_route_key("fast_path").is_err());
    }

    #[test]
    fn route_key_rejects_leading_hyphen() {
        assert!(validate_route_key("-fast").is_err());
    }

    #[test]
    fn route_key_rejects_trailing_hyphen() {
        assert!(validate_route_key("fast-").is_err());
    }

    #[test]
    fn route_key_rejects_too_long() {
        let key = "a".repeat(MAX_ROUTE_KEY_LEN + 1);
        assert!(validate_route_key(&key).is_err());
    }

    #[test]
    fn candidate_shape_rejects_negative_weight() {
        let cand = candidate(-1, None);
        assert!(validate_candidate_shape(&cand, ModelRouterStrategy::Weighted).is_err());
    }

    #[test]
    fn candidate_shape_rules_strategy_requires_rules_doc() {
        let cand = candidate(1, None);
        let err = validate_candidate_shape(&cand, ModelRouterStrategy::Rules).unwrap_err();
        assert!(err.contains("rules"));
    }

    #[test]
    fn candidate_shape_rules_strategy_accepts_rules_doc() {
        let cand = candidate(1, Some(serde_json::json!({ "if": { "tier": "fast" } })));
        assert!(validate_candidate_shape(&cand, ModelRouterStrategy::Rules).is_ok());
    }

    #[test]
    fn route_shape_rejects_single_with_multiple_candidates() {
        let route = ModelRouterRoute {
            id: Uuid::nil(),
            key: "base".into(),
            purpose: "default route".into(),
            when_to_use: "use this when no specific route fits".into(),
            strategy: ModelRouterStrategy::Single,
            position: 0,
            candidates: vec![candidate(1, None), candidate(1, None)],
            created_at: now(),
            updated_at: now(),
        };
        let err = validate_route_shape(&route).unwrap_err();
        assert!(err.contains("single"));
    }

    #[test]
    fn route_shape_rejects_single_with_zero_candidates() {
        let route = ModelRouterRoute {
            id: Uuid::nil(),
            key: "base".into(),
            purpose: "default route".into(),
            when_to_use: "use this when no specific route fits".into(),
            strategy: ModelRouterStrategy::Single,
            position: 0,
            candidates: vec![],
            created_at: now(),
            updated_at: now(),
        };
        let err = validate_route_shape(&route).unwrap_err();
        assert!(err.contains("single"));
    }

    #[test]
    fn route_shape_accepts_single_with_exactly_one_candidate() {
        let route = ModelRouterRoute {
            id: Uuid::nil(),
            key: "base".into(),
            purpose: "default route".into(),
            when_to_use: "use this when no specific route fits".into(),
            strategy: ModelRouterStrategy::Single,
            position: 0,
            candidates: vec![candidate(1, None)],
            created_at: now(),
            updated_at: now(),
        };
        assert!(validate_route_shape(&route).is_ok());
    }

    #[test]
    fn route_shape_accepts_ordered_fallback_with_multiple_candidates() {
        let route = ModelRouterRoute {
            id: Uuid::nil(),
            key: "base".into(),
            purpose: "default route".into(),
            when_to_use: "use this when no specific route fits".into(),
            strategy: ModelRouterStrategy::OrderedFallback,
            position: 0,
            candidates: vec![candidate(1, None), candidate(1, None)],
            created_at: now(),
            updated_at: now(),
        };
        assert!(validate_route_shape(&route).is_ok());
    }

    #[test]
    fn candidate_default_weight_is_one() {
        let json = r#"{
            "id": "00000000-0000-0000-0000-000000000000",
            "model_id": "model_00000000000000000000000000000001",
            "position": 0,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z"
        }"#;
        let cand: ModelRouterCandidate = serde_json::from_str(json).unwrap();
        assert_eq!(cand.weight, 1);
    }

    #[test]
    fn candidate_default_request_overrides_is_empty_object() {
        // Wire and DB shapes must match: missing `request_overrides` defaults
        // to `{}`, never JSON `null`, so downstream consumers can rely on an
        // object-shaped value.
        let json = r#"{
            "id": "00000000-0000-0000-0000-000000000000",
            "model_id": "model_00000000000000000000000000000001",
            "position": 0,
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z"
        }"#;
        let cand: ModelRouterCandidate = serde_json::from_str(json).unwrap();
        assert!(
            cand.request_overrides.is_object(),
            "expected default request_overrides to be a JSON object, got {:?}",
            cand.request_overrides
        );
        assert_eq!(cand.request_overrides.as_object().unwrap().len(), 0);
    }

    #[test]
    fn router_default_param_schema_is_empty_object() {
        // Wire and DB shapes must match: missing `param_schema` defaults to
        // `{}`, never JSON `null`.
        let json = r#"{
            "id": "mrtr_00000000000000000000000000000001",
            "name": "default",
            "status": "active",
            "created_at": "2024-01-01T00:00:00Z",
            "updated_at": "2024-01-01T00:00:00Z"
        }"#;
        let router: ModelRouter = serde_json::from_str(json).unwrap();
        assert!(
            router.param_schema.is_object(),
            "expected default param_schema to be a JSON object, got {:?}",
            router.param_schema
        );
        assert_eq!(router.param_schema.as_object().unwrap().len(), 0);
    }
}