brokk-mj-controller 2.6.0

Daemon-side controller, session manager, and web server for Mjolnir
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
//! Shared subscription-backed web and native prompt dictation support.
//!
//! Shared credential discovery is kept in `mj_client` because both the terminal
//! chat and authenticated web server need the same decision about which Codex
//! profile may transcribe audio. HTTP handlers send typed requests here;
//! filesystem access and the provider call stay off the controller event loop.

use std::path::PathBuf;
use std::time::Duration;

use anvil_client::codex_client::CodexClient;
use anvil_client::transcribe::TranscribeRequest;
use axum::body::Bytes;
use tokio::sync::oneshot;
use tokio_util::sync::CancellationToken;

pub use mj_client::auth::{auth_paths, available_auth};

/// Maximum complete WAV upload accepted by the web endpoint.
pub const MAX_AUDIO_BYTES: usize = 20 * 1024 * 1024;
/// Maximum audio duration accepted by the web endpoint.
pub const MAX_AUDIO_DURATION: Duration = Duration::from_secs(600);
/// Maximum audio bytes in 16 kHz mono PCM16. This is stricter than the whole
/// RIFF envelope limit and avoids accepting a file whose header claims a
/// shorter duration than its sample payload actually contains.
const MAX_PCM_DATA_BYTES: u64 = 16_000 * 2 * MAX_AUDIO_DURATION.as_secs();
/// Whole-request deadline for credential inspection and provider work.
pub const DICTATION_TIMEOUT: Duration = Duration::from_secs(120);

/// An operation submitted by an authenticated HTTP surface.
#[derive(Debug)]
pub enum DictationOperation {
    /// Probe the selected session's profile set without contacting the provider.
    Availability,
    /// Validate and transcribe one complete WAV upload.
    Transcribe(Bytes),
}

/// A request crossing the HTTP/controller boundary.
#[derive(Debug)]
pub struct DictationRequest {
    pub session_id: String,
    pub operation: DictationOperation,
    pub cancel: CancellationToken,
    pub reply: oneshot::Sender<Result<DictationResponse, DictationError>>,
}

/// Result returned to an HTTP handler.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DictationResponse {
    Availability {
        available: bool,
        reason: Option<String>,
    },
    Transcript {
        text: String,
    },
}

/// Errors that cross the controller boundary. Provider details are retained
/// for logs and diagnostics, while the HTTP layer maps them to safe messages.
#[derive(Debug)]
pub enum DictationError {
    SessionNotFound,
    CredentialsUnavailable,
    InvalidAudio(&'static str),
    Cancelled,
    TimedOut,
    CredentialProbe,
    Provider(String),
}

impl std::fmt::Display for DictationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SessionNotFound => formatter.write_str("unknown session"),
            Self::CredentialsUnavailable => {
                formatter.write_str("no Codex subscription credentials are available")
            }
            Self::InvalidAudio(message) => write!(formatter, "invalid WAV audio: {message}"),
            Self::Cancelled => formatter.write_str("dictation was cancelled"),
            Self::TimedOut => formatter.write_str("dictation timed out"),
            Self::CredentialProbe => formatter.write_str("could not inspect dictation credentials"),
            Self::Provider(message) => {
                write!(formatter, "transcription provider failed: {message}")
            }
        }
    }
}

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

/// Validate a complete RIFF/WAVE file before any credentials or provider work
/// is started. Unknown chunks are allowed, but every chunk length and padding
/// byte must fit inside the declared RIFF envelope.
pub fn validate_wav(audio: &Bytes) -> Result<(), DictationError> {
    validate_wav_bytes(audio)
}

