provider-core 0.1.1

Provider abstractions for the SteadyMux local continuity router.
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Gemini `generateContent` adapter (PRD-001y S2) serving the
//! `gemini_subscription` and `gemini_api` phases.
//!
//! Wire format, base URL, and auth scheme were verified at build time against
//! the published Gemini API `generateContent` documentation at
//! https://ai.google.dev/api/generate-content (no live call). The Gemini phases
//! are NOT OpenAI-compatible: the request is a `generateContent` body
//! (`contents`, `systemInstruction`, `generationConfig`, `tools`) sent to
//! `POST https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent`
//! with the `x-goog-api-key` header, and streaming uses the sibling
//! `:streamGenerateContent` path.
//!
//! Gemini requires the model id in the URL path, not the body. The route
//! endpoint path therefore stores the static template
//! `/v1beta/models/{model}:generateContent` (validated exactly in
//! `validate_gemini_route`), and this adapter materializes the per-request
//! streaming path by substituting the catalog-driven model id and switching to
//! `:streamGenerateContent`. The route carries the credential reference; this
//! adapter only wraps it for the transport layer, which resolves it through
//! the secret boundary.

use crate::ollama_chat::{HttpMethod, NetworkPolicy, ReplayBoundary, ReplayDecision};
use router_protocol::{
    CanonicalRequest, ContentBlock, InputItem, MessageRole, PhaseKind, RouteIdentity,
    RouteIdentityError, ToolChoice, TransportKind,
};
use serde_json::{Map, Value, json};
use std::fmt;

/// The header name carrying the Gemini API key.
pub const GEMINI_API_KEY_HEADER: &str = router_protocol::GEMINI_API_KEY_HEADER;
/// Default `maxOutputTokens` used when the canonical request does not bound
/// output (Gemini defaults are opaque and provider-side).
pub const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 1024;

/// The Gemini phases this adapter serves.
pub const fn is_gemini_phase(phase: PhaseKind) -> bool {
    matches!(phase, PhaseKind::GeminiSubscription | PhaseKind::GeminiApi)
}

/// Per-route MAv2 capability projection for the Gemini phases (PRD-001l/001u):
/// the Gemini wire API cannot represent namespaces, so SteadyMux normalizes at
/// the wire boundary under the non-reserved `agents` namespace. Mirrors the
/// DeepSeek/OpenAI-compat follow-on projection.
pub const fn capability_projection() -> router_protocol::MultiAgentCapabilityProjection {
    router_protocol::MultiAgentCapabilityProjection {
        namespace_tools: false,
        multi_agent_version: router_protocol::MultiAgentVersion::V2,
        wire_api: router_protocol::MultiAgentWireApi::Responses,
        observed_namespace_calls:
            router_protocol::ObservedNamespaceCallBehavior::BareNameNoNamespace,
    }
}

#[derive(Clone, PartialEq, Eq)]
pub struct GeminiSecretReferenceMarker(String);

impl GeminiSecretReferenceMarker {
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Debug for GeminiSecretReferenceMarker {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("GeminiSecretReferenceMarker([REDACTED])")
    }
}

#[derive(Clone, PartialEq)]
pub struct GeminiRequestSpec {
    pub method: HttpMethod,
    pub origin: String,
    /// The materialized per-request streaming path, e.g.
    /// `/v1beta/models/<model-id>:streamGenerateContent`.
    pub path: String,
    pub content_type: &'static str,
    pub accept: &'static str,
    pub api_key_secret: GeminiSecretReferenceMarker,
    pub network: NetworkPolicy,
    body: Value,
}

impl GeminiRequestSpec {
    pub fn body(&self) -> &Value {
        &self.body
    }

    pub fn body_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
        serde_json::to_vec(&self.body)
    }
}

impl fmt::Debug for GeminiRequestSpec {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("GeminiRequestSpec")
            .field("method", &self.method)
            .field("origin", &self.origin)
            .field("path", &self.path)
            .field("content_type", &self.content_type)
            .field("accept", &self.accept)
            .field("api_key_secret", &self.api_key_secret)
            .field("network", &self.network)
            .field("body", &"[REDACTED]")
            .finish()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeminiRequestErrorKind {
    InvalidRouteIdentity,
    InvalidRouteEndpoint,
    UnsupportedRoute,
    InvalidCanonicalRequest,
    AmbiguousToolName,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GeminiRequestError {
    pub kind: GeminiRequestErrorKind,
}

impl fmt::Display for GeminiRequestError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("the Gemini generateContent request could not be prepared")
    }
}

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

