converge-core 2.1.2

Converge Agent OS - correctness-first, context-driven multi-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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// Copyright 2024-2026 Reflective Labs
// SPDX-License-Identifier: MIT

//! Model selection based on agent requirements.
//!
//! This module provides orthogonal selection dimensions that users reason about:
//!
//! 1. **Jurisdiction** - Where can data legally reside?
//! 2. **`LatencyClass`** - How fast do you need responses?
//! 3. **`CostTier`** - What's your budget preference?
//! 4. **`TaskComplexity`** - How hard is the task?
//! 5. **`RequiredCapabilities`** - What features are needed?
//!
//! # Design Principles
//!
//! These dimensions are orthogonal - each represents a distinct concern users have.
//! "Local" is not a dimension; it's an *outcome* that emerges when:
//! - Jurisdiction requires same-country AND no cloud provider exists there
//! - Latency requires real-time AND network round-trip is too slow
//! - Control requires on-premises infrastructure
//!
//! # Architecture
//!
//! - **Core (this module)**: Abstract requirements and selection trait
//! - **Provider crate**: Concrete selector with all provider metadata
//!
//! This separation ensures core remains provider-agnostic while allowing
//! injection of provider-specific selection logic.

use crate::llm::LlmError;

// =============================================================================
// DIMENSION 1: JURISDICTION
// =============================================================================

/// Data jurisdiction requirements - where can data legally reside?
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Jurisdiction {
    #[default]
    Unrestricted,
    Trusted,
    SameRegion,
    SameCountry,
}

impl Jurisdiction {
    #[must_use]
    pub fn satisfied_by(
        self,
        provider_country: &str,
        provider_region: &str,
        user_country: &str,
        user_region: &str,
    ) -> bool {
        match self {
            Self::Unrestricted => true,
            Self::Trusted => is_trusted_jurisdiction(provider_region),
            Self::SameRegion => provider_region == user_region,
            Self::SameCountry => provider_country == user_country,
        }
    }
}

fn is_trusted_jurisdiction(region: &str) -> bool {
    matches!(
        region.to_uppercase().as_str(),
        "EU" | "EEA" | "CH" | "UK" | "JP" | "CA" | "NZ" | "IL" | "KR" | "AR" | "UY"
    )
}

// =============================================================================
// DIMENSION 2: LATENCY CLASS
// =============================================================================

/// Latency class requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum LatencyClass {
    Realtime,
    #[default]
    Interactive,
    Background,
    Batch,
}

impl LatencyClass {
    #[must_use]
    pub fn max_latency_ms(self) -> u32 {
        match self {
            Self::Realtime => 100,
            Self::Interactive => 2000,
            Self::Background => 30000,
            Self::Batch => 300_000,
        }
    }

    #[must_use]
    pub fn satisfied_by(self, provider_latency_ms: u32) -> bool {
        provider_latency_ms <= self.max_latency_ms()
    }
}

// =============================================================================
// DIMENSION 3: COST TIER
// =============================================================================

/// Cost tier preference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
pub enum CostTier {
    Minimal,
    #[default]
    Standard,
    Premium,
}

// =============================================================================
// DIMENSION 4: TASK COMPLEXITY
// =============================================================================

/// Task complexity hint.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TaskComplexity {
    Extraction,
    #[default]
    Classification,
    Reasoning,
    Generation,
}

impl TaskComplexity {
    #[must_use]
    pub fn min_quality_hint(self) -> f64 {
        match self {
            Self::Extraction => 0.5,
            Self::Classification => 0.6,
            Self::Reasoning => 0.8,
            Self::Generation => 0.7,
        }
    }

    #[must_use]
    pub fn requires_reasoning(self) -> bool {
        matches!(self, Self::Reasoning)
    }
}

// =============================================================================
// DIMENSION 5: REQUIRED CAPABILITIES
// =============================================================================

/// Required model capabilities.
#[derive(Debug, Clone, PartialEq, Default)]
#[allow(clippy::struct_excessive_bools)]
pub struct RequiredCapabilities {
    pub tool_use: bool,
    pub vision: bool,
    pub min_context_tokens: Option<usize>,
    pub structured_output: bool,
    pub code: bool,
    pub multilingual: bool,
    pub web_search: bool,
}

