aurum-core 0.0.19

On-device speech I/O core: whisper.cpp STT, ONNX TTS, cleanup, providers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! OpenRouter remote TTS via OpenAI-compatible `/audio/speech` (JOE-1939).
//!
//! Direction-specific from [`super::openrouter::OpenRouterProvider`] (STT).
//! Prefer PCM wire format and normalize through [`crate::audio::normalize_remote_audio`].

use crate::audio::{normalize_remote_audio, BoundedAudioBody, RemoteAudioLimits};
use crate::error::{ProviderError, Result, UserError};
use crate::remote::{
    map_http_status, read_body_limited_with_op, resolve_encoded_format, send_with_op,
    ExpectedWireFormat, HardenedHttpClient, OpenAiSpeechRequest, RemoteBodyLimits, RemotePolicy,
    SpeechResponseFormat,
};
use crate::runtime::{OpContext, PermitKind, ResourceGovernor};
use crate::secret::SecretString;
use crate::tts::provider::{BackendKind, SynthesisOptions, SynthesisProvider, SynthesisResult};
use crate::tts::validate::{clamp_speaking_rate, SPEAKING_RATE_MAX, SPEAKING_RATE_MIN};
use async_trait::async_trait;
use std::sync::Arc;
use std::time::Duration;

const PROVIDER_NAME: &str = "openrouter";

/// Default OpenRouter TTS model: exact dated id from OpenRouter TTS docs (JOE-1978).
///
/// Support tier is **experimental** until a protected live smoke is retained.
/// Bare undated `openai/gpt-4o-mini-tts` is not accepted (no silent alias).
pub const DEFAULT_OPENROUTER_TTS_MODEL: &str = "openai/gpt-4o-mini-tts-2025-12-15";

/// Default OpenAI-compatible voice for the reviewed OpenAI-family TTS model.
pub const DEFAULT_OPENROUTER_TTS_VOICE: &str = "alloy";

/// Static evidence date for the reviewed registry (UTC calendar day).
pub const OPENROUTER_TTS_EVIDENCE_DATE: &str = "2026-08-02";

/// Support tier for a reviewed OpenRouter TTS record.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenRouterTtsTier {
    /// Protected live smoke retained; ordinary CI may use mocks.
    Supported,
    /// Implemented + mocks; no protected live evidence yet.
    Experimental,
    /// Requires deliberate model selection; not a default.
    ExplicitOnly,
}

/// Reviewed OpenRouter TTS catalogue entry (fail closed for unknown models).
#[derive(Debug, Clone, Copy)]
pub struct OpenRouterTtsRecord {
    pub model: &'static str,
    pub voices: &'static [&'static str],
    pub default_sample_rate_hz: u32,
    pub max_text_chars: usize,
    pub rate_min: f32,
    pub rate_max: f32,
    pub tier: OpenRouterTtsTier,
    /// UTC YYYY-MM-DD for last human/doc evidence note (not live discovery).
    pub evidence_date: &'static str,
    pub evidence_source: &'static str,
}

/// Static reviewed TTS models for OpenRouter (JOE-1939 / JOE-1978).
///
/// None of these are promoted to [`OpenRouterTtsTier::Supported`] without a
/// protected credentialed speech smoke. Discovery via
/// `GET /api/v1/models?output_modalities=speech` is an explicit refresh workflow
/// (offline startup never fetches).
pub static OPENROUTER_TTS_REGISTRY: &[OpenRouterTtsRecord] = &[
    OpenRouterTtsRecord {
        // Official OpenRouter TTS guide exact model id (2025-12-15 pin).
        model: "openai/gpt-4o-mini-tts-2025-12-15",
        voices: &[
            "alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer",
            "verse",
        ],
        default_sample_rate_hz: 24_000,
        max_text_chars: 4_096,
        rate_min: 0.25,
        rate_max: 4.0,
        tier: OpenRouterTtsTier::Experimental,
        evidence_date: OPENROUTER_TTS_EVIDENCE_DATE,
        evidence_source: "openrouter.ai/docs TTS guide exact model id; protected smoke pending",
    },
    OpenRouterTtsRecord {
        // Present in Models API speech modality listing (2026-08-02 probe); explicit-only.
        model: "mistralai/voxtral-mini-tts-2603",
        voices: &["alloy"], // conservative; provider may ignore — not advertised as guaranteed
        default_sample_rate_hz: 24_000,
        max_text_chars: 4_096,
        rate_min: 0.25,
        rate_max: 4.0,
        tier: OpenRouterTtsTier::ExplicitOnly,
        evidence_date: OPENROUTER_TTS_EVIDENCE_DATE,
        evidence_source:
            "models?output_modalities=speech listing; explicit-only until voice evidence",
    },
];

