rustvani 0.1.0

Voice AI framework for Rust — real-time speech pipelines with STT, LLM, TTS, and Dhara conversation flows
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
pub mod direction;
pub mod processor;
pub mod queue;

pub use direction::FrameDirection;
pub use processor::{
    FrameCallback, FrameHandler, FrameProcessor, FrameProcessorSetup, PassthroughHandler,
    WeakFrameProcessor,
};

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

// ---------------------------------------------------------------------------
// Frame ID counter
// ---------------------------------------------------------------------------

static FRAME_ID_COUNTER: AtomicU64 = AtomicU64::new(1);

pub fn next_frame_id() -> u64 {
    FRAME_ID_COUNTER.fetch_add(1, Ordering::Relaxed)
}

// ---------------------------------------------------------------------------
// Flat FrameKind
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FrameKind {
    // System — lifecycle
    Start, Cancel, Error, Interruption, Stop,
    EndTask, CancelTask, StopTask, InterruptionTask,
    // System — speaking signals
    BotSpeaking, UserSpeaking,
    BotStartedSpeaking, BotStoppedSpeaking,
    UserStartedSpeaking, UserStoppedSpeaking,
    VADUserStartedSpeaking, VADUserStoppedSpeaking,
    // System — audio/video input
    InputAudioRaw,
    // System — processor control
    PauseProcessor, PauseProcessorUrgent,
    ResumeProcessor, ResumeProcessorUrgent,
    Heartbeat,
    // System — RAVI protocol
    RaviClientMessage,
    RaviServerMessage,
    RaviServerResponse,
    // Control — pipeline lifecycle
    End,
    // Control — LLM response boundaries
    LLMFullResponseStart,
    LLMFullResponseEnd,
    // Control — function call boundaries
    FunctionCallStart,
    FunctionCallEnd,
    // Data
    Data,
    Transcription,
    LLMText,
    LLMContextFrame,
    // Data — function calling
    FunctionCallInProgress,
    FunctionCallResult,
    /// Raw structured data from a data tool — full payload, not summarised.
    /// Downstream processors (loggers, UI aggregators) consume this.
    /// The LLM never sees this — it gets only the summary via FunctionCallResult.
    FunctionCallRawResult,
    // Data — audio output
    OutputAudioRaw,
}

// ---------------------------------------------------------------------------
// Audio payload
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct AudioRawData {
    pub audio:            Vec<u8>,
    pub sample_rate:      u32,
    pub num_channels:     u16,
    pub num_frames:       usize,
    pub transport_source: Option<String>,
}

impl AudioRawData {
    pub fn new(audio: Vec<u8>, sample_rate: u32, num_channels: u16) -> Self {
        let num_frames = if num_channels > 0 {
            audio.len() / (num_channels as usize * 2)
        } else {
            0
        };
        Self { audio, sample_rate, num_channels, num_frames, transport_source: None }
    }

    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.transport_source = Some(source.into());
        self
    }
}

// ---------------------------------------------------------------------------
// Payloads
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Default)]
pub struct StartFrameData {
    pub allow_interruptions:       bool,
    pub enable_metrics:            bool,
    pub enable_usage_metrics:      bool,
    pub report_only_initial_ttfb:  bool,
    pub metadata: HashMap<String, String>,
}