impl RequiredCapabilities {
    #[must_use]
    pub fn none() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_tool_use(mut self) -> Self {
        self.tool_use = true;
        self
    }

    #[must_use]
    pub fn with_vision(mut self) -> Self {
        self.vision = true;
        self
    }

    #[must_use]
    pub fn with_min_context(mut self, tokens: usize) -> Self {
        self.min_context_tokens = Some(tokens);
        self
    }

    #[must_use]
    pub fn with_structured_output(mut self) -> Self {
        self.structured_output = true;
        self
    }

    #[must_use]
    pub fn with_code(mut self) -> Self {
        self.code = true;
        self
    }

    #[must_use]
    pub fn with_multilingual(mut self) -> Self {
        self.multilingual = true;
        self
    }

    #[must_use]
    pub fn with_web_search(mut self) -> Self {
        self.web_search = true;
        self
    }
}

// =============================================================================
// LEGACY TYPES
// =============================================================================

/// Cost classification for model selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CostClass {
    VeryLow,
    Low,
    Medium,
    High,
    VeryHigh,
}

impl CostClass {
    #[must_use]
    pub fn allowed_classes(self) -> Vec<CostClass> {
        match self {
            Self::VeryLow => vec![Self::VeryLow],
            Self::Low => vec![Self::VeryLow, Self::Low],
            Self::Medium => vec![Self::VeryLow, Self::Low, Self::Medium],
            Self::High => vec![Self::VeryLow, Self::Low, Self::Medium, Self::High],
            Self::VeryHigh => vec![
                Self::VeryLow,
                Self::Low,
                Self::Medium,
                Self::High,
                Self::VeryHigh,
            ],
        }
    }

    #[must_use]
    pub fn from_tier(tier: CostTier) -> Self {
        match tier {
            CostTier::Minimal => Self::Low,
            CostTier::Standard => Self::Medium,
            CostTier::Premium => Self::VeryHigh,
        }
    }
}

/// Data sovereignty requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DataSovereignty {
    Any,
    EU,
    Switzerland,
    China,
    US,
    OnPremises,
}

impl DataSovereignty {
    #[must_use]
    pub fn from_jurisdiction(jurisdiction: Jurisdiction, user_region: &str) -> Self {
        match jurisdiction {
            Jurisdiction::Unrestricted | Jurisdiction::Trusted => Self::Any,
            Jurisdiction::SameRegion => match user_region.to_uppercase().as_str() {
                "EU" | "EEA" => Self::EU,
                "CH" => Self::Switzerland,
                "CN" => Self::China,
                "US" => Self::US,
                _ => Self::Any,
            },
            Jurisdiction::SameCountry => Self::OnPremises,
        }
    }
}

/// Compliance and explainability requirements.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ComplianceLevel {
    None,
    GDPR,
    SOC2,
    HIPAA,
    HighExplainability,
}

// =============================================================================
// SELECTION CRITERIA
// =============================================================================

/// Selection criteria using orthogonal dimensions.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct SelectionCriteria {
    pub jurisdiction: Jurisdiction,
    pub latency: LatencyClass,
    pub cost: CostTier,
    pub complexity: TaskComplexity,
    pub capabilities: RequiredCapabilities,
    pub compliance: Option<ComplianceLevel>,
    pub user_country: Option<String>,
    pub user_region: Option<String>,
}

impl SelectionCriteria {
    #[must_use]
    pub fn high_volume() -> Self {
        Self {
            latency: LatencyClass::Interactive,
            cost: CostTier::Minimal,
            complexity: TaskComplexity::Extraction,
            ..Default::default()
        }
    }

    #[must_use]
    pub fn interactive() -> Self {
        Self {
            latency: LatencyClass::Interactive,
            cost: CostTier::Standard,
            complexity: TaskComplexity::Classification,
            ..Default::default()
        }
    }

    #[must_use]
    pub fn analysis() -> Self {
        Self {
            latency: LatencyClass::Background,
            cost: CostTier::Premium,
            complexity: TaskComplexity::Reasoning,
            ..Default::default()
        }
    }

    #[must_use]
    pub fn batch() -> Self {
        Self {
            latency: LatencyClass::Batch,
            cost: CostTier::Minimal,
            complexity: TaskComplexity::Extraction,
            ..Default::default()
        }
    }