pub fn lookup_openrouter_tts(model: &str) -> Option<&'static OpenRouterTtsRecord> {
    let m = model.trim();
    OPENROUTER_TTS_REGISTRY
        .iter()
        .find(|r| r.model.eq_ignore_ascii_case(m))
}

/// Whether `model_id` appears in a Models API speech-modality id list (bounded fixture).
pub fn openrouter_tts_model_in_discovery(model_id: &str, discovered_ids: &[&str]) -> bool {
    discovered_ids
        .iter()
        .any(|id| id.eq_ignore_ascii_case(model_id.trim()))
}

/// Remote OpenRouter TTS provider (speech endpoint only).
pub struct OpenRouterTtsProvider {
    api_key: SecretString,
    http: HardenedHttpClient,
    governor: Arc<ResourceGovernor>,
}

impl std::fmt::Debug for OpenRouterTtsProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("OpenRouterTtsProvider")
            .field("base_url", &self.http.base_url())
            .field("api_key", &"***")
            .finish()
    }
}

impl OpenRouterTtsProvider {
    pub fn with_policy(
        api_key: Option<SecretString>,
        base_url: Option<String>,
        mut policy: RemotePolicy,
    ) -> Result<Self> {
        let api_key = api_key
            .filter(|s| !s.expose().trim().is_empty())
            .ok_or(UserError::MissingApiKey)?;

        if base_url
            .as_deref()
            .is_some_and(|u| u.contains("127.0.0.1") || u.contains("localhost"))
        {
            policy.allow_loopback_http = true;
        }

        let http = HardenedHttpClient::openrouter(base_url.as_deref(), policy)?;
        Ok(Self {
            api_key,
            http,
            governor: ResourceGovernor::process_global(),
        })
    }

    /// Bind an engine-local governor (preferred for long-lived hosts).
    pub fn with_governor(mut self, governor: Arc<ResourceGovernor>) -> Self {
        self.governor = governor;
        self
    }

    fn resolve_model_voice(
        model: &str,
        voice: &str,
    ) -> Result<(&'static OpenRouterTtsRecord, String)> {
        let rec = lookup_openrouter_tts(model).ok_or_else(|| UserError::UnsupportedCapability {
            provider: PROVIDER_NAME.into(),
            model: model.into(),
            reason: "model is not in the reviewed OpenRouter TTS registry".into(),
            hint: format!(
                "use one of: {}",
                OPENROUTER_TTS_REGISTRY
                    .iter()
                    .map(|r| r.model)
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        })?;
        let voice = voice.trim();
        if voice.is_empty() {
            return Ok((rec, DEFAULT_OPENROUTER_TTS_VOICE.into()));
        }
        // Never remap local Kitten/Kokoro aliases — only accept provider voice ids.
        let ok = rec.voices.iter().any(|v| v.eq_ignore_ascii_case(voice));
        if !ok {
            return Err(UserError::UnsupportedCapability {
                provider: PROVIDER_NAME.into(),
                model: model.into(),
                reason: format!("voice '{voice}' is not supported for this OpenRouter TTS model"),
                hint: format!("supported voices: {}", rec.voices.join(", ")),
            }
            .into());
        }
        // Canonical lowercase OpenAI voice ids.
        Ok((rec, voice.to_ascii_lowercase()))
    }
}

#[async_trait]
impl SynthesisProvider for OpenRouterTtsProvider {
    fn name(&self) -> &'static str {
        PROVIDER_NAME
    }