fn validate_wav_bytes(audio: &[u8]) -> Result<(), DictationError> {
    if audio.is_empty() {
        return Err(DictationError::InvalidAudio(
            "audio upload must not be empty",
        ));
    }
    if audio.len() > MAX_AUDIO_BYTES {
        return Err(DictationError::InvalidAudio("audio upload is too large"));
    }
    if audio.len() < 12 || &audio[..4] != b"RIFF" || &audio[8..12] != b"WAVE" {
        return Err(DictationError::InvalidAudio("expected a RIFF/WAVE file"));
    }
    let declared_size = u32::from_le_bytes(audio[4..8].try_into().unwrap()) as usize;
    if declared_size != audio.len().saturating_sub(8) {
        return Err(DictationError::InvalidAudio(
            "RIFF length does not match the upload",
        ));
    }

    let mut cursor = 12_usize;
    let mut fmt_seen = false;
    let mut data_bytes = 0_u64;
    let mut data_seen = false;
    while cursor < audio.len() {
        if audio.len() - cursor < 8 {
            return Err(DictationError::InvalidAudio("truncated WAV chunk header"));
        }
        let id = &audio[cursor..cursor + 4];
        let chunk_size = u32::from_le_bytes(
            audio[cursor + 4..cursor + 8]
                .try_into()
                .expect("WAV chunk size is four bytes"),
        ) as usize;
        let data_start = cursor + 8;
        let data_end = data_start
            .checked_add(chunk_size)
            .ok_or(DictationError::InvalidAudio("WAV chunk length overflows"))?;
        let padded_end = data_end
            .checked_add(chunk_size & 1)
            .ok_or(DictationError::InvalidAudio("WAV chunk padding overflows"))?;
        if data_end > audio.len() || padded_end > audio.len() {
            return Err(DictationError::InvalidAudio("truncated WAV chunk data"));
        }
        match id {
            b"fmt " => {
                if fmt_seen || chunk_size < 16 {
                    return Err(DictationError::InvalidAudio("invalid WAV format chunk"));
                }
                fmt_seen = true;
                let format =
                    u16::from_le_bytes(audio[data_start..data_start + 2].try_into().unwrap());
                let channels =
                    u16::from_le_bytes(audio[data_start + 2..data_start + 4].try_into().unwrap());
                let rate =
                    u32::from_le_bytes(audio[data_start + 4..data_start + 8].try_into().unwrap());
                let bytes_per_second =
                    u32::from_le_bytes(audio[data_start + 8..data_start + 12].try_into().unwrap());
                let alignment =
                    u16::from_le_bytes(audio[data_start + 12..data_start + 14].try_into().unwrap());
                let bits =
                    u16::from_le_bytes(audio[data_start + 14..data_start + 16].try_into().unwrap());
                if format != 1
                    || channels != 1
                    || rate != 16_000
                    || alignment != 2
                    || bits != 16
                    || bytes_per_second != 32_000
                {
                    return Err(DictationError::InvalidAudio(
                        "WAV must be mono 16-bit PCM at 16 kHz",
                    ));
                }
            }
            b"data" => {
                if data_seen || !chunk_size.is_multiple_of(2) {
                    return Err(DictationError::InvalidAudio(
                        "WAV PCM data is not one even-sized sample chunk",
                    ));
                }
                data_seen = true;
                data_bytes = data_bytes
                    .checked_add(chunk_size as u64)
                    .ok_or(DictationError::InvalidAudio("WAV sample length overflows"))?;
            }
            _ => {}
        }
        cursor = padded_end;
    }
    if !fmt_seen {
        return Err(DictationError::InvalidAudio("WAV format chunk is missing"));
    }
    if data_bytes == 0 {
        return Err(DictationError::InvalidAudio("WAV sample data is missing"));
    }
    if data_bytes > MAX_PCM_DATA_BYTES {
        return Err(DictationError::InvalidAudio(
            "audio duration exceeds 600 seconds",
        ));
    }
    Ok(())
}

/// Execute one request. This future is supervised by the controller's
/// `JoinSet`; no provider task is detached when the HTTP client disconnects or
/// the daemon shuts down.
pub async fn execute(
    request: DictationRequest,
    auth_paths: Option<Vec<PathBuf>>,
    shutdown: CancellationToken,
) {
    let DictationRequest {
        session_id: _,
        operation,
        cancel,
        mut reply,
    } = request;
    let result = tokio::select! {
        biased;
        _ = reply.closed() => return,
        _ = shutdown.cancelled() => Err(DictationError::Cancelled),
        _ = cancel.cancelled() => Err(DictationError::Cancelled),
        result = tokio::time::timeout(DICTATION_TIMEOUT, execute_operation(operation, auth_paths, cancel.clone())) => {
            result.unwrap_or(Err(DictationError::TimedOut))
        },
    };
    let _ = reply.send(result);
}