#[derive(Debug, Clone)]
pub struct ErrorFrameData {
    pub error:          String,
    pub fatal:          bool,
    pub processor_name: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct DataFrameData {
    pub content:  Vec<u8>,
    pub metadata: HashMap<String, String>,
}

#[derive(Debug, Clone)]
pub struct TranscriptionData {
    pub text:      String,
    pub user_id:   String,
    pub timestamp: String,
    pub language:  Option<String>,
    pub finalized: bool,
}

impl TranscriptionData {
    pub fn new(text: impl Into<String>, user_id: impl Into<String>, timestamp: impl Into<String>) -> Self {
        Self { text: text.into(), user_id: user_id.into(), timestamp: timestamp.into(), language: None, finalized: false }
    }
    pub fn with_language(mut self, lang: impl Into<String>) -> Self { self.language = Some(lang.into()); self }
    pub fn finalized(mut self) -> Self { self.finalized = true; self }
}

/// Payload for FunctionCallInProgressFrame — the model wants to invoke a tool.
#[derive(Debug, Clone)]
pub struct FunctionCallData {
    /// Unique call ID assigned by the model (e.g. `"call_abc123"`).
    pub id: String,
    /// Name of the function to invoke.
    pub function_name: String,
    /// Raw JSON string of the function arguments.
    pub arguments: String,
}

/// Payload for FunctionCallResultFrame — tool execution result.
///
/// Carries the *summary* string that goes into LLM context.
/// For the full raw payload, see `FunctionCallRawResultData`.
#[derive(Debug, Clone)]
pub struct FunctionCallResultData {
    /// Matches the `id` of the `FunctionCallData` this responds to.
    pub id: String,
    /// Name of the function that was called.
    pub function_name: String,
    /// Summarised result — what the LLM sees in context.
    pub result: String,
}

/// Payload for FunctionCallRawResultFrame — full structured data from a data tool.
///
/// Emitted *alongside* `FunctionCallResultFrame` when a data tool returns
/// `full_data: Some(value)`. The LLM never sees this — only the summary in
/// `FunctionCallResultFrame` goes into context. Downstream processors
/// (loggers, UI, storage sinks) consume this frame.
#[derive(Debug, Clone)]
pub struct FunctionCallRawResultData {
    /// Matches the `id` of the originating `FunctionCallData`.
    pub id: String,
    /// Name of the function that was called.
    pub function_name: String,
    /// Full structured output from the tool handler.
    pub raw_data: serde_json::Value,
}

// ---------------------------------------------------------------------------
// SystemFrame
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub enum SystemFrame {
    // ---- Lifecycle ----
    Start(StartFrameData),
    Cancel    { reason: Option<String> },
    Error(ErrorFrameData),
    Interruption,
    Stop      { reason: Option<String> },

    EndTask   { reason: Option<String> },
    CancelTask { reason: Option<String> },
    StopTask,
    InterruptionTask,

    // ---- Speaking signals ----
    BotSpeaking,
    UserSpeaking,
    BotStartedSpeaking,
    BotStoppedSpeaking,
    UserStartedSpeaking { emulated: bool },
    UserStoppedSpeaking  { emulated: bool },
    VADUserStartedSpeaking { start_secs: f32, timestamp: f64 },
    VADUserStoppedSpeaking { stop_secs: f32, timestamp: f64 },

    // ---- Audio input ----
    InputAudioRaw(AudioRawData),

    // ---- Processor control ----
    PauseProcessor        { name: String },
    PauseProcessorUrgent  { name: String },
    ResumeProcessor       { name: String },
    ResumeProcessorUrgent { name: String },

    // ---- Pipeline health probe ----
    Heartbeat(f64),

    // ---- RAVI protocol ----
    RaviClientMessage {
        msg_id:   String,
        msg_type: String,
        data:     Option<String>,
    },
    RaviServerMessage {
        payload: String,
    },
    RaviServerResponse {
        client_msg_id: String,
        payload:       String,
    },
}

// ---------------------------------------------------------------------------
// ControlFrame / DataFrame
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub enum ControlFrame {
    End { reason: Option<String> },
    LLMFullResponseStart,
    LLMFullResponseEnd,
    /// Signals that the model returned tool calls — execution is starting.
    FunctionCallStart,
    /// Signals that all tool calls for this turn have been executed.
    FunctionCallEnd,
}

#[derive(Debug, Clone)]
pub enum DataFrame {
    Data(DataFrameData),
    OutputAudioRaw(AudioRawData),
    Transcription(TranscriptionData),
    LLMText(String),
    LLMContextFrame(Arc<Mutex<crate::context::LLMContext>>),
    /// Model wants to invoke a tool — downstream observers can show "thinking…"
    FunctionCallInProgress(FunctionCallData),
    /// Tool execution summary — what goes into LLM context.
    FunctionCallResult(FunctionCallResultData),
    /// Full raw structured data from a data tool — LLM never sees this.
    FunctionCallRawResult(FunctionCallRawResultData),
}

#[derive(Debug, Clone)]
pub enum FrameInner {
    System(SystemFrame),
    Control(ControlFrame),
    Data(DataFrame),
}

// ---------------------------------------------------------------------------
// Frame
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct Frame {
    pub id:         u64,
    pub sibling_id: Option<u64>,
    pub inner:      FrameInner,
}

// ---------------------------------------------------------------------------
// Core accessors
// ---------------------------------------------------------------------------

impl Frame {
    pub fn name(&self) -> &'static str {
        match &self.inner {
            FrameInner::System(s) => match s {
                SystemFrame::Start(_)                      => "StartFrame",
                SystemFrame::Cancel { .. }                 => "CancelFrame",
                SystemFrame::Error(_)                      => "ErrorFrame",
                SystemFrame::Interruption                  => "InterruptionFrame",
                SystemFrame::Stop { .. }                   => "StopFrame",
                SystemFrame::EndTask { .. }                => "EndTaskFrame",
                SystemFrame::CancelTask { .. }             => "CancelTaskFrame",
                SystemFrame::StopTask                      => "StopTaskFrame",
                SystemFrame::InterruptionTask              => "InterruptionTaskFrame",
                SystemFrame::BotSpeaking                   => "BotSpeakingFrame",
                SystemFrame::UserSpeaking                  => "UserSpeakingFrame",
                SystemFrame::BotStartedSpeaking            => "BotStartedSpeakingFrame",
                SystemFrame::BotStoppedSpeaking            => "BotStoppedSpeakingFrame",
                SystemFrame::UserStartedSpeaking { .. }    => "UserStartedSpeakingFrame",
                SystemFrame::UserStoppedSpeaking { .. }    => "UserStoppedSpeakingFrame",
                SystemFrame::VADUserStartedSpeaking { .. } => "VADUserStartedSpeakingFrame",
                SystemFrame::VADUserStoppedSpeaking { .. } => "VADUserStoppedSpeakingFrame",
                SystemFrame::InputAudioRaw(_)              => "InputAudioRawFrame",
                SystemFrame::PauseProcessor { .. }         => "PauseProcessorFrame",
                SystemFrame::PauseProcessorUrgent { .. }   => "PauseProcessorUrgentFrame",
                SystemFrame::ResumeProcessor { .. }        => "ResumeProcessorFrame",
                SystemFrame::ResumeProcessorUrgent { .. }  => "ResumeProcessorUrgentFrame",
                SystemFrame::Heartbeat(_)                  => "HeartbeatFrame",
                SystemFrame::RaviClientMessage { .. }      => "RaviClientMessageFrame",
                SystemFrame::RaviServerMessage { .. }      => "RaviServerMessageFrame",
                SystemFrame::RaviServerResponse { .. }     => "RaviServerResponseFrame",
            },
            FrameInner::Control(c) => match c {
                ControlFrame::End { .. }           => "EndFrame",
                ControlFrame::LLMFullResponseStart => "LLMFullResponseStartFrame",
                ControlFrame::LLMFullResponseEnd   => "LLMFullResponseEndFrame",
                ControlFrame::FunctionCallStart    => "FunctionCallStartFrame",
                ControlFrame::FunctionCallEnd      => "FunctionCallEndFrame",
            },
            FrameInner::Data(d) => match d {
                DataFrame::Data(_)                     => "DataFrame",
                DataFrame::OutputAudioRaw(_)           => "OutputAudioRawFrame",
                DataFrame::Transcription(_)            => "TranscriptionFrame",
                DataFrame::LLMText(_)                  => "LLMTextFrame",
                DataFrame::LLMContextFrame(_)          => "LLMContextFrame",
                DataFrame::FunctionCallInProgress(_)   => "FunctionCallInProgressFrame",
                DataFrame::FunctionCallResult(_)       => "FunctionCallResultFrame",
                DataFrame::FunctionCallRawResult(_)    => "FunctionCallRawResultFrame",
            },
        }
    }