    async fn synthesize(&self, text: &str, opts: &SynthesisOptions) -> Result<SynthesisResult> {
        if opts.pack_dir.is_some() || opts.allow_unverified {
            return Err(UserError::UnsupportedCapability {
                provider: PROVIDER_NAME.into(),
                model: opts.model.clone(),
                reason: "local pack_dir/allow_unverified are not valid for remote TTS".into(),
                hint: "omit pack_dir; use a local TTS provider for custom packs".into(),
            }
            .into());
        }

        if opts.local_only {
            return Err(UserError::UnsupportedCapability {
                provider: PROVIDER_NAME.into(),
                model: opts.model.clone(),
                reason: "remote TTS is disabled under local_only".into(),
                hint: "unset local_only or use provider=local".into(),
            }
            .into());
        }

        let text = text.trim();
        if text.is_empty() {
            return Err(UserError::Other {
                message: "TTS text is empty".into(),
            }
            .into());
        }

        let (rec, voice) = Self::resolve_model_voice(&opts.model, &opts.voice)?;
        if text.chars().count() > rec.max_text_chars {
            return Err(UserError::Other {
                message: format!(
                    "TTS text exceeds OpenRouter model limit ({} chars)",
                    rec.max_text_chars
                ),
            }
            .into());
        }

        // Intersect Aurum global rate range with model limits.
        if !opts.speaking_rate.is_finite()
            || opts.speaking_rate < SPEAKING_RATE_MIN
            || opts.speaking_rate > SPEAKING_RATE_MAX
        {
            return Err(UserError::Other {
                message: format!(
                    "speaking rate must be finite in {SPEAKING_RATE_MIN}..={SPEAKING_RATE_MAX}"
                ),
            }
            .into());
        }
        let rate = clamp_speaking_rate(opts.speaking_rate);
        if rate < rec.rate_min || rate > rec.rate_max {
            return Err(UserError::UnsupportedCapability {
                provider: PROVIDER_NAME.into(),
                model: opts.model.clone(),
                reason: format!(
                    "speaking rate {rate} outside model range {}..={}",
                    rec.rate_min, rec.rate_max
                ),
                hint: format!(
                    "use a rate in {}..={} (also within Aurum {}..={})",
                    rec.rate_min, rec.rate_max, SPEAKING_RATE_MIN, SPEAKING_RATE_MAX
                ),
            }
            .into());
        }

        let timeout = Duration::from_millis(opts.timeout_ms.max(1));
        let op =
            OpContext::from_optional_cancel(opts.cancel.clone()).with_deadline_from_now(timeout);
        op.check()?;
        op.emit("tts", "admit");
        let _permit = self.governor.acquire(PermitKind::Remote, Some(&op))?;
        op.check()?;
        op.emit("tts", "request");

        let body = OpenAiSpeechRequest::new(
            &opts.model,
            text,
            &voice,
            SpeechResponseFormat::Pcm,
            Some(rate),
        );
        let json = body.to_json_bytes().map_err(|e| ProviderError::Other {
            message: format!("speech request serialize: {e}"),
        })?;

        let response = send_with_op(
            self.http
                .request(reqwest::Method::POST, "audio/speech", self.api_key.expose())?
                .header("Content-Type", "application/json")
                .body(json),
            &op,
            PROVIDER_NAME,
        )
        .await?;

        op.check()?;
        let status = response.status();
        let content_type = response
            .headers()
            .get(reqwest::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();

        op.emit("tts", "read_body");
        let body_cap = if status.is_success() {
            RemoteAudioLimits::default().max_encoded_bytes
        } else {
            64 * 1024
        };
        let bytes = read_body_limited_with_op(
            response,
            PROVIDER_NAME,
            RemoteBodyLimits {
                max_bytes: body_cap,
            },
            &op,
        )
        .await?;
        op.check()?;
        // Never echo response body text; status mapping is allowlisted only.
        map_http_status(PROVIDER_NAME, status, "")?;

        let expected = ExpectedWireFormat::pcm(rec.default_sample_rate_hz, 1);
        let format = resolve_encoded_format(PROVIDER_NAME, expected, &content_type, &bytes)?;
        let bounded = BoundedAudioBody::try_from_bytes(
            bytes,
            RemoteAudioLimits::default().max_encoded_bytes,
            PROVIDER_NAME,
        )?;
        op.emit("tts", "normalize");
        let norm = normalize_remote_audio(
            bounded,
            format,
            RemoteAudioLimits::default(),
            &op,
            PROVIDER_NAME,
        )
        .await?;

        Ok(SynthesisResult {
            pcm_i16_mono: norm.pcm_i16_mono,
            sample_rate_hz: norm.sample_rate_hz,
            channels: 1,
            backend_kind: BackendKind::Remote,
            provider: PROVIDER_NAME.into(),
            model: opts.model.clone(),
            voice,
            language: opts.language.clone(),
            duration_ms: norm.duration_ms,
            text_chars: text.chars().count(),
            text_truncated: false,
            chunk_count: 1,
            synthesized_chars: text.chars().count(),
            adapter: None,
            trust: None,
            provenance: None,
        })
    }

    async fn preload(&self, _model: &str, _voice: &str) -> Result<()> {
        // Remote TTS has no local preload.
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use wiremock::matchers::{header, method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    #[test]
    fn registry_lookup() {
        assert!(lookup_openrouter_tts(DEFAULT_OPENROUTER_TTS_MODEL).is_some());
        assert!(lookup_openrouter_tts("not-a-real-model").is_none());
        // Undated bare id is not accepted (JOE-1978).
        assert!(lookup_openrouter_tts("openai/gpt-4o-mini-tts").is_none());
        let def = lookup_openrouter_tts(DEFAULT_OPENROUTER_TTS_MODEL).unwrap();
        assert_eq!(def.tier, OpenRouterTtsTier::Experimental);
        assert!(openrouter_tts_model_in_discovery(
            "mistralai/voxtral-mini-tts-2603",
            &["mistralai/voxtral-mini-tts-2603"]
        ));
    }

    #[test]
    fn rejects_local_voice_aliases() {
        let err = OpenRouterTtsProvider::resolve_model_voice(DEFAULT_OPENROUTER_TTS_MODEL, "Luna")
            .unwrap_err();
        assert!(err.to_string().contains("voice") || err.to_string().contains("Luna"));
    }

    #[tokio::test]
    async fn mock_pcm_speech_success() {
        let server = MockServer::start().await;
        // 100 ms @ 24 kHz mono s16le
        let n = 2_400;
        let mut pcm = Vec::with_capacity(n * 2);
        for i in 0..n {
            let s = ((i % 50) as i16) * 20;
            pcm.extend_from_slice(&s.to_le_bytes());
        }
        Mock::given(method("POST"))
            .and(path("/audio/speech"))
            .and(header("Authorization", "Bearer sk-test"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("Content-Type", "audio/pcm;rate=24000;channels=1")
                    .set_body_bytes(pcm),
            )
            .mount(&server)
            .await;

        let provider = OpenRouterTtsProvider::with_policy(
            Some("sk-test".into()),
            Some(server.uri()),
            RemotePolicy {
                allow_loopback_http: true,
                allow_custom_credentialed_endpoint: true,
                ..Default::default()
            },
        )
        .unwrap();

        let result = provider
            .synthesize(
                "Hello from OpenRouter",
                &SynthesisOptions {
                    model: DEFAULT_OPENROUTER_TTS_MODEL.into(),
                    voice: "alloy".into(),
                    language: "en".into(),
                    sample_rate_hz: None,
                    speaking_rate: 1.0,
                    timeout_ms: 30_000,
                    cancel: None,
                    local_only: false,
                    pack_dir: None,
                    allow_unverified: false,
                },
            )
            .await
            .unwrap();

        assert_eq!(result.backend_kind, BackendKind::Remote);
        assert_eq!(result.provider, "openrouter");
        assert_eq!(result.voice, "alloy");
        assert_eq!(result.sample_rate_hz, 24_000);
        assert_eq!(result.pcm_i16_mono.len(), n);
        assert!(result.duration_ms >= 90 && result.duration_ms <= 110);
        assert!(result.adapter.is_none());
        assert!(result.trust.is_none());
    }

    #[tokio::test]
    async fn local_only_rejects_before_network() {
        let provider = OpenRouterTtsProvider::with_policy(
            Some("sk-test".into()),
            None,
            RemotePolicy::default(),
        )
        .unwrap();
        let err = provider
            .synthesize(
                "hi",
                &SynthesisOptions {
                    model: DEFAULT_OPENROUTER_TTS_MODEL.into(),
                    voice: "alloy".into(),
                    language: "en".into(),
                    sample_rate_hz: None,
                    speaking_rate: 1.0,
                    timeout_ms: 5_000,
                    cancel: None,
                    local_only: true,
                    pack_dir: None,
                    allow_unverified: false,
                },
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("local_only") || err.to_string().contains("remote"));
    }
}