    #[must_use]
    pub fn with_jurisdiction(mut self, jurisdiction: Jurisdiction) -> Self {
        self.jurisdiction = jurisdiction;
        self
    }

    #[must_use]
    pub fn with_latency(mut self, latency: LatencyClass) -> Self {
        self.latency = latency;
        self
    }

    #[must_use]
    pub fn with_cost(mut self, cost: CostTier) -> Self {
        self.cost = cost;
        self
    }

    #[must_use]
    pub fn with_complexity(mut self, complexity: TaskComplexity) -> Self {
        self.complexity = complexity;
        self
    }

    #[must_use]
    pub fn with_capabilities(mut self, capabilities: RequiredCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    #[must_use]
    pub fn with_compliance(mut self, compliance: ComplianceLevel) -> Self {
        self.compliance = Some(compliance);
        self
    }

    #[must_use]
    pub fn with_user_location(
        mut self,
        country: impl Into<String>,
        region: impl Into<String>,
    ) -> Self {
        self.user_country = Some(country.into());
        self.user_region = Some(region.into());
        self
    }

    #[must_use]
    pub fn to_legacy_requirements(&self) -> AgentRequirements {
        let user_region = self.user_region.as_deref().unwrap_or("US");
        AgentRequirements {
            max_cost_class: CostClass::from_tier(self.cost),
            max_latency_ms: self.latency.max_latency_ms(),
            requires_reasoning: self.complexity.requires_reasoning(),
            requires_web_search: self.capabilities.web_search,
            min_quality: self.complexity.min_quality_hint(),
            data_sovereignty: DataSovereignty::from_jurisdiction(self.jurisdiction, user_region),
            compliance: self.compliance.unwrap_or(ComplianceLevel::None),
            requires_multilingual: self.capabilities.multilingual,
        }
    }
}

// =============================================================================
// LEGACY AGENT REQUIREMENTS
// =============================================================================

/// Requirements for an agent's LLM usage.
#[derive(Debug, Clone, PartialEq)]
pub struct AgentRequirements {
    pub max_cost_class: CostClass,
    pub max_latency_ms: u32,
    pub requires_reasoning: bool,
    pub requires_web_search: bool,
    pub min_quality: f64,
    pub data_sovereignty: DataSovereignty,
    pub compliance: ComplianceLevel,
    pub requires_multilingual: bool,
}

impl AgentRequirements {
    #[must_use]
    pub fn fast_cheap() -> Self {
        Self {
            max_cost_class: CostClass::VeryLow,
            max_latency_ms: 2000,
            requires_reasoning: false,
            requires_web_search: false,
            min_quality: 0.6,
            data_sovereignty: DataSovereignty::Any,
            compliance: ComplianceLevel::None,
            requires_multilingual: false,
        }
    }

    #[must_use]
    pub fn deep_research() -> Self {
        Self {
            max_cost_class: CostClass::High,
            max_latency_ms: 30000,
            requires_reasoning: true,
            requires_web_search: true,
            min_quality: 0.9,
            data_sovereignty: DataSovereignty::Any,
            compliance: ComplianceLevel::None,
            requires_multilingual: false,
        }
    }

    #[must_use]
    pub fn balanced() -> Self {
        Self {
            max_cost_class: CostClass::Medium,
            max_latency_ms: 5000,
            requires_reasoning: false,
            requires_web_search: false,
            min_quality: 0.7,
            data_sovereignty: DataSovereignty::Any,
            compliance: ComplianceLevel::None,
            requires_multilingual: false,
        }
    }

    #[must_use]
    pub fn new(max_cost_class: CostClass, max_latency_ms: u32, requires_reasoning: bool) -> Self {
        Self {
            max_cost_class,
            max_latency_ms,
            requires_reasoning,
            requires_web_search: false,
            min_quality: 0.7,
            data_sovereignty: DataSovereignty::Any,
            compliance: ComplianceLevel::None,
            requires_multilingual: false,
        }
    }

    #[must_use]
    pub fn with_web_search(mut self, requires: bool) -> Self {
        self.requires_web_search = requires;
        self
    }

    #[must_use]
    pub fn with_min_quality(mut self, quality: f64) -> Self {
        self.min_quality = quality.clamp(0.0, 1.0);
        self
    }

    #[must_use]
    pub fn with_data_sovereignty(mut self, sovereignty: DataSovereignty) -> Self {
        self.data_sovereignty = sovereignty;
        self
    }