impl From<RouteIdentityError> for GeminiRequestError {
    fn from(_: RouteIdentityError) -> Self {
        Self {
            kind: GeminiRequestErrorKind::InvalidRouteIdentity,
        }
    }
}

pub fn build_request(
    route: &RouteIdentity,
    request: &CanonicalRequest,
) -> Result<GeminiRequestSpec, GeminiRequestError> {
    route.validate()?;
    if !is_gemini_phase(route.phase) || route.transport != TransportKind::DirectHttps {
        return Err(GeminiRequestError {
            kind: GeminiRequestErrorKind::UnsupportedRoute,
        });
    }
    request.validate().map_err(|_| GeminiRequestError {
        kind: GeminiRequestErrorKind::InvalidCanonicalRequest,
    })?;
    let secret_ref = route.credential_ref.clone().ok_or(GeminiRequestError {
        kind: GeminiRequestErrorKind::InvalidRouteEndpoint,
    })?;

    Ok(GeminiRequestSpec {
        method: HttpMethod::Post,
        origin: route.endpoint.origin.clone(),
        path: materialize_stream_path(&route.endpoint.path, &route.model_id),
        content_type: "application/json",
        accept: "text/event-stream",
        api_key_secret: GeminiSecretReferenceMarker(secret_ref),
        network: NetworkPolicy {
            allow_proxy: false,
            allow_dns: true,
            follow_redirects: false,
            require_tls: true,
        },
        body: build_body(request)?,
    })
}

/// Substitute the catalog model id into the `{model}` template and switch the
/// non-streaming verb to the streaming sibling path. The template and the
/// produced path are both confined to the verified route.
fn materialize_stream_path(template: &str, model_id: &str) -> String {
    let encoded = encode_model_id(model_id);
    let with_model = template.replace("{model}", &encoded);
    with_model.replace(":generateContent", ":streamGenerateContent")
}

/// Percent-encode any byte outside the model-id safe set so the materialized
/// path stays confined to the verified route.
fn encode_model_id(model_id: &str) -> String {
    let mut out = String::with_capacity(model_id.len());
    for byte in model_id.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'.' | b'_' | b'-' => {
                out.push(byte as char);
            }
            other => {
                out.push('%');
                out.push_str(&format!("{other:02X}"));
            }
        }
    }
    out
}

fn build_body(request: &CanonicalRequest) -> Result<Value, GeminiRequestError> {
    let mut object = Map::new();
    object.insert("contents".to_owned(), Value::Array(build_contents(request)));
    let mut generation_config = Map::new();
    generation_config.insert(
        "maxOutputTokens".to_owned(),
        Value::from(
            request
                .max_output_tokens
                .unwrap_or(DEFAULT_MAX_OUTPUT_TOKENS),
        ),
    );
    object.insert(
        "generationConfig".to_owned(),
        Value::Object(generation_config),
    );
    let system = build_system_instruction(request);
    if !system.is_empty() {
        object.insert(
            "systemInstruction".to_owned(),
            json!({"parts": [{"text": system}]}),
        );
    }
    if !request.tools.is_empty() {
        let mut names = std::collections::HashSet::new();
        let mut declarations = Vec::with_capacity(request.tools.len());
        for tool in &request.tools {
            let name = provider_tool_name(tool.namespace.as_deref(), &tool.name);
            if !names.insert(name.clone()) {
                return Err(GeminiRequestError {
                    kind: GeminiRequestErrorKind::AmbiguousToolName,
                });
            }
            declarations.push(json!({
                "name": name,
                "description": tool.description,
                "parameters": tool.parameters,
            }));
        }
        object.insert(
            "tools".to_owned(),
            json!([{"functionDeclarations": declarations}]),
        );
        object.insert(
            "toolConfig".to_owned(),
            json!({"functionCallingConfig": {"mode": gemini_tool_mode(&request.tool_choice)}}),
        );
    }
    Ok(Value::Object(object))
}