    pub fn kind(&self) -> FrameKind {
        match &self.inner {
            FrameInner::System(s) => match s {
                SystemFrame::Start(_)                      => FrameKind::Start,
                SystemFrame::Cancel { .. }                 => FrameKind::Cancel,
                SystemFrame::Error(_)                      => FrameKind::Error,
                SystemFrame::Interruption                  => FrameKind::Interruption,
                SystemFrame::Stop { .. }                   => FrameKind::Stop,
                SystemFrame::EndTask { .. }                => FrameKind::EndTask,
                SystemFrame::CancelTask { .. }             => FrameKind::CancelTask,
                SystemFrame::StopTask                      => FrameKind::StopTask,
                SystemFrame::InterruptionTask              => FrameKind::InterruptionTask,
                SystemFrame::BotSpeaking                   => FrameKind::BotSpeaking,
                SystemFrame::UserSpeaking                  => FrameKind::UserSpeaking,
                SystemFrame::BotStartedSpeaking            => FrameKind::BotStartedSpeaking,
                SystemFrame::BotStoppedSpeaking            => FrameKind::BotStoppedSpeaking,
                SystemFrame::UserStartedSpeaking { .. }    => FrameKind::UserStartedSpeaking,
                SystemFrame::UserStoppedSpeaking { .. }    => FrameKind::UserStoppedSpeaking,
                SystemFrame::VADUserStartedSpeaking { .. } => FrameKind::VADUserStartedSpeaking,
                SystemFrame::VADUserStoppedSpeaking { .. } => FrameKind::VADUserStoppedSpeaking,
                SystemFrame::InputAudioRaw(_)              => FrameKind::InputAudioRaw,
                SystemFrame::PauseProcessor { .. }         => FrameKind::PauseProcessor,
                SystemFrame::PauseProcessorUrgent { .. }   => FrameKind::PauseProcessorUrgent,
                SystemFrame::ResumeProcessor { .. }        => FrameKind::ResumeProcessor,
                SystemFrame::ResumeProcessorUrgent { .. }  => FrameKind::ResumeProcessorUrgent,
                SystemFrame::Heartbeat(_)                  => FrameKind::Heartbeat,
                SystemFrame::RaviClientMessage { .. }      => FrameKind::RaviClientMessage,
                SystemFrame::RaviServerMessage { .. }      => FrameKind::RaviServerMessage,
                SystemFrame::RaviServerResponse { .. }     => FrameKind::RaviServerResponse,
            },
            FrameInner::Control(c) => match c {
                ControlFrame::End { .. }           => FrameKind::End,
                ControlFrame::LLMFullResponseStart => FrameKind::LLMFullResponseStart,
                ControlFrame::LLMFullResponseEnd   => FrameKind::LLMFullResponseEnd,
                ControlFrame::FunctionCallStart    => FrameKind::FunctionCallStart,
                ControlFrame::FunctionCallEnd      => FrameKind::FunctionCallEnd,
            },
            FrameInner::Data(d) => match d {
                DataFrame::Data(_)                     => FrameKind::Data,
                DataFrame::OutputAudioRaw(_)           => FrameKind::OutputAudioRaw,
                DataFrame::Transcription(_)            => FrameKind::Transcription,
                DataFrame::LLMText(_)                  => FrameKind::LLMText,
                DataFrame::LLMContextFrame(_)          => FrameKind::LLMContextFrame,
                DataFrame::FunctionCallInProgress(_)   => FrameKind::FunctionCallInProgress,
                DataFrame::FunctionCallResult(_)       => FrameKind::FunctionCallResult,
                DataFrame::FunctionCallRawResult(_)    => FrameKind::FunctionCallRawResult,
            },
        }
    }