async fn execute_operation(
    operation: DictationOperation,
    auth_paths: Option<Vec<PathBuf>>,
    cancel: CancellationToken,
) -> Result<DictationResponse, DictationError> {
    let paths = auth_paths.ok_or(DictationError::SessionNotFound)?;
    let audio = match &operation {
        DictationOperation::Transcribe(audio) => Some(audio.clone()),
        DictationOperation::Availability => None,
    };
    let probe = tokio::task::spawn_blocking(move || {
        if let Some(audio) = audio {
            validate_wav(&audio)?;
        }
        Ok::<_, DictationError>(available_auth(paths))
    });
    let auth_path = tokio::select! {
        biased;
        _ = cancel.cancelled() => return Err(DictationError::Cancelled),
        result = probe => result.map_err(|error| {
            tracing::warn!(%error, "Codex dictation credential probe task failed");
            DictationError::CredentialProbe
        })??,
    };

    match operation {
        DictationOperation::Availability => Ok(DictationResponse::Availability {
            available: auth_path.is_some(),
            reason: auth_path
                .is_none()
                .then(|| "no Codex subscription credentials are available".to_owned()),
        }),
        DictationOperation::Transcribe(audio) => {
            let auth_path = auth_path.ok_or(DictationError::CredentialsUnavailable)?;
            let mut request = TranscribeRequest::new(audio, "audio.wav", "audio/wav");
            request.cancel = cancel.clone();
            request.timeout = DICTATION_TIMEOUT;
            let transcription = CodexClient::with_auth_path(auth_path)
                .transcribe(request)
                .await
                .map_err(|error| {
                    let message = error.to_string();
                    if message.to_ascii_lowercase().contains("timed out") {
                        DictationError::TimedOut
                    } else if cancel.is_cancelled() {
                        DictationError::Cancelled
                    } else {
                        DictationError::Provider(message)
                    }
                })?;
            Ok(DictationResponse::Transcript {
                text: transcription.text,
            })
        }
    }
}

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

    fn wav(sample_bytes: usize) -> Bytes {
        let padded = sample_bytes + (sample_bytes & 1);
        let riff_size = 36 + padded;
        let mut bytes = Vec::with_capacity(8 + riff_size);
        bytes.extend_from_slice(b"RIFF");
        bytes.extend_from_slice(&(riff_size as u32).to_le_bytes());
        bytes.extend_from_slice(b"WAVEfmt ");
        bytes.extend_from_slice(&16_u32.to_le_bytes());
        bytes.extend_from_slice(&1_u16.to_le_bytes());
        bytes.extend_from_slice(&1_u16.to_le_bytes());
        bytes.extend_from_slice(&16_000_u32.to_le_bytes());
        bytes.extend_from_slice(&32_000_u32.to_le_bytes());
        bytes.extend_from_slice(&2_u16.to_le_bytes());
        bytes.extend_from_slice(&16_u16.to_le_bytes());
        bytes.extend_from_slice(b"data");
        bytes.extend_from_slice(&(sample_bytes as u32).to_le_bytes());
        bytes.resize(bytes.len() + sample_bytes, 0);
        if sample_bytes & 1 != 0 {
            bytes.push(0);
        }
        Bytes::from(bytes)
    }

    #[test]
    fn accepts_wav_with_unknown_padded_chunk() {
        let mut audio = wav(64).to_vec();
        audio.splice(12..12, b"JUNK\x01\x00\x00\x00x\x00".iter().copied());
        let size = audio.len() - 8;
        audio[4..8].copy_from_slice(&(size as u32).to_le_bytes());
        assert!(validate_wav(&Bytes::from(audio)).is_ok());
    }

    #[test]
    fn rejects_truncated_and_wrong_format_audio() {
        assert!(matches!(
            validate_wav(&Bytes::from_static(b"RIFF")),
            Err(DictationError::InvalidAudio(_))
        ));
        let mut audio = wav(64).to_vec();
        audio[22..24].copy_from_slice(&2_u16.to_le_bytes());
        assert!(matches!(
            validate_wav(&Bytes::from(audio)),
            Err(DictationError::InvalidAudio(_))
        ));
    }

    #[test]
    fn rejects_data_longer_than_six_hundred_seconds() {
        let audio = wav((MAX_PCM_DATA_BYTES + 2) as usize);
        assert!(matches!(
            validate_wav(&audio),
            Err(DictationError::InvalidAudio(_))
        ));
    }

    #[tokio::test]
    async fn availability_and_transcription_without_credentials_do_not_call_provider() {
        for operation in [
            DictationOperation::Availability,
            DictationOperation::Transcribe(wav(96_000)),
        ] {
            let availability = matches!(operation, DictationOperation::Availability);
            let (reply, answer) = oneshot::channel();
            execute(
                DictationRequest {
                    session_id: "session".into(),
                    operation,
                    cancel: CancellationToken::new(),
                    reply,
                },
                Some(vec![]),
                CancellationToken::new(),
            )
            .await;
            let result = answer.await.unwrap();
            if availability {
                assert!(matches!(
                    result,
                    Ok(DictationResponse::Availability {
                        available: false,
                        reason: Some(_)
                    })
                ));
            } else {
                assert!(matches!(
                    result,
                    Err(DictationError::CredentialsUnavailable)
                ));
            }
        }
    }

    #[tokio::test]
    async fn shutdown_and_request_cancellation_preempt_credential_work() {
        for shutdown_cancelled in [false, true] {
            let cancel = CancellationToken::new();
            let shutdown = CancellationToken::new();
            if shutdown_cancelled {
                shutdown.cancel();
            } else {
                cancel.cancel();
            }
            let (reply, answer) = oneshot::channel();
            execute(
                DictationRequest {
                    session_id: "session".into(),
                    operation: DictationOperation::Availability,
                    cancel,
                    reply,
                },
                None,
                shutdown,
            )
            .await;
            assert!(matches!(
                answer.await.unwrap(),
                Err(DictationError::Cancelled)
            ));
        }
    }

    #[test]
    fn duplicate_or_odd_data_chunks_and_wrong_riff_lengths_are_rejected() {
        let mut duplicate = wav(2).to_vec();
        duplicate.extend_from_slice(b"data\x02\x00\x00\x00\x00\x00");
        let length = duplicate.len() as u32 - 8;
        duplicate[4..8].copy_from_slice(&length.to_le_bytes());
        assert!(validate_wav(&Bytes::from(duplicate)).is_err());
        assert!(validate_wav(&wav(3)).is_err());
        let mut wrong_length = wav(2).to_vec();
        wrong_length[4..8].copy_from_slice(&0_u32.to_le_bytes());
        assert!(validate_wav(&Bytes::from(wrong_length)).is_err());
        assert!(validate_wav(&wav(MAX_PCM_DATA_BYTES as usize)).is_ok());
    }
}