    #[must_use]
    pub fn with_compliance(mut self, compliance: ComplianceLevel) -> Self {
        self.compliance = compliance;
        self
    }

    #[must_use]
    pub fn with_multilingual(mut self, requires: bool) -> Self {
        self.requires_multilingual = requires;
        self
    }

    #[must_use]
    pub fn from_criteria(criteria: &SelectionCriteria) -> Self {
        criteria.to_legacy_requirements()
    }
}

/// Trait for model selection based on agent requirements.
pub trait ModelSelectorTrait: Send + Sync {
    fn select(&self, requirements: &AgentRequirements) -> Result<(String, String), LlmError>;
}

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

    #[test]
    fn test_jurisdiction_trusted() {
        assert!(is_trusted_jurisdiction("EU"));
        assert!(is_trusted_jurisdiction("CH"));
        assert!(!is_trusted_jurisdiction("CN"));
    }

    #[test]
    fn test_jurisdiction_same_region() {
        assert!(Jurisdiction::SameRegion.satisfied_by("DE", "EU", "SE", "EU"));
        assert!(!Jurisdiction::SameRegion.satisfied_by("US", "US", "SE", "EU"));
    }

    #[test]
    fn test_latency_class_thresholds() {
        assert_eq!(LatencyClass::Realtime.max_latency_ms(), 100);
        assert_eq!(LatencyClass::Interactive.max_latency_ms(), 2000);
        assert_eq!(LatencyClass::Background.max_latency_ms(), 30000);
        assert_eq!(LatencyClass::Batch.max_latency_ms(), 300_000);
    }

    #[test]
    fn test_latency_satisfied_by() {
        assert!(LatencyClass::Interactive.satisfied_by(1500));
        assert!(!LatencyClass::Interactive.satisfied_by(3000));
    }

    #[test]
    fn test_task_complexity_hints() {
        assert!(
            TaskComplexity::Extraction.min_quality_hint()
                < TaskComplexity::Reasoning.min_quality_hint()
        );
        assert!(TaskComplexity::Reasoning.requires_reasoning());
        assert!(!TaskComplexity::Extraction.requires_reasoning());
    }

    #[test]
    fn test_required_capabilities_builder() {
        let caps = RequiredCapabilities::none()
            .with_tool_use()
            .with_vision()
            .with_min_context(128_000);
        assert!(caps.tool_use);
        assert!(caps.vision);
        assert_eq!(caps.min_context_tokens, Some(128_000));
        assert!(!caps.code);
    }

    #[test]
    fn test_selection_criteria_presets() {
        let high_vol = SelectionCriteria::high_volume();
        assert_eq!(high_vol.cost, CostTier::Minimal);
        assert_eq!(high_vol.complexity, TaskComplexity::Extraction);

        let analysis = SelectionCriteria::analysis();
        assert_eq!(analysis.cost, CostTier::Premium);
        assert_eq!(analysis.complexity, TaskComplexity::Reasoning);
    }

    #[test]
    fn test_selection_criteria_to_legacy() {
        let criteria = SelectionCriteria::default()
            .with_latency(LatencyClass::Background)
            .with_cost(CostTier::Premium)
            .with_complexity(TaskComplexity::Reasoning);
        let legacy = criteria.to_legacy_requirements();
        assert_eq!(legacy.max_latency_ms, 30000);
        assert!(legacy.requires_reasoning);
        assert!(legacy.min_quality >= 0.8);
    }

    #[test]
    fn test_cost_class_from_tier() {
        assert_eq!(CostClass::from_tier(CostTier::Minimal), CostClass::Low);
        assert_eq!(CostClass::from_tier(CostTier::Standard), CostClass::Medium);
        assert_eq!(CostClass::from_tier(CostTier::Premium), CostClass::VeryHigh);
    }

    #[test]
    fn test_fast_cheap_requirements() {
        let reqs = AgentRequirements::fast_cheap();
        assert_eq!(reqs.max_cost_class, CostClass::VeryLow);
        assert!(!reqs.requires_reasoning);
    }

    #[test]
    fn test_cost_class_allowed() {
        assert_eq!(CostClass::VeryLow.allowed_classes().len(), 1);
        assert_eq!(CostClass::VeryHigh.allowed_classes().len(), 5);
    }
}