    pub fn is_system(&self) -> bool {
        matches!(self.inner, FrameInner::System(_))
    }

    pub fn is_uninterruptible(&self) -> bool {
        matches!(
            &self.inner,
            FrameInner::Control(ControlFrame::End { .. })
                | FrameInner::System(SystemFrame::EndTask { .. })
                | FrameInner::System(SystemFrame::StopTask)
                | FrameInner::System(SystemFrame::CancelTask { .. })
        )
    }
}

// ---------------------------------------------------------------------------
// Mutation helpers
// ---------------------------------------------------------------------------

impl Frame {
    pub fn with_new_id(self) -> Self { Self { id: next_frame_id(), ..self } }
    pub fn with_sibling(self, sibling_id: u64) -> Self { Self { sibling_id: Some(sibling_id), ..self } }
}

// ---------------------------------------------------------------------------
// Internal constructor
// ---------------------------------------------------------------------------

impl Frame {
    fn make(inner: FrameInner) -> Self {
        Self { id: next_frame_id(), sibling_id: None, inner }
    }
}

// ---------------------------------------------------------------------------
// Public constructors
// ---------------------------------------------------------------------------

impl Frame {
    // ---- Lifecycle ----
    pub fn start(data: StartFrameData) -> Self { Self::make(FrameInner::System(SystemFrame::Start(data))) }
    pub fn cancel() -> Self { Self::make(FrameInner::System(SystemFrame::Cancel { reason: None })) }
    pub fn cancel_with(reason: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::Cancel { reason: Some(reason.into()) }))
    }
    pub fn error(msg: impl Into<String>, fatal: bool, processor: Option<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::Error(ErrorFrameData {
            error: msg.into(), fatal, processor_name: processor,
        })))
    }
    pub fn interruption() -> Self { Self::make(FrameInner::System(SystemFrame::Interruption)) }
    pub fn stop() -> Self { Self::make(FrameInner::System(SystemFrame::Stop { reason: None })) }
    pub fn stop_with(reason: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::Stop { reason: Some(reason.into()) }))
    }
    pub fn end_task() -> Self { Self::make(FrameInner::System(SystemFrame::EndTask { reason: None })) }
    pub fn cancel_task() -> Self { Self::make(FrameInner::System(SystemFrame::CancelTask { reason: None })) }
    pub fn stop_task() -> Self { Self::make(FrameInner::System(SystemFrame::StopTask)) }
    pub fn interruption_task() -> Self { Self::make(FrameInner::System(SystemFrame::InterruptionTask)) }

    // ---- Speaking signals ----
    pub fn bot_speaking() -> Self { Self::make(FrameInner::System(SystemFrame::BotSpeaking)) }
    pub fn user_speaking() -> Self { Self::make(FrameInner::System(SystemFrame::UserSpeaking)) }
    pub fn bot_started_speaking() -> Self { Self::make(FrameInner::System(SystemFrame::BotStartedSpeaking)) }
    pub fn bot_stopped_speaking() -> Self { Self::make(FrameInner::System(SystemFrame::BotStoppedSpeaking)) }
    pub fn user_started_speaking() -> Self {
        Self::make(FrameInner::System(SystemFrame::UserStartedSpeaking { emulated: false }))
    }
    pub fn user_started_speaking_emulated() -> Self {
        Self::make(FrameInner::System(SystemFrame::UserStartedSpeaking { emulated: true }))
    }
    pub fn user_stopped_speaking() -> Self {
        Self::make(FrameInner::System(SystemFrame::UserStoppedSpeaking { emulated: false }))
    }
    pub fn user_stopped_speaking_emulated() -> Self {
        Self::make(FrameInner::System(SystemFrame::UserStoppedSpeaking { emulated: true }))
    }
    pub fn vad_user_started_speaking(start_secs: f32, timestamp: f64) -> Self {
        Self::make(FrameInner::System(SystemFrame::VADUserStartedSpeaking { start_secs, timestamp }))
    }
    pub fn vad_user_stopped_speaking(stop_secs: f32, timestamp: f64) -> Self {
        Self::make(FrameInner::System(SystemFrame::VADUserStoppedSpeaking { stop_secs, timestamp }))
    }

    // ---- Audio ----
    pub fn input_audio_raw(data: AudioRawData) -> Self {
        Self::make(FrameInner::System(SystemFrame::InputAudioRaw(data)))
    }
    pub fn input_audio(audio: Vec<u8>, sample_rate: u32, num_channels: u16) -> Self {
        Self::input_audio_raw(AudioRawData::new(audio, sample_rate, num_channels))
    }
    pub fn output_audio_raw(data: AudioRawData) -> Self {
        Self::make(FrameInner::Data(DataFrame::OutputAudioRaw(data)))
    }
    pub fn output_audio(audio: Vec<u8>, sample_rate: u32, num_channels: u16) -> Self {
        Self::output_audio_raw(AudioRawData::new(audio, sample_rate, num_channels))
    }

    // ---- Processor control ----
    pub fn pause_processor(name: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::PauseProcessor { name: name.into() }))
    }
    pub fn pause_processor_urgent(name: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::PauseProcessorUrgent { name: name.into() }))
    }
    pub fn resume_processor(name: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::ResumeProcessor { name: name.into() }))
    }
    pub fn resume_processor_urgent(name: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::ResumeProcessorUrgent { name: name.into() }))
    }
    pub fn heartbeat(ts: f64) -> Self {
        Self::make(FrameInner::System(SystemFrame::Heartbeat(ts)))
    }

    // ---- Control ----
    pub fn end() -> Self { Self::make(FrameInner::Control(ControlFrame::End { reason: None })) }
    pub fn end_with(reason: impl Into<String>) -> Self {
        Self::make(FrameInner::Control(ControlFrame::End { reason: Some(reason.into()) }))
    }

    // ---- Generic data ----
    pub fn transcription(data: TranscriptionData) -> Self {
        Self::make(FrameInner::Data(DataFrame::Transcription(data)))
    }
    pub fn data(content: Vec<u8>) -> Self {
        Self::make(FrameInner::Data(DataFrame::Data(DataFrameData { content, ..Default::default() })))
    }

    // ---- LLM ----
    pub fn llm_full_response_start() -> Self {
        Self::make(FrameInner::Control(ControlFrame::LLMFullResponseStart))
    }
    pub fn llm_full_response_end() -> Self {
        Self::make(FrameInner::Control(ControlFrame::LLMFullResponseEnd))
    }
    pub fn llm_text(text: String) -> Self {
        Self::make(FrameInner::Data(DataFrame::LLMText(text)))
    }
    pub fn llm_context(context: Arc<Mutex<crate::context::LLMContext>>) -> Self {
        Self::make(FrameInner::Data(DataFrame::LLMContextFrame(context)))
    }

    // ---- Function calling ----
    pub fn function_call_start() -> Self {
        Self::make(FrameInner::Control(ControlFrame::FunctionCallStart))
    }
    pub fn function_call_end() -> Self {
        Self::make(FrameInner::Control(ControlFrame::FunctionCallEnd))
    }
    pub fn function_call_in_progress(data: FunctionCallData) -> Self {
        Self::make(FrameInner::Data(DataFrame::FunctionCallInProgress(data)))
    }
    pub fn function_call_result(data: FunctionCallResultData) -> Self {
        Self::make(FrameInner::Data(DataFrame::FunctionCallResult(data)))
    }
    /// Emit full structured data from a data tool.
    ///
    /// Only pushed when `ToolCallOutput.full_data` is `Some`. The LLM never
    /// sees this frame — it receives only the summary via `function_call_result`.
    pub fn function_call_raw_result(data: FunctionCallRawResultData) -> Self {
        Self::make(FrameInner::Data(DataFrame::FunctionCallRawResult(data)))
    }

    // ---- RAVI protocol ----
    pub fn ravi_client_message(
        msg_id:   impl Into<String>,
        msg_type: impl Into<String>,
        data:     Option<String>,
    ) -> Self {
        Self::make(FrameInner::System(SystemFrame::RaviClientMessage {
            msg_id:   msg_id.into(),
            msg_type: msg_type.into(),
            data,
        }))
    }
    pub fn ravi_server_message(payload: impl Into<String>) -> Self {
        Self::make(FrameInner::System(SystemFrame::RaviServerMessage {
            payload: payload.into(),
        }))
    }
    pub fn ravi_server_response(
        client_msg_id: impl Into<String>,
        payload:       impl Into<String>,
    ) -> Self {
        Self::make(FrameInner::System(SystemFrame::RaviServerResponse {
            client_msg_id: client_msg_id.into(),
            payload:       payload.into(),
        }))
    }
}