gaise-api 5.8.0

Axum HTTP server for GAISe — exposes /v1/instruct, /v1/instruct/stream, and /v1/embeddings
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
use axum::{
    Json, Router,
    extract::{Path, Query, State},
    http::StatusCode,
    response::{
        IntoResponse,
        sse::{Event, Sse},
    },
    routing::{get, post},
};
use futures_util::StreamExt;
use gaise_client::GaiseClientService;
use gaise_core::{
    GaiseClient,
    contracts::{
        GaiseContent, GaiseContentEmbeddingsRequest, GaiseDecisionRequest, GaiseEmbeddingsRequest,
        GaiseImageRequest, GaiseInstructRequest, GaiseListModelsRequest, GaiseOperation,
        GaiseTranscriptionRequest, GaiseVideoJobRequest, GaiseVideoRequest,
    },
    registry,
};
use std::sync::Arc;
use tracing::error;

#[cfg(feature = "live")]
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
#[cfg(feature = "live")]
use gaise_core::{
    GaiseLiveClient,
    contracts::{GaiseLiveConfig, GaiseLiveEvent, GaiseLiveInput},
};
#[cfg(any(feature = "elevenlabs", feature = "xai"))]
use gaise_core::{
    GaiseSpeechClient,
    contracts::{GaiseSpeechChunk, GaiseSpeechRequest},
};

pub struct AppState {
    pub client_service: GaiseClientService,
}

pub fn create_app(state: Arc<AppState>) -> Router {
    let router = Router::new()
        .route("/v1/decision", post(handle_decision))
        // Same handler: the path TypeSafe and Ollama use for this protocol.
        .route("/v1/systemone", post(handle_decision))
        .route("/v1/instruct", post(handle_instruct))
        .route("/v1/instruct/stream", post(handle_instruct_stream))
        .route("/v1/embeddings", post(handle_embeddings))
        .route("/v1/embeddings/contents", post(handle_content_embeddings))
        .route("/v1/models", get(handle_list_models))
        .route("/v1/models/limits", get(handle_model_limits))
        .route("/v1/models/:model", get(handle_get_model))
        .route("/v1/transcriptions", post(handle_transcribe))
        .route("/v1/images", post(handle_images))
        .route("/v1/videos", post(handle_start_video))
        .route("/v1/videos/:id", get(handle_get_video));

    #[cfg(feature = "live")]
    let router = router
        .route("/v1/live", axum::routing::get(handle_live_ws))
        .route(
            "/v1/transcriptions/live",
            axum::routing::get(handle_transcription_ws),
        );

    #[cfg(any(feature = "elevenlabs", feature = "xai"))]
    let router = router
        .route("/v1/speech", post(handle_speech))
        .route("/v1/speech/stream", post(handle_speech_stream))
        .route("/v1/speech/audio", post(handle_speech_audio));

    router.with_state(state)
}

/// `POST /v1/decision` body: a decision request plus optional `images`
/// (`GaiseContent` image items) shared by every question.
#[derive(serde::Deserialize)]
struct DecisionBody {
    #[serde(flatten)]
    request: GaiseDecisionRequest,
    #[serde(default)]
    images: Vec<GaiseContent>,
}

