ai-lib-core 0.9.6

AI-Protocol execution runtime core (protocol, client, pipeline, transport)
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
//! V2 三环清单结构 — Ring1 核心骨架 / Ring2 能力映射 / Ring3 高级扩展
//!
//! V2 manifest structure implementing the concentric circle model.
//! Parses the three-ring structure from YAML/JSON and provides typed access
//! to all V2 features including MCP, Computer Use, and Extended Multimodal.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::capabilities::CapabilitiesV2;
use crate::protocol::config::{
    AccumulatorConfig, CandidateConfig, DecoderConfig, EndpointConfig, ErrorClassification,
    EventMapRule, RateLimitHeaders, RetryPolicy, ServiceConfig, TerminationConfig,
};

// ─── Ring 1: Core Skeleton (Required) ───────────────────────────────────────

/// V2 authentication configuration (Ring 1).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfigV2 {
    #[serde(rename = "type")]
    pub auth_type: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub header: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prefix: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token_env: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub param_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra_headers: Option<Vec<ExtraHeader>>,
}

/// Extra header entry for authentication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtraHeader {
    pub name: String,
    pub value: String,
}

/// V2 endpoint definition (Ring 1).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EndpointV2 {
    pub base_url: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub chat: Option<EndpointPath>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub embeddings: Option<EndpointPath>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stt: Option<EndpointPath>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tts: Option<EndpointPath>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rerank: Option<EndpointPath>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth: Option<AuthConfigV2>,
}

/// Endpoint path can be a plain string or an object carrying a path field.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum EndpointPath {
    Plain(String),
    Structured {
        path: String,
        #[serde(flatten)]
        extra: HashMap<String, serde_json::Value>,
    },
}

impl EndpointPath {
    pub fn as_path(&self) -> &str {
        match self {
            Self::Plain(path) => path,
            Self::Structured { path, .. } => path,
        }
    }
}

// ─── Ring 2: Capability Mapping (Conditional) ───────────────────────────────

/// V2 streaming configuration (Ring 2).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreamingV2 {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub decoder: Option<DecoderConfig>,
    #[serde(default)]
    pub event_map: Vec<EventMapRule>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub candidate: Option<CandidateConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accumulator: Option<AccumulatorConfig>,
}

/// V2 parameter definition (Ring 2).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParameterDef {
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub param_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub range: Option<Vec<f64>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub min: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max: Option<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub alias: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
}

// ─── Ring 2: MCP Integration ────────────────────────────────────────────────

/// MCP integration configuration (Ring 2).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client: Option<McpClientConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server: Option<McpServerConfig>,
}

/// MCP client configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpClientConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub protocol_version: Option<String>,
    #[serde(default)]
    pub transports: Vec<String>,
    #[serde(default)]
    pub auth_methods: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<McpCapabilities>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool_filtering: Option<McpToolFiltering>,
    #[serde(default)]
    pub approval_modes: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_mapping: Option<HashMap<String, serde_json::Value>>,
}

/// MCP server capabilities that can be consumed.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpCapabilities {
    #[serde(default)]
    pub tools: bool,
    #[serde(default)]
    pub resources: bool,
    #[serde(default)]
    pub prompts: bool,
    #[serde(default)]
    pub sampling: bool,
    #[serde(default)]
    pub elicitation: bool,
}

/// MCP tool filtering configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpToolFiltering {
    #[serde(default)]
    pub allowed_tools: bool,
    #[serde(default)]
    pub denied_tools: bool,
}

/// MCP server mode configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub transports: Vec<String>,
    #[serde(default)]
    pub exposed_capabilities: Vec<String>,
}

// ─── Ring 2: Computer Use Abstraction ───────────────────────────────────────

/// Computer Use configuration (Ring 2).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ComputerUseConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub implementation: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actions: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safety: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub environment: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provider_mapping: Option<HashMap<String, serde_json::Value>>,
}

// ─── Ring 2: Extended Multimodal ────────────────────────────────────────────

/// Extended multimodal configuration (Ring 2).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultimodalConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub input: Option<MultimodalInput>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<MultimodalOutput>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub omni_mode: Option<OmniModeConfig>,
}