fn build_system_instruction(request: &CanonicalRequest) -> String {
    request
        .input
        .iter()
        .filter_map(|item| match item {
            InputItem::Message {
                role: MessageRole::Developer | MessageRole::System,
                content,
            } => Some(content),
            _ => None,
        })
        .flat_map(|content| {
            content.iter().filter_map(|block| match block {
                ContentBlock::Text { text } => Some(text.as_str()),
                ContentBlock::ImageReference { .. } => None,
            })
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn build_contents(request: &CanonicalRequest) -> Vec<Value> {
    // A `functionResponse` part must name the function that was called. The
    // canonical `FunctionCallOutput` carries only the opaque call id and the
    // output, so the adapter recovers the provider tool name from the
    // preceding `FunctionCall` item that declared the id.
    let mut call_name = std::collections::HashMap::new();
    for item in &request.input {
        if let InputItem::FunctionCall {
            call_id,
            namespace,
            name,
            ..
        } = item
        {
            call_name.insert(
                call_id.as_str(),
                provider_tool_name(namespace.as_deref(), name),
            );
        }
    }
    request
        .input
        .iter()
        .map(|item| match item {
            InputItem::Message {
                role: MessageRole::User,
                content,
            } => json!({
                "role": "user",
                "parts": gemini_parts(content),
            }),
            InputItem::Message {
                role: MessageRole::Assistant,
                content,
            } => json!({
                "role": "model",
                "parts": gemini_parts(content),
            }),
            InputItem::Message {
                role: MessageRole::Developer | MessageRole::System,
                ..
            } => json!({
                "role": "user",
                "parts": [],
            }),
            InputItem::FunctionCall {
                call_id: _,
                namespace,
                name,
                arguments,
            } => json!({
                "role": "model",
                "parts": [{
                    "functionCall": {
                        "name": provider_tool_name(namespace.as_deref(), name),
                        "args": arguments,
                    }
                }]
            }),
            InputItem::FunctionCallOutput { call_id, output } => {
                let name = call_name
                    .get(call_id.as_str())
                    .map(String::as_str)
                    .unwrap_or("result");
                json!({
                    "role": "user",
                    "parts": [{
                        "functionResponse": {
                            "name": name,
                            "response": {"result": output.to_string()},
                        }
                    }]
                })
            }
        })
        .collect()
}

fn gemini_parts(content: &[ContentBlock]) -> Value {
    Value::Array(
        content
            .iter()
            .filter_map(|block| match block {
                ContentBlock::Text { text } => Some(json!({"text": text})),
                ContentBlock::ImageReference { .. } => {
                    // The canonical request does not carry inline image bytes;
                    // Gemini `inlineData` requires base64. Image parts are
                    // omitted from the wire body; text parts still flow.
                    None
                }
            })
            .collect(),
    )
}

fn provider_tool_name(namespace: Option<&str>, name: &str) -> String {
    namespace.map_or_else(
        || name.to_owned(),
        |namespace| format!("{namespace}__{name}"),
    )
}

fn gemini_tool_mode(tool_choice: &ToolChoice) -> &'static str {
    match tool_choice {
        ToolChoice::Auto => "AUTO",
        ToolChoice::None => "NONE",
        // Gemini has no named single-tool mode; the strictest available mode
        // for a forced call is ANY, and the model selects the single declared
        // function when only one is declared.
        ToolChoice::Required | ToolChoice::Named(_) => "ANY",
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GeminiUsage {
    pub prompt_tokens: u64,
    pub candidates_tokens: u64,
    pub total_tokens: u64,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GeminiStreamEvent {
    ContentDelta { text: String },
    FinishReason { reason: String },
    Usage(GeminiUsage),
    Done,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeminiStreamErrorKind {
    InvalidUtf8,
    InvalidJson,
    InvalidFrame,
    MissingTerminal,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GeminiStreamError {
    pub kind: GeminiStreamErrorKind,
}

impl fmt::Display for GeminiStreamError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("the Gemini stream could not be normalized")
    }
}

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

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct GeminiReplayGuard {
    boundary: Option<ReplayBoundary>,
    body_written: bool,
}

impl GeminiReplayGuard {
    pub fn mark_body_written(&mut self) {
        self.body_written = true;
    }

    pub fn observe(&mut self, event: &GeminiStreamEvent) {
        match event {
            GeminiStreamEvent::ContentDelta { text } if !text.is_empty() => {
                self.cross(ReplayBoundary::PublicContent);
            }
            GeminiStreamEvent::ContentDelta { .. }
            | GeminiStreamEvent::FinishReason { .. }
            | GeminiStreamEvent::Usage(_)
            | GeminiStreamEvent::Done => {}
        }
    }

    pub fn mark_transport_outcome_unknown(&mut self) {
        if self.body_written {
            self.cross(ReplayBoundary::AmbiguousDispatch);
        }
    }

    pub fn decision(&self) -> ReplayDecision {
        self.boundary
            .map_or(ReplayDecision::Allowed, ReplayDecision::Denied)
    }

    fn cross(&mut self, boundary: ReplayBoundary) {
        if self.boundary.is_none() {
            self.boundary = Some(boundary);
        }
    }
}

/// Minimal Gemini `streamGenerateContent` SSE parser. Each SSE `data:` frame
/// carries one `GenerateContentResponse` object (`candidates` with `content`
/// `parts`, a `finishReason`, and `usageMetadata`). The stream is terminal
/// when a candidate carries a `finishReason`; the parser emits `Usage` and
/// `Done` at that boundary. Function-call streaming responses
/// (`functionCall` parts) are not yet normalized for these phases; a
/// text-only response normalizes fully.
pub struct GeminiSseParser {
    _attempt_id: router_protocol::AttemptId,
    replay: GeminiReplayGuard,
    terminal: bool,
    prompt_tokens: u64,
    candidates_tokens: u64,
    total_tokens: u64,
}

impl GeminiSseParser {
    pub fn new(attempt_id: &router_protocol::AttemptId) -> Self {
        Self {
            _attempt_id: attempt_id.clone(),
            replay: GeminiReplayGuard::default(),
            terminal: false,
            prompt_tokens: 0,
            candidates_tokens: 0,
            total_tokens: 0,
        }
    }

    pub fn replay_decision(&self) -> ReplayDecision {
        self.replay.decision()
    }

    pub fn mark_body_written(&mut self) {
        self.replay.mark_body_written();
    }

    pub fn mark_transport_outcome_unknown(&mut self) {
        self.replay.mark_transport_outcome_unknown();
    }

    pub fn feed(&mut self, chunk: &[u8]) -> Result<Vec<GeminiStreamEvent>, GeminiStreamError> {
        let mut events = Vec::new();
        for frame in split_sse_frames(chunk)? {
            let value: Value = serde_json::from_slice(&frame).map_err(|_| GeminiStreamError {
                kind: GeminiStreamErrorKind::InvalidJson,
            })?;
            events.extend(self.observe_json(value)?);
        }
        for event in &events {
            self.replay.observe(event);
        }
        Ok(events)
    }

    pub fn finish(&mut self) -> Result<Vec<GeminiStreamEvent>, GeminiStreamError> {
        if !self.terminal {
            return Err(GeminiStreamError {
                kind: GeminiStreamErrorKind::MissingTerminal,
            });
        }
        Ok(Vec::new())
    }

    fn observe_json(&mut self, value: Value) -> Result<Vec<GeminiStreamEvent>, GeminiStreamError> {
        let mut events = Vec::new();
        if let Some(candidates) = value.get("candidates").and_then(Value::as_array) {
            for candidate in candidates {
                if let Some(text) = candidate
                    .pointer("/content/parts")
                    .and_then(Value::as_array)
                    .and_then(|parts| {
                        parts
                            .iter()
                            .find_map(|part| part.get("text").and_then(Value::as_str))
                    })
                    && !text.is_empty()
                {
                    events.push(GeminiStreamEvent::ContentDelta {
                        text: text.to_owned(),
                    });
                }
                if let Some(reason) = candidate.get("finishReason").and_then(Value::as_str) {
                    events.push(GeminiStreamEvent::FinishReason {
                        reason: reason.to_owned(),
                    });
                    if !self.terminal {
                        self.terminal = true;
                        if let Some(usage) = value.get("usageMetadata") {
                            self.capture_usage(usage);
                        }
                        events.push(GeminiStreamEvent::Usage(GeminiUsage {
                            prompt_tokens: self.prompt_tokens,
                            candidates_tokens: self.candidates_tokens,
                            total_tokens: self.total_tokens,
                        }));
                        events.push(GeminiStreamEvent::Done);
                    }
                }
            }
        }
        if let Some(usage) = value.get("usageMetadata") {
            self.capture_usage(usage);
        }
        Ok(events)
    }

    fn capture_usage(&mut self, usage: &Value) {
        if let Some(prompt) = usage.get("promptTokenCount").and_then(Value::as_u64) {
            self.prompt_tokens = prompt;
        }
        if let Some(candidates) = usage.get("candidatesTokenCount").and_then(Value::as_u64) {
            self.candidates_tokens = candidates;
        }
        if let Some(total) = usage.get("totalTokenCount").and_then(Value::as_u64) {
            self.total_tokens = total;
        }
    }
}

/// Split an SSE byte buffer into one or more `data:` payload frames. Each
/// frame is the concatenation of the `data:` lines of one SSE event, without
/// the `data: ` prefix.
fn split_sse_frames(buffer: &[u8]) -> Result<Vec<Vec<u8>>, GeminiStreamError> {
    let text = std::str::from_utf8(buffer).map_err(|_| GeminiStreamError {
        kind: GeminiStreamErrorKind::InvalidUtf8,
    })?;
    let mut frames = Vec::new();
    let mut current = Vec::new();
    for line in text.split('\n') {
        let line = line.strip_suffix('\r').unwrap_or(line);
        if line.is_empty() {
            if !current.is_empty() {
                frames.push(std::mem::take(&mut current));
            }
            continue;
        }
        if let Some(data) = line.strip_prefix("data:") {
            let data = data.strip_prefix(' ').unwrap_or(data);
            if !current.is_empty() {
                current.push(b'\n');
            }
            current.extend_from_slice(data.as_bytes());
        }
    }
    if !current.is_empty() {
        frames.push(current);
    }
    if frames.is_empty() {
        return Err(GeminiStreamError {
            kind: GeminiStreamErrorKind::InvalidFrame,
        });
    }
    Ok(frames)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeminiFailureClass {
    InvalidRequest,
    Authentication,
    PaymentRequired,
    Authorization,
    NotFound,
    Timeout,
    Unprocessable,
    RateLimited,
    UpstreamServer,
    UnexpectedStatus,
    MismatchedContentType,
    RedirectRejected,
    Cancelled,
    TransportTimeout,
    AmbiguousDispatch,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GeminiFailure {
    pub class: GeminiFailureClass,
    pub status: Option<u16>,
    pub retry_after: Option<crate::ollama_chat::BoundedRetryAfter>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeminiBodyWriteState {
    NotWritten,
    Written,
    Unknown,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GeminiTransportFailureSignal {
    Cancelled,
    Timeout,
}

/// Maps a non-2xx/redirected HTTP response to the failure class. The Gemini
/// protocol is SSE from `POST ...:streamGenerateContent`; a 200 with any other
/// media type is rejected.
pub fn normalize_http_response(
    status: u16,
    content_type: Option<&str>,
    retry_after: Option<&str>,
    redirected: bool,
) -> Result<(), GeminiFailure> {
    if redirected || (300..400).contains(&status) {
        return Err(gemini_failure(
            GeminiFailureClass::RedirectRejected,
            Some(status),
            retry_after,
        ));
    }
    if status != 200 {
        let class = match status {
            400 => GeminiFailureClass::InvalidRequest,
            401 => GeminiFailureClass::Authentication,
            402 => GeminiFailureClass::PaymentRequired,
            403 => GeminiFailureClass::Authorization,
            404 => GeminiFailureClass::NotFound,
            408 => GeminiFailureClass::Timeout,
            422 => GeminiFailureClass::Unprocessable,
            429 => GeminiFailureClass::RateLimited,
            500..=599 => GeminiFailureClass::UpstreamServer,
            _ => GeminiFailureClass::UnexpectedStatus,
        };
        return Err(gemini_failure(class, Some(status), retry_after));
    }
    let media_type = content_type
        .and_then(|value| value.split(';').next())
        .map(str::trim);
    if media_type != Some("text/event-stream") {
        return Err(gemini_failure(
            GeminiFailureClass::MismatchedContentType,
            Some(status),
            None,
        ));
    }
    Ok(())
}

pub fn normalize_transport_failure(
    signal: GeminiTransportFailureSignal,
    body_write: GeminiBodyWriteState,
) -> GeminiFailure {
    let class = match body_write {
        GeminiBodyWriteState::Written | GeminiBodyWriteState::Unknown => {
            GeminiFailureClass::AmbiguousDispatch
        }
        GeminiBodyWriteState::NotWritten => match signal {
            GeminiTransportFailureSignal::Cancelled => GeminiFailureClass::Cancelled,
            GeminiTransportFailureSignal::Timeout => GeminiFailureClass::TransportTimeout,
        },
    };
    gemini_failure(class, None, None)
}

fn gemini_failure(
    class: GeminiFailureClass,
    status: Option<u16>,
    retry_after: Option<&str>,
) -> GeminiFailure {
    GeminiFailure {
        class,
        status,
        retry_after: crate::ollama_chat::BoundedRetryAfter::parse(retry_after),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use router_protocol::{
        BillingAuthorityClass, CapabilityRequirements, CatalogSourceKind, CredentialSourceKind,
        EndpointIdentity, ExecutionLocation, FunctionTool, HarnessInstanceId, M1_WIRE_VERSION,
        MessageRole, ModelNamespace, PhaseKind, PhasePlacement, ProviderService, ReasoningIntent,
        SessionId, TurnId,
    };

    fn gemini_route(phase: PhaseKind, billing: BillingAuthorityClass) -> RouteIdentity {
        RouteIdentity {
            phase,
            placement: PhasePlacement::Builtin,
            provider: ProviderService::Gemini,
            transport: TransportKind::DirectHttps,
            endpoint: EndpointIdentity {
                origin: router_protocol::GEMINI_ORIGIN.to_owned(),
                path: router_protocol::GEMINI_GENERATE_CONTENT_PATH.to_owned(),
            },
            credential_source: CredentialSourceKind::SecretRef,
            credential_ref: Some("env:STEADYMUX_GEMINI_KEY".to_owned()),
            credential_refs: vec!["env:STEADYMUX_GEMINI_KEY".to_owned()],
            catalog_source: CatalogSourceKind::GeminiCatalog,
            catalog_ref: "catalog:gemini:verified".to_owned(),
            billing_authority: billing,
            model_namespace: ModelNamespace::Gemini,
            model_id: "gemini-2.5-flash".to_owned(),
            execution_location: ExecutionLocation::RemoteCloud,
            account_ref: "account:gemini".to_owned(),
            capacity_domain_ref: "capacity:gemini".to_owned(),
            local_execution_proof: false,
            approved_local_inventory: Vec::new(),
            reasoning_modes: Vec::new(),
        }
    }

    fn request(prompt: &str) -> CanonicalRequest {
        CanonicalRequest {
            wire_version: M1_WIRE_VERSION.to_owned(),
            model: "router-auto".to_owned(),
            stream: true,
            harness_instance: HarnessInstanceId::parse("fixture-cli").expect("fixture"),
            session_id: SessionId::parse("session-gemini").expect("fixture"),
            turn_id: TurnId::parse("turn-gemini").expect("fixture"),
            input: vec![InputItem::Message {
                role: MessageRole::User,
                content: vec![ContentBlock::Text {
                    text: prompt.to_owned(),
                }],
            }],
            tools: vec![FunctionTool {
                namespace: Some("forecast".to_owned()),
                name: "current".to_owned(),
                description: "current forecast".to_owned(),
                parameters: json!({"type":"object"}),
                strict: true,
            }],
            tool_choice: ToolChoice::Auto,
            structured_output: None,
            reasoning: ReasoningIntent::None,
            max_output_tokens: Some(256),
            max_spend_micro_usd: None,
            capabilities: CapabilityRequirements::default(),
        }
    }

    #[test]
    fn gemini_routes_build_verified_generate_content_wire_shape() {
        // PRD-001y AC-06: the Gemini phases build a `generateContent` request
        // against `https://generativelanguage.googleapis.com` with the
        // `x-goog-api-key` auth scheme and the model id materialized in the
        // streaming path.
        for (phase, billing) in [
            (
                PhaseKind::GeminiSubscription,
                BillingAuthorityClass::GeminiSubscription,
            ),
            (
                PhaseKind::GeminiApi,
                BillingAuthorityClass::GeminiMeteredApi,
            ),
        ] {
            let route = gemini_route(phase, billing);
            route.validate().expect("valid gemini route");
            let spec = build_request(&route, &request("gemini-canary")).expect("request");
            assert_eq!(spec.method, HttpMethod::Post);
            assert_eq!(spec.origin, router_protocol::GEMINI_ORIGIN);
            assert_eq!(
                spec.path,
                "/v1beta/models/gemini-2.5-flash:streamGenerateContent"
            );
            assert_eq!(spec.accept, "text/event-stream");
            assert_eq!(spec.api_key_secret.as_str(), "env:STEADYMUX_GEMINI_KEY");
            assert!(spec.network.require_tls);
            assert!(!spec.network.follow_redirects);
            assert!(!spec.network.allow_proxy);
            assert!(spec.body().get("model").is_none());
            assert_eq!(spec.body()["contents"][0]["role"], json!("user"));
            assert_eq!(
                spec.body()["contents"][0]["parts"][0]["text"],
                json!("gemini-canary")
            );
            assert_eq!(
                spec.body()["generationConfig"]["maxOutputTokens"],
                json!(256)
            );
            assert_eq!(
                spec.body()["tools"][0]["functionDeclarations"][0]["name"],
                json!("forecast__current")
            );
            assert_eq!(
                spec.body()["toolConfig"]["functionCallingConfig"]["mode"],
                json!("AUTO")
            );
        }
    }

    #[test]
    fn gemini_adapter_has_no_hardcoded_model_id_and_exposes_projection() {
        // PRD-001y AC-07: model ids are catalog driven, never hardcoded in the
        // adapter, and the adapter exposes the per-route MAv2 capability
        // projection.
        let adapter_core = include_str!("gemini_chat.rs")
            .split("#[cfg(test)]")
            .next()
            .expect("adapter body precedes the test module");
        for model_literal in [
            concat!("gemini", "-2"),
            concat!("gemini", "-3"),
            concat!("gemini", "-pro"),
            concat!("gemini", "-flash"),
        ] {
            assert!(
                !adapter_core.contains(model_literal),
                "adapter hardcodes the model literal {model_literal}"
            );
        }
        assert!(is_gemini_phase(PhaseKind::GeminiSubscription));
        assert!(is_gemini_phase(PhaseKind::GeminiApi));
        assert!(!is_gemini_phase(PhaseKind::ClaudeApi));
        assert!(!capability_projection().namespace_tools);
        assert_eq!(
            PhaseKind::GeminiApi.multi_agent_v2_projection(),
            capability_projection()
        );
    }

    #[test]
    fn gemini_sse_parses_text_finish_and_usage_once() {
        let transcript = concat!(
            "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"hello \"}]},\"finishReason\":null}],\"usageMetadata\":{\"promptTokenCount\":9,\"candidatesTokenCount\":0,\"totalTokenCount\":9}}\n\n",
            "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"world\"}]},\"finishReason\":null}]}\n\n",
            "data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"\"}]},\"finishReason\":\"STOP\"}],\"usageMetadata\":{\"promptTokenCount\":9,\"candidatesTokenCount\":5,\"totalTokenCount\":14}}\n\n",
        );
        let attempt = router_protocol::AttemptId::parse("attempt-gemini-1").expect("attempt");
        let mut parser = GeminiSseParser::new(&attempt);
        let events = parser
            .feed(transcript.as_bytes())
            .expect("feed gemini stream");
        assert_eq!(
            events,
            vec![
                GeminiStreamEvent::ContentDelta {
                    text: "hello ".to_owned()
                },
                GeminiStreamEvent::ContentDelta {
                    text: "world".to_owned()
                },
                GeminiStreamEvent::FinishReason {
                    reason: "STOP".to_owned()
                },
                GeminiStreamEvent::Usage(GeminiUsage {
                    prompt_tokens: 9,
                    candidates_tokens: 5,
                    total_tokens: 14,
                }),
                GeminiStreamEvent::Done,
            ]
        );
        assert_eq!(parser.finish(), Ok(vec![]));
        assert!(parser.replay_decision() != ReplayDecision::Allowed);
    }

    #[test]
    fn gemini_stream_requires_terminal() {
        let attempt = router_protocol::AttemptId::parse("attempt-gemini-2").expect("attempt");
        let mut parser = GeminiSseParser::new(&attempt);
        parser
            .feed(
                b"data: {\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"partial\"}]},\"finishReason\":null}]}\n\n",
            )
            .expect("feed");
        assert_eq!(
            parser.finish(),
            Err(GeminiStreamError {
                kind: GeminiStreamErrorKind::MissingTerminal
            })
        );
    }
}