async fn handle_decision(
    State(state): State<Arc<AppState>>,
    Json(body): Json<DecisionBody>,
) -> impl IntoResponse {
    let DecisionBody { request, images } = body;
    if let Err(error) = request.validate() {
        return (StatusCode::BAD_REQUEST, error).into_response();
    }
    match state
        .client_service
        .decision_with_images(&request, &images)
        .await
    {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Decision error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_instruct(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseInstructRequest>,
) -> impl IntoResponse {
    match state.client_service.instruct(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Instruct error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_instruct_stream(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseInstructRequest>,
) -> impl IntoResponse {
    match state.client_service.instruct_stream(&request).await {
        Ok(stream) => {
            let sse_stream = stream.map(|item| match item {
                Ok(chunk) => Event::default().json_data(chunk),
                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
            });
            Sse::new(sse_stream).into_response()
        }
        Err(e) => {
            error!("Instruct stream error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_embeddings(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseEmbeddingsRequest>,
) -> impl IntoResponse {
    match state.client_service.embeddings(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Embeddings error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

async fn handle_content_embeddings(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseContentEmbeddingsRequest>,
) -> impl IntoResponse {
    if let Err(error) = request.validate() {
        return (StatusCode::BAD_REQUEST, error).into_response();
    }
    match state.client_service.embed_contents(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Embeddings error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

// ── Media endpoints ────────────────────────────────────────────────

/// Validation failures are the caller's (400); everything else is a
/// provider or routing failure (500).
fn media_error(
    what: &str,
    e: Box<dyn std::error::Error + Send + Sync>,
) -> axum::response::Response {
    error!("{what} error: {e}");
    (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
}

/// `POST /v1/transcriptions` — `GaiseTranscriptionRequest` (audio as a
/// `bytes` or `url` media source) to `GaiseTranscriptionResponse`.
async fn handle_transcribe(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseTranscriptionRequest>,
) -> impl IntoResponse {
    if let Err(e) = request.validate() {
        return (StatusCode::BAD_REQUEST, e).into_response();
    }
    match state.client_service.transcribe(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => media_error("Transcription", e),
    }
}

/// `POST /v1/images` — generate or edit images.
async fn handle_images(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseImageRequest>,
) -> impl IntoResponse {
    if let Err(e) = request.validate() {
        return (StatusCode::BAD_REQUEST, e).into_response();
    }
    match state.client_service.generate_images(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => media_error("Image generation", e),
    }
}

/// `POST /v1/videos` — start a video job; returns `202` with the job.
async fn handle_start_video(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseVideoRequest>,
) -> impl IntoResponse {
    if let Err(e) = request.validate() {
        return (StatusCode::BAD_REQUEST, e).into_response();
    }
    match state.client_service.start_video(&request).await {
        Ok(job) => (StatusCode::ACCEPTED, Json(job)).into_response(),
        Err(e) => media_error("Video generation", e),
    }
}

/// Query for `GET /v1/videos/{id}`.
#[derive(Debug, serde::Deserialize)]
pub struct VideoJobQuery {
    /// The `provider::model` the job was started with.
    pub model: String,
    pub correlation_id: Option<String>,
}

/// `GET /v1/videos/{id}?model=provider::model` — poll a video job. The id is
/// the job id returned by `POST /v1/videos`, URL-encoded (Google operation
/// names and Bedrock ARNs contain `/` and `:`).
async fn handle_get_video(
    State(state): State<Arc<AppState>>,
    Path(id): Path<String>,
    Query(query): Query<VideoJobQuery>,
) -> impl IntoResponse {
    let request = GaiseVideoJobRequest {
        model: query.model,
        id,
        correlation_id: query.correlation_id,
        connection: None,
    };
    match state.client_service.get_video(&request).await {
        Ok(job) => Json(job).into_response(),
        Err(e) => media_error("Video status", e),
    }
}

/// Query parameters for `GET /v1/models`.
#[derive(Debug, Default, serde::Deserialize)]
pub struct ListModelsQuery {
    /// Restrict to one provider key.
    pub provider: Option<String>,
    /// Keep only models supporting this operation
    /// (`instruct`, `instruct_stream`, `embeddings`, `speech`, `live`, `decision`).
    pub operation: Option<String>,
    /// Fetch per-model detail where it costs extra requests (Ollama).
    #[serde(default)]
    pub include_details: bool,
    /// Attach each provider's native record.
    #[serde(default)]
    pub include_raw: bool,
    pub correlation_id: Option<String>,
}

impl ListModelsQuery {
    fn into_request(self) -> Result<GaiseListModelsRequest, String> {
        let operation = match self.operation.as_deref() {
            None | Some("") => None,
            Some(value) => Some(
                GaiseOperation::parse(value)
                    .ok_or_else(|| format!("unknown operation '{value}'"))?,
            ),
        };
        Ok(GaiseListModelsRequest {
            provider: self.provider.filter(|p| !p.is_empty()),
            operation,
            include_details: self.include_details,
            include_raw: self.include_raw,
            correlation_id: self.correlation_id,
            connection: None,
        })
    }
}

async fn handle_list_models(
    State(state): State<Arc<AppState>>,
    Query(query): Query<ListModelsQuery>,
) -> impl IntoResponse {
    let request = match query.into_request() {
        Ok(request) => request,
        Err(message) => return (StatusCode::BAD_REQUEST, message).into_response(),
    };
    match state.client_service.list_models(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("List models error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// Query parameters for `GET /v1/models/limits`.
#[derive(Debug, Default, serde::Deserialize)]
pub struct ModelLimitsQuery {
    /// Restrict to one provider key.
    pub provider: Option<String>,
    /// Keep only entries mapped to this operation.
    pub operation: Option<String>,
}

/// `GET /v1/models/limits` — the registry's model × limits matrix
/// (`context_window`, `max_input_tokens`, `max_output_tokens`,
/// `embedding_dimensions`), served without contacting any provider or
/// needing credentials. `GET /v1/models` carries the same fields per model,
/// with provider-reported values taking precedence over the registry.
async fn handle_model_limits(Query(query): Query<ModelLimitsQuery>) -> impl IntoResponse {
    let operation = match query.operation.as_deref() {
        None | Some("") => None,
        Some(value) => match GaiseOperation::parse(value) {
            Some(op) => Some(op),
            None => {
                return (
                    StatusCode::BAD_REQUEST,
                    format!("unknown operation '{value}'"),
                )
                    .into_response();
            }
        },
    };
    let provider = query.provider.filter(|p| !p.is_empty());
    let mut matrix = registry::limits_matrix(provider.as_deref());
    if let Some(operation) = operation {
        matrix.models.retain(|m| m.operations.contains(&operation));
    }
    Json(matrix).into_response()
}

/// `GET /v1/models/{provider}::{id}` — one model from one provider's listing.
async fn handle_get_model(
    State(state): State<Arc<AppState>>,
    Path(model): Path<String>,
    Query(query): Query<ListModelsQuery>,
) -> impl IntoResponse {
    let Some((provider, _)) = model.split_once("::") else {
        return (
            StatusCode::BAD_REQUEST,
            "model must be in the format 'provider::model'".to_string(),
        )
            .into_response();
    };
    let request = GaiseListModelsRequest {
        provider: Some(provider.to_string()),
        operation: None,
        include_details: query.include_details,
        include_raw: query.include_raw,
        correlation_id: query.correlation_id,
        connection: None,
    };
    match state.client_service.list_models(&request).await {
        Ok(response) => match response.models.into_iter().find(|m| m.id == model) {
            Some(found) => Json(found).into_response(),
            None => (
                StatusCode::NOT_FOUND,
                format!("model '{model}' not listed by {provider}"),
            )
                .into_response(),
        },
        Err(e) => {
            error!("Get model error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

// ── Speech endpoints ───────────────────────────────────────────────

/// `POST /v1/speech` — full clip as JSON (`audio` is a byte array).
#[cfg(any(feature = "elevenlabs", feature = "xai"))]
async fn handle_speech(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    match state.client_service.speech(&request).await {
        Ok(response) => Json(response).into_response(),
        Err(e) => {
            error!("Speech error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// `POST /v1/speech/stream` — SSE of `GaiseSpeechStreamResponse` (audio,
/// alignment, usage chunks).
#[cfg(any(feature = "elevenlabs", feature = "xai"))]
async fn handle_speech_stream(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    match state.client_service.speech_stream(&request).await {
        Ok(stream) => {
            let sse_stream = stream.map(|item| match item {
                Ok(chunk) => Event::default().json_data(chunk),
                Err(e) => Ok(Event::default().event("error").data(e.to_string())),
            });
            Sse::new(sse_stream).into_response()
        }
        Err(e) => {
            error!("Speech stream error: {}", e);
            (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response()
        }
    }
}

/// `POST /v1/speech/audio` — raw audio bytes, chunked as the provider
/// produces them, with the MIME type in `Content-Type` and the PCM rate in
/// `X-Gaise-Sample-Rate`. Alignment and usage chunks are dropped.
#[cfg(any(feature = "elevenlabs", feature = "xai"))]
async fn handle_speech_audio(
    State(state): State<Arc<AppState>>,
    Json(request): Json<GaiseSpeechRequest>,
) -> impl IntoResponse {
    use axum::body::Body;
    use futures_util::StreamExt as _;

    let mut stream = match state.client_service.speech_stream(&request).await {
        Ok(stream) => stream,
        Err(e) => {
            error!("Speech audio error: {}", e);
            return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
        }
    };
    // Peek the first audio chunk so the headers can carry the real format.
    let mut first: Option<(Vec<u8>, String, Option<u32>)> = None;
    while let Some(item) = stream.next().await {
        match item {
            Ok(resp) => {
                if let GaiseSpeechChunk::Audio {
                    data,
                    format,
                    sample_rate,
                } = resp.chunk
                {
                    first = Some((data, format, sample_rate));
                    break;
                }
            }
            Err(e) => {
                error!("Speech audio error: {}", e);
                return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response();
            }
        }
    }
    let Some((head, format, sample_rate)) = first else {
        return (
            StatusCode::BAD_GATEWAY,
            "provider returned no audio".to_string(),
        )
            .into_response();
    };
    let rest = stream.filter_map(|item| async move {
        match item {
            Ok(resp) => match resp.chunk {
                GaiseSpeechChunk::Audio { data, .. } => Some(Ok::<_, std::io::Error>(data)),
                _ => None,
            },
            Err(e) => Some(Err(std::io::Error::other(e.to_string()))),
        }
    });
    let body = Body::from_stream(futures_util::stream::once(async move { Ok(head) }).chain(rest));
    let mut response = axum::response::Response::new(body);
    response.headers_mut().insert(
        axum::http::header::CONTENT_TYPE,
        axum::http::HeaderValue::from_str(&format).unwrap_or(axum::http::HeaderValue::from_static(
            "application/octet-stream",
        )),
    );
    if let Some(rate) = sample_rate
        && let Ok(value) = axum::http::HeaderValue::from_str(&rate.to_string())
    {
        response.headers_mut().insert("x-gaise-sample-rate", value);
    }
    response
}

// ── Live WebSocket endpoint ─────────────────────────────────────────

#[cfg(feature = "live")]
async fn handle_live_ws(
    ws: WebSocketUpgrade,
    State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_live_session(socket, state))
}

#[cfg(feature = "live")]
async fn handle_live_session(socket: WebSocket, state: Arc<AppState>) {
    use futures_util::SinkExt;

    let (mut ws_sink, mut ws_source) = socket.split();

    // First message must be a config message
    let config: GaiseLiveConfig = loop {
        match ws_source.next().await {
            Some(Ok(Message::Text(text))) => match serde_json::from_str::<GaiseLiveConfig>(&text) {
                Ok(cfg) => break cfg,
                Err(e) => {
                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {}", e)});
                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
                    return;
                }
            },
            Some(Ok(Message::Close(_))) | None => return,
            _ => continue,
        }
    };

    // Connect to provider
    let session = match state.client_service.live_connect(&config).await {
        Ok(s) => s,
        Err(e) => {
            let err =
                serde_json::json!({"type": "error", "message": format!("Connect error: {}", e)});
            let _ = ws_sink.send(Message::Text(err.to_string())).await;
            return;
        }
    };

    let input_tx = session.tx;
    let mut event_rx = session.rx;

    // Forward provider events → client WebSocket
    let send_handle = tokio::spawn(async move {
        while let Some(event) = event_rx.next().await {
            let msg = match event {
                Ok(GaiseLiveEvent::Audio { data, sample_rate }) => {
                    // Send audio as binary frames
                    // Prepend 4-byte sample rate header for client to know the rate
                    let mut frame = Vec::with_capacity(4 + data.len());
                    frame.extend_from_slice(&sample_rate.to_le_bytes());
                    frame.extend_from_slice(&data);
                    Message::Binary(frame)
                }
                Ok(event) => match serde_json::to_string(&event) {
                    Ok(json) => Message::Text(json),
                    Err(_) => continue,
                },
                Err(e) => {
                    let err = serde_json::json!({"type": "error", "message": e.to_string()});
                    Message::Text(err.to_string())
                }
            };
            if ws_sink.send(msg).await.is_err() {
                break;
            }
        }
    });

    // Forward client WebSocket → provider input channel
    while let Some(msg) = ws_source.next().await {
        let msg = match msg {
            Ok(m) => m,
            Err(_) => break,
        };

        let input = match msg {
            Message::Text(text) => match serde_json::from_str::<GaiseLiveInput>(&text) {
                Ok(input) => input,
                Err(_) => continue,
            },
            Message::Binary(data) => {
                // Binary frames are raw PCM audio (16kHz PCM16 by default)
                GaiseLiveInput::Audio {
                    data: data.to_vec(),
                    sample_rate: 16000,
                }
            }
            Message::Close(_) => {
                let _ = input_tx.send(GaiseLiveInput::Close).await;
                break;
            }
            _ => continue,
        };

        if input_tx.send(input).await.is_err() {
            break;
        }
    }

    // Cleanup
    let _ = input_tx.send(GaiseLiveInput::Close).await;
    send_handle.abort();
}

// ── Streaming transcription WebSocket ──────────────────────────────

#[cfg(feature = "live")]
async fn handle_transcription_ws(
    ws: WebSocketUpgrade,
    State(state): State<Arc<AppState>>,
) -> impl IntoResponse {
    ws.on_upgrade(move |socket| handle_transcription_session(socket, state))
}

/// First text frame: `GaiseTranscriptionSessionConfig`. Then binary frames
/// are audio in the configured format, and text frames are
/// `GaiseTranscriptionInput` (`commit`, `close`). Every event goes back as a
/// JSON text frame.
#[cfg(feature = "live")]
async fn handle_transcription_session(socket: WebSocket, state: Arc<AppState>) {
    use futures_util::SinkExt;
    use gaise_core::contracts::{GaiseTranscriptionInput, GaiseTranscriptionSessionConfig};

    let (mut ws_sink, mut ws_source) = socket.split();
    let config: GaiseTranscriptionSessionConfig = loop {
        match ws_source.next().await {
            Some(Ok(Message::Text(text))) => match serde_json::from_str(&text) {
                Ok(cfg) => break cfg,
                Err(e) => {
                    let err = serde_json::json!({"type": "error", "message": format!("Invalid config: {e}")});
                    let _ = ws_sink.send(Message::Text(err.to_string())).await;
                    return;
                }
            },
            Some(Ok(Message::Close(_))) | None => return,
            _ => continue,
        }
    };

    let session = match state.client_service.transcribe_connect(&config).await {
        Ok(s) => s,
        Err(e) => {
            let err =
                serde_json::json!({"type": "error", "message": format!("Connect error: {e}")});
            let _ = ws_sink.send(Message::Text(err.to_string())).await;
            return;
        }
    };
    let input_tx = session.tx;
    let mut event_rx = session.rx;

    let send_handle = tokio::spawn(async move {
        while let Some(event) = event_rx.next().await {
            let text = match event {
                Ok(event) => match serde_json::to_string(&event) {
                    Ok(json) => json,
                    Err(_) => continue,
                },
                Err(e) => {
                    serde_json::json!({"type": "error", "message": e.to_string()}).to_string()
                }
            };
            if ws_sink.send(Message::Text(text)).await.is_err() {
                break;
            }
        }
    });

    while let Some(Ok(msg)) = ws_source.next().await {
        let input = match msg {
            Message::Binary(data) => GaiseTranscriptionInput::Audio {
                data: data.to_vec(),
            },
            Message::Text(text) => match serde_json::from_str::<GaiseTranscriptionInput>(&text) {
                Ok(input) => input,
                Err(_) => continue,
            },
            Message::Close(_) => break,
            _ => continue,
        };
        if input_tx.send(input).await.is_err() {
            break;
        }
    }
    let _ = input_tx.send(GaiseTranscriptionInput::Close).await;
    // Let the provider deliver the final transcript before tearing down.
    let _ = tokio::time::timeout(std::time::Duration::from_secs(10), send_handle).await;
}