/// Multimodal input modalities.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultimodalInput {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vision: Option<VisionConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio: Option<AudioInputConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub video: Option<VideoInputConfig>,
}

/// Vision input configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VisionConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub formats: Vec<String>,
    #[serde(default)]
    pub encoding_methods: Vec<String>,
    #[serde(default)]
    pub document_understanding: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_file_size: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_resolution: Option<String>,
}

/// Audio input configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AudioInputConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub formats: Vec<String>,
    #[serde(default)]
    pub real_time_streaming: bool,
    #[serde(default)]
    pub speech_recognition: bool,
}

/// Video input configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VideoInputConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub formats: Vec<String>,
    #[serde(default)]
    pub temporal_reasoning: bool,
    #[serde(default)]
    pub audio_track: bool,
}

/// Multimodal output modalities.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MultimodalOutput {
    #[serde(default)]
    pub text: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub audio: Option<AudioOutputConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub image: Option<ImageOutputConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub video: Option<VideoOutputConfig>,
}

/// Audio output configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct AudioOutputConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub real_time_tts: bool,
    #[serde(default)]
    pub natural_voice: bool,
    #[serde(default)]
    pub voice_selection: bool,
}

/// Image generation output configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ImageOutputConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub formats: Vec<String>,
}

/// Video generation output configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct VideoOutputConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub formats: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_duration: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_resolution: Option<String>,
}

/// Omni-mode configuration.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OmniModeConfig {
    #[serde(default)]
    pub supported: bool,
    #[serde(default)]
    pub real_time_voice_chat: bool,
    #[serde(default)]
    pub streaming_multimodal: bool,
}

// ─── Root V2 Manifest ───────────────────────────────────────────────────────

/// Complete V2 Provider Manifest — three-ring concentric circle structure.
///
/// Ring 1 fields are required. Ring 2 fields are conditional on capabilities.
/// Ring 3 fields are optional advanced extensions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestV2 {
    // ─── Ring 1: Core Skeleton (Required) ───
    pub id: String,
    pub protocol_version: String,
    pub endpoint: EndpointV2,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error_classification: Option<ErrorClassification>,

    // Provider metadata
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub official_url: Option<String>,

    // ─── Ring 2: Capability Mapping (Conditional) ───
    pub capabilities: CapabilitiesV2,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameters: Option<HashMap<String, ParameterDef>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub streaming: Option<StreamingV2>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub multimodal: Option<MultimodalConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub computer_use: Option<ComputerUseConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mcp: Option<McpConfig>,

    // ─── Ring 3: Advanced Extensions (Optional) ───
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub api_families: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_api_family: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub endpoints: Option<HashMap<String, EndpointConfig>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub services: Option<HashMap<String, ServiceConfig>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_limit_headers: Option<RateLimitHeaders>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_policy: Option<RetryPolicy>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub termination: Option<TerminationConfig>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,

    // Catch-all for forward compatibility
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl ManifestV2 {
    /// Check if the manifest declares support for a given capability.
    pub fn has_capability(&self, cap: super::capabilities::Capability) -> bool {
        self.capabilities.has_capability(cap)
    }

    /// Check if MCP client is supported.
    pub fn mcp_client_supported(&self) -> bool {
        self.mcp
            .as_ref()
            .and_then(|m| m.client.as_ref())
            .map(|c| c.supported)
            .unwrap_or(false)
    }

    /// Check if Computer Use is supported.
    pub fn computer_use_supported(&self) -> bool {
        self.computer_use
            .as_ref()
            .map(|cu| cu.supported)
            .unwrap_or(false)
    }

    /// Get the base URL for API requests.
    pub fn base_url(&self) -> &str {
        &self.endpoint.base_url
    }

    /// Get the chat endpoint path.
    pub fn chat_path(&self) -> &str {
        self.endpoint
            .chat
            .as_ref()
            .map(EndpointPath::as_path)
            .unwrap_or("/chat/completions")
    }

    /// Detect the API style from the manifest structure.
    pub fn detect_api_style(&self) -> ApiStyle {
        // Heuristic: check streaming decoder strategy or endpoint patterns
        if let Some(streaming) = &self.streaming {
            if let Some(decoder) = &streaming.decoder {
                if let Some(strategy) = &decoder.strategy {
                    if strategy.starts_with("anthropic") {
                        return ApiStyle::AnthropicMessages;
                    }
                    if strategy.starts_with("gemini") {
                        return ApiStyle::GeminiGenerate;
                    }
                }
            }
        }
        // Check endpoint path for Gemini pattern
        if self.chat_path().contains(":generateContent") {
            return ApiStyle::GeminiGenerate;
        }
        if self.chat_path().contains("/messages") && !self.chat_path().contains("/chat/") {
            return ApiStyle::AnthropicMessages;
        }
        ApiStyle::OpenAiCompatible
    }

    /// Determine the protocol version as a semver-like tuple.
    pub fn protocol_semver(&self) -> (u32, u32) {
        let parts: Vec<&str> = self.protocol_version.split('.').collect();
        let major = parts.first().and_then(|s| s.parse().ok()).unwrap_or(1);
        let minor = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
        (major, minor)
    }

    /// Check if this is a V2 manifest.
    pub fn is_v2(&self) -> bool {
        self.protocol_semver().0 >= 2
    }
}

/// API style classification for ProviderDriver selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ApiStyle {
    /// OpenAI chat completions format (also used by DeepSeek, Moonshot, Zhipu, etc.)
    OpenAiCompatible,
    /// Anthropic messages format
    AnthropicMessages,
    /// Google Gemini generateContent format
    GeminiGenerate,
    /// Custom format requiring a dedicated driver
    Custom,
}

impl std::fmt::Display for ApiStyle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OpenAiCompatible => write!(f, "openai_compatible"),
            Self::AnthropicMessages => write!(f, "anthropic_messages"),
            Self::GeminiGenerate => write!(f, "gemini_generate"),
            Self::Custom => write!(f, "custom"),
        }
    }
}

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

    #[test]
    fn test_parse_v2_manifest_from_yaml() {
        let yaml = r#"
id: openai
protocol_version: "2.0"
name: OpenAI
status: stable
endpoint:
  base_url: https://api.openai.com/v1
  chat: /chat/completions
  auth:
    type: bearer
    header: Authorization
    prefix: Bearer
error_classification:
  by_http_status:
    "400": invalid_request
    "429": rate_limited
capabilities:
  required: [text, streaming, tools]
  optional: [vision, mcp_client, computer_use]
  feature_flags:
    structured_output: true
    parallel_tool_calls: true
mcp:
  client:
    supported: true
    protocol_version: "2025-11-25"
    transports: [streamable_http, sse]
computer_use:
  supported: true
  status: preview
  implementation: screen_based
streaming:
  decoder:
    format: sse
    strategy: openai_chat
"#;
        let manifest: ManifestV2 = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(manifest.id, "openai");
        assert!(manifest.is_v2());
        assert!(manifest.mcp_client_supported());
        assert!(manifest.computer_use_supported());
        assert_eq!(manifest.detect_api_style(), ApiStyle::OpenAiCompatible);
        assert!(manifest.has_capability(super::super::capabilities::Capability::McpClient));
    }

    #[test]
    fn test_detect_anthropic_style() {
        let yaml = r#"
id: anthropic
protocol_version: "2.0"
endpoint:
  base_url: https://api.anthropic.com/v1
  chat: /messages
capabilities:
  required: [text, streaming]
streaming:
  decoder:
    format: anthropic_sse
    strategy: anthropic_event_stream
"#;
        let manifest: ManifestV2 = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(manifest.detect_api_style(), ApiStyle::AnthropicMessages);
    }

    #[test]
    fn test_detect_gemini_style() {
        let yaml = r#"
id: google
protocol_version: "2.0"
endpoint:
  base_url: https://generativelanguage.googleapis.com/v1beta
  chat: "/models/{model}:generateContent"
capabilities:
  required: [text, streaming]
"#;
        let manifest: ManifestV2 = serde_yaml::from_str(yaml).unwrap();
        assert_eq!(manifest.detect_api_style(), ApiStyle::GeminiGenerate);